<?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';


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

checkIfNoPhpContentsReceive();
if (!isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])
) {
    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($role == 'principal' or $role == 'teacher'){
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id = $jwt_validate->data->branch_id;
}else{
    $institution_id = $postdata['institution_id'];
    $branch_id = $postdata['branch_id'] ?? "all"; 
}

// 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 fetchSpecificStaffPayrollCategory($conn_rjllearning_specific, $institution_id, $category_id) {
    try {
        // Fetch details of a specific category
        $query = "SELECT * FROM staff_payroll_category_info WHERE institution_id = ? AND id = ?";
        $params = [$institution_id, $category_id];

        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        // If no record found
        if (!$row) {
            return [
                "error" => "No category found for given ID",
                "category_info" => []
            ];
        }

        // Fetch branch info (if applicable)
        $branch_info = ($row['branch_id'] !== 'all') ? getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']) : 'all';

        // Return formatted response
        return [
            'category_id' => $row['id'],
            'institution_id' => $row['institution_id'],
            'branch_id' => $branch_info,
            'group_name' => $row['group_name']
        ];

    } catch (PDOException $e) {
        return [
            "error" => $e->getMessage(),
            "category_info" => []
        ];
    }
}

// Handle API Function Type
if ($postdata['function_type'] === "fetch_specific_staff_payroll_group") {
    $institution_id = $postdata['institution_id'];
    $category_id = $postdata['category_id'];

    if (!$category_id) {
        errorreturn("Category ID is required.");
    } else {
        $response = fetchSpecificStaffPayrollCategory($conn_rjllearning_specific, $institution_id, $category_id);
        successreturn($response);
    }
} else {
    errorreturn("Invalid function type.");
}
