<?php
ini_set('display_errors', 1);
require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
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';

require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

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

// Required fields
$requiredFields = ['function_type', 'api_signature', 'jwt_token', 'category_id'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorReturn("Field '$field' is required.");
    }
}
validateApiSignature($postdata['api_signature']);
$jwt_token = $postdata['jwt_token'];

$category_id = $postdata['category_id'];

// Validate JWT Token
// Validate JWT Token
$jwt_validate = authenticate_jwt($jwt_token);
if (!$jwt_validate) {
    errorReturn("Invalid JWT token.");
}

// Extract user details from token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['teacher'], null);
if (!$specific_db_name) {
    errorReturn("Access denied.");
}

// Connect to the specific database
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
if (!$conn_rjllearning_specific) {
    errorReturn("Failed to connect to the database.");
}
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning,$conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

$sql_faculty = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$sql_faculty->execute([$userid, $institution_id, $branch_id]);
$result_faculty = $sql_faculty->fetch(PDO::FETCH_ASSOC);
if (!$result_faculty) {
    errorreturn("Faculty not found.");
}

$faculty_id = $result_faculty['id'];
$function_type = $postdata['function_type'];

// Check faculty permissions
$teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
checkFacultyModuleGranted($function_type, $teacher_data['class_section_subjects'], $teacher_data['class_incharge_roles'], $teacher_data['staff_access_modules'], null, null, null, $conn_rjllearning);


function fetchSpecificPayrollCategory($conn_rjllearning_specific, $institution_id, $branch_id, $category_id) {
    try {
        $query = "SELECT id, institution_id, branch_id, name, payroll_profile_params, allowed_leaves, allowed_leaves_basis, created_by, created_on, status 
                  FROM payroll_category 
                  WHERE institution_id = ? AND id = ? AND branch_id = ?
                  LIMIT 1";

        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$institution_id, $category_id, $branch_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            errorReturn("Payroll category not found.");
        }

        // Fetch branch info
        $branch_info = $row['branch_id'] == 'all' ? array('branch_id' => 'all', 'name' => ucwords('all')) : 
                           getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        
        // Fetch salary param names
            $paramQuery = "SELECT id, name_of_profile FROM payroll_profile WHERE id = ?";
            $paramStmt = $conn_rjllearning_specific->prepare($paramQuery);
            $paramStmt->execute([$row['payroll_profile_params']]);
            $profile_params = $paramStmt->fetchAll(PDO::FETCH_ASSOC);
            if (count($profile_params) > 0) {
                $salary_params =  array("id" => $profile_params[0]['id'], "name_of_profile" => $profile_params[0]['name_of_profile']);
            } else {
                errorreturn("payroll profile not found.");
            }

        // Returning structured data
        return [
            "payroll_category" => [
                "id" => $row["id"],
                "institution_id" => $row["institution_id"],
                "branch_id" => $branch_info, // Fetching detailed branch info
                "name" => $row["name"],
                "params" => $salary_params, // Now returns both ID & Name
                "allowed_leaves" => $row['allowed_leaves'],
                "allowed_leaves_basis" => $row['allowed_leaves_basis'],
                "created_by" => $row["created_by"],
                "created_on" => $row["created_on"],
                "status" => $row["status"]
            ]
        ];

    } catch (PDOException $e) {
        errorReturn("Database Error: " . $e->getMessage());
    }
}

// Fetch specific payroll category
if ($function_type == "fetch_specific_payroll_category") {
    $category_id = $postdata['category_id'];
    $data = fetchSpecificPayrollCategory($conn_rjllearning_specific, $institution_id, $branch_id, $category_id);
    successreturn($data);
}

?>
