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

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

// Required fields
$requiredFields = ['jwt_token', 'institution_id', 'allowed_leave_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'];
$institution_id = $postdata['institution_id'];
$allowed_leave_id = $postdata['allowed_leave_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;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], 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.");
}

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

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

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

        // Fetch branch info
        // $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        $branch_info = ($row['branch_id'] == 'all')
            ? array('branch_id' => 'all', 'name' => ucwords('all'))
            : getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
 

        // Returning structured data
        return [
            "allowed_leaves" => [
            'allowed_id' => $row['id'],
            'institution_id' => $row['institution_id'],
            'branch_id' => $branch_info,
            'leave_type' => $row['leave_type'],
            'allowed_days' => $row['allowed_days'],
            'carry_forward' => $row['carry_forward'],
            'year' => $row['year'],
            'added_by' => $row['added_by'],
            'date_created' => $row['date_created'],
            'time_created' => $row['time_created'],
            'status' => $row['status']
        ]
        ];

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

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

?>
