<?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['apply_leave_id']) || empty($postdata['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 = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);


require_once $base_path_to_learning . 'functions/get_branch_functions.php';


// $class_id = isset($postdata['class_id']) ;
// $branch_id = isset($postdata['branch_id']) ;
// $subject_id = isset($postdata['subject_id']) ;
// $section_id = isset($postdata['section_id']) ;


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

    $leave_id = trim($postdata['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 apply_leaves WHERE id = ? AND institution_id = ?");
    $sql->execute([$leave_id, $institution_id]);
    $leave = $sql->fetch();

    if ($leave) {
    $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
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $leave['class_id']);
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $leave['branch_id']);
        $section_info = getSection($conn_rjllearning_specific, $institution_id, $leave['section_id']);
        // Uncomment if you need subject info
        // $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $leave['subject_id']);

        $success['data'] = [
            'leave_id' => $leave['id'],
            'branch_id' => $branch_info,
            'class_id' => $class_info,
            'section_id' => $section_info,
            'subject_info' => $leave['subject_id'], // or $subject_info if you fetch it
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'apply_leave_id' => $leave['id'],
            'subject_leave' => $leave['subject_leave'],
            'description' => $leave['description'],
            'status' => $leave['status'],
            'attachment' => $final_array_attachment
        ];

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