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

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['institution_id']) || empty($postdata['institution_id']) ||
      !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;

$institution_id = trim($postdata['institution_id']);
$specific_db_name = validateStudentAcess($conn_rjllearning,  $role, $workspace_id,['superadmin','admin'],null, $userid);
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';


if ($postdata['function_type'] == "fetch_specific_staff_apply_leave_id") {
    
    if (!isset($postdata['staff_apply_leave_id']) || empty($postdata['staff_apply_leave_id'])) {
        errorreturn("Leave ID is required.");
    }

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

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $sql = $conn_rjllearning_specific->prepare("SELECT * FROM staff_apply_leaves WHERE id = ? AND institution_id = ?");
    $sql->execute([$leave_id, $institution_id]);
    $leave = $sql->fetch();

    if ($leave) {
        
    $student_sql = "SELECT id, name FROM faculty_info WHERE institution_id = ? AND id = ?";

$student_stmt = $conn_rjllearning_specific->prepare($student_sql);
$student_stmt->execute([$institution_id, $leave['staff_id']]);

// Fetch a single result as an associative array
$staff_result = $student_stmt->fetch(PDO::FETCH_ASSOC);


    if ($staff_result) {
        // Access data correctly from the associative array
        $staff_id = $staff_result['id'];
        $staff_name = $staff_result['name'];
    } else {
        $staff_id = null;
        $staff_name = null;
    }

    $final_array_attachment = null;

if ($leave['attachment'] !== null && !is_array($leave['attachment'])) {
    $data_attachment = json_decode($leave['attachment'], true);

    // Check if $data_attachment is an array and contains the expected keys
    if (is_array($data_attachment) && isset($data_attachment['filepath']) && isset($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 {
            // Handle case where $filePath is empty
            $final_array_attachment = ["filepath" => null, "original_name" => $originalName];
        }
    }
}

        // Get class, section, subject, and branch info
        
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $leave['branch_id']);
       
        // $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $leave['subject_id']);

        $success['data'] = [
            'staff_leave_id' => $leave['id'],
            'branch_id' => $branch_info,
            'staff_id' => $staff_result, // or $subject_info if you fetch it
            'staffleave_type_id' => $leave['leave_type'],
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'leave_reason' => $leave['leave_reason'],
            'description' => $leave['approved_by'],
            'approved_by' => $leave['approved_by'],
              'leave_days' => $leave['leave_days'],
            'attachment' => $final_array_attachment
        ];

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