<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/staff/staff_details/staff_functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);

// checkIfNoPhpContentsReceive();
// print_R($postdata);die();
if (
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

if (!in_array($role, ['superadmin', 'admin', 'principal'])) {
    errorreturn('Access denied.');
}

// Dynamic DB Connection
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["superadmin", "admin", "principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}


function insertStaffPayrollCategoryData($conn_rjllearning_specific, $institution_id, $branch_id, $staff_id, $payroll_category_id, $recruitment_type) {
    try {
        $stmt = $conn_rjllearning_specific->prepare(
            "INSERT INTO staff_payroll_category_data (institution_id, branch_id, staff_id, payroll_category_id, recruitment_type) 
             VALUES (?, ?, ?, ?, ?)"
        );

        if ($stmt->execute([$institution_id, $branch_id, $staff_id, $payroll_category_id, $recruitment_type])) {
            return $conn_rjllearning_specific->lastInsertId(); // Return last inserted ID
        } else {
            return false;
        }
    } catch (PDOException $e) {
        error_log("Insert Error: " . $e->getMessage());
        return false;
    }
}

// Handle API Function Type
if ($postdata['function_type'] === "insert_staff_payroll_data") {
    $institution_id = $postdata['institution_id'];
    $branch_id = $postdata['branch_id'] ?? "all";
    $staff_id = $postdata['staff_id'];
    $payroll_category_id = $postdata['category_id'];
    $recruitment_type = $postdata['recruitment_type'] ?? 'permanent';

    $insert_id = insertStaffPayrollCategoryData($conn_rjllearning_specific, $institution_id, $branch_id, $staff_id, $payroll_category_id, $recruitment_type);

    if ($insert_id) {
        successreturn(["message" => "Category successfully stored", "insert_id" => $insert_id]);
    } else {
        errorreturn("Failed to store category.");
    }
} else {
    errorreturn("Invalid function type.");
}
