<?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 fetchStaffPayrollData($conn_rjllearning_specific, $institution_id, $branch_id = "all", $limit = "all") {
    try {
        // Count total rows for the given institution_id
        $countQuery = "SELECT COUNT(*) as total FROM staff_payroll_category_data WHERE institution_id = ?";
        $countParams = [$institution_id];

        if ($branch_id !== "all") {
            $countQuery .= " AND branch_id = ?";
            $countParams[] = $branch_id;
        }

        $countStmt = $conn_rjllearning_specific->prepare($countQuery);
        $countStmt->execute($countParams);
        $countResult = $countStmt->fetch(PDO::FETCH_ASSOC);
        $totalrows = $countResult['total'] ?? 0;

        // Fetch records with optional branch_id filtering
        $query = "SELECT * FROM staff_payroll_category_data WHERE institution_id = ?";
        $params = [$institution_id];

        if ($branch_id !== "all") {
            $query .= " AND branch_id = ?";
            $params[] = $branch_id;
        }

        // Apply limit only if it's a valid integer
        if ($limit !== "all" && is_numeric($limit) && (int)$limit > 0) {
            $query .= " LIMIT " . (int)$limit; // Directly add LIMIT value instead of binding it
        }

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

        // Initialize return array
        $array_return = [];

       foreach ($results as $rows) {
    // Fetch branch info
    $branch_info = ($rows['branch_id'] !== "all") 
        ? getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id'])
        : 'all';

    // Fetch category information
    $categoryStmt = $conn_rjllearning_specific->prepare(
        "SELECT id, group_name FROM staff_payroll_category_info WHERE id = ? AND institution_id = ?"
    );
    $categoryStmt->execute([$rows['payroll_category_id'], $institution_id]);
    $categoryInfo = $categoryStmt->fetch(PDO::FETCH_ASSOC);

    // Build response array
    $array_return[] = [
        'institution_id' => $rows['institution_id'],
        'category' => [
            'id' => $categoryInfo['id'] ?? null,
            'group_name' => $categoryInfo['group_name'] ?? 'Unknown'
        ],
        'branch_id' => $branch_info,
        'recruitment_type' => $rows['recruitment_type'],
    ];
}


        return [
            'total_rows' => $totalrows,
            'fetched_rows' => count($array_return),
            'category_info' => $array_return,
            'maxreach' => ($totalrows < 50) ? 1 : 0
        ];

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

// Handle API Function Type
if ($postdata['function_type'] === "fetch_staff_payroll_data") {
    $institution_id = $postdata['institution_id'];
    $branch_id = $postdata['branch_id'] ?? "all";
    $limit = $postdata['limit'] ?? "all"; // Default to "all" if not provided

    $response = fetchStaffPayrollData($conn_rjllearning_specific, $institution_id, $branch_id, $limit);
    successreturn($response);
} else {
    errorreturn("Invalid function type.");
}
