<?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/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
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);

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

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

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

$institution_id = trim($postdata['institution_id']);
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

$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 (isset($postdata['search_string']) && !empty($postdata['search_string'])) {
    $search_string = trim($postdata['search_string']);
} else {
    $search_string = null;
}

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

    $leave_id = trim($postdata['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);
            $filePath = $data_attachment['filepath'];
            $originalName = $data_attachment['original_name'];
            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $final_array_attachment = ["filepath" => $aws_attachment, "original_name" => $originalName];
        }

        // Construct SQL query based on conditions
        $sql_fetch_lesson_categories = "SELECT * FROM your_table_name WHERE institution_id = ?";
        $array_params_fetch_leave = [$institution_id];

        if ($branch_id != null && $branch_id != 'all') {
            $sql_fetch_lesson_categories .= " AND branch_id = ? ";
            $array_params_fetch_leave[] = $branch_id;
        }

        if ($class_id != null && $class_id != 'all') {
            $sql_fetch_lesson_categories .= " AND class_id = ? ";
            $array_params_fetch_leave[] = $class_id;
        }

        if ($subject_id != null && $subject_id != 'all') {
            $sql_fetch_lesson_categories .= " AND subject_id = ? ";
            $array_params_fetch_leave[] = $subject_id;
        }

        if ($search_string != null) {
            $sql_fetch_lesson_categories .= " AND (topic_name LIKE ? OR description LIKE ?)";
            $array_params_fetch_leave[] = '%' . $search_string . '%';
            $array_params_fetch_leave[] = '%' . $search_string . '%';
        }

        // Execute the SQL query
        $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);
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_array_attachment = ["filepath" => $aws_attachment, "original_name" => $originalName];
            }
// var_dump($leave);
            // 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']);
        //  $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'],
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'apply_leave_id' => $leave['id'],
            'subject_leave' => $leave['subject_leave'],
            'description' => $leave['description'],
            'attachment' => $final_array_attachment
        ];
        successreturn($success);
    } else {
        errorreturn("Invalid leave info.");
    }
}
}
