<?php
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/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";


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

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

if (!$postdata) {
    errorreturn("No data received.");
}

if (
    !isset($postdata['staff_apply_leave_id']) || empty($postdata['staff_apply_leave_id']) ||
    !isset($postdata['api_signature']) || empty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || empty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || empty($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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

// $institution_id = trim($postdata['institution_id']);
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], null, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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);

if ($postdata['function_type'] == "fetch_specific_staff_apply_leave") {
    
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted('fetch_staff_apply_leaves', $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }
    // Validate leave ID
    if (empty($postdata['staff_apply_leave_id'])) {
        errorreturn("Leave ID is required.");
    }

    $leave_id = trim($postdata['staff_apply_leave_id']);

    // Check active academic session
    if (!CheckAcademicSession($conn_rjllearning_specific, $institution_id)) {
        errorreturn("Access denied. Academic session not active.");
    }

    // Fetch leave details
    $sql = "SELECT * FROM staff_apply_leaves WHERE institution_id = ? AND branch_id = ? AND id = ?";
    $array_params = [$institution_id, $branch_id, $leave_id];
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $leave = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($leave) {
        $final_array_attachment = null;

        // Process attachment if it exists
        if (!empty($leave['attachment']) && !is_array($leave['attachment'])) {
            $data_attachment = json_decode($leave['attachment'], true);

            if (is_array($data_attachment) && isset($data_attachment['filepath'], $data_attachment['original_name'])) {
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];

                if (!empty($filePath)) {
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    $final_array_attachment = [
                        "filepath" => $aws_attachment,
                        "original_name" => $originalName
                    ];
                } else {
                    $final_array_attachment = [
                        "filepath" => null,
                        "original_name" => $originalName
                    ];
                }
            }
        }

        // Fetch branch information
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id);

        // Build response data
        $success['data'] = [
            'staff_leave_id' => $leave['id'],
            'branch_info' => $branch_info,
            'staff_id' => $leave['staff_id'],
            'staffleave_type_id' => $leave['leave_type'],
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'leave_reason' => $leave['leave_reason'],
            'approved_by' => $leave['approved_by'],
            'leave_days' => $leave['leave_days'],
            'attachment' => $final_array_attachment
        ];

        successreturn($success);
    } else {
        errorreturn("Invalid leave info.");
    }
}
