<?php
ini_set('display_errors', 1);


// Include necessary files
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_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.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";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

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

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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["teacher"], null);

if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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);

$function_type = trim($postdata['function_type']);

$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));

// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);

// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

// Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];
if ($function_type == "fetch_apply_leaves") {
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    // Set default values if not provided
    if (isset($postdata['class_id']) and !empty($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        $class_id = null;
    }
    if (isset($postdata['section_id']) and !empty($postdata['section_id'])) {
        $section_id = trim($postdata['section_id']);
    } else {
        $section_id = null;
    }
    if (isset($postdata['subject_id']) and !empty($postdata['subject_id'])) {
        $subject_id = trim($postdata['subject_id']);
    } else {
        $subject_id = null;
    }
    // $section_id = trim($postdata['section_id']) ;
    // $search_string = isset($postdata['search_string']) ? trim($postdata['search_string']) : null;
    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }

    // $subject_leave = isset($postdata['subject_leave']) ? trim($postdata['subject_leave']) : null;
    if (isset($postdata['subject_leave']) and !empty($postdata['subject_leave'])) {
        $subject_leave = trim($postdata['subject_leave']);
    } else {
        $subject_leave = null;
    }
    // $description = isset($postdata['description']) ? trim($postdata['description']) : null;
    if (isset($postdata['description']) and !empty($postdata['description'])) {
        $description = trim($postdata['description']);
    } else {
        $description = null;
    }

    // $start_date = isset($postdata['start_date']) ? trim($postdata['start_date']) : null;
    if (isset($postdata['start_date']) and !empty($postdata['start_date'])) {
        $start_date = trim($postdata['start_date']);
    } else {
        $start_date = null;
    }
    // $end_date = isset($postdata['end_date']) ? trim($postdata['end_date']) : null;

    if (isset($postdata['end_date']) and !empty($postdata['end_date'])) {
        $end_date = trim($postdata['end_date']);
    } else {
        $end_date = null;
    }

    // $date_created = isset($postdata['date_created']) ? trim($postdata['date_created']) : null;
    if (isset($postdata['date_created']) and !empty($postdata['date_created'])) {
        $date_created = trim($postdata['date_created']);
    } else {
        $date_created = null;
    }

    // $time_created = isset($postdata['time_created']) ? trim($postdata['time_created']) : null;
    if (isset($postdata['time_created']) and !empty($postdata['time_created'])) {
        $time_created = trim($postdata['time_created']);
    } else {
        $time_created = null;
    }

    // $name = isset($postdata['name']) ? trim($postdata['name']) : null;
    if (isset($postdata['name']) and !empty($postdata['name'])) {
        $name = trim($postdata['name']);
    } else {
        $name = null;
    }

    $status = isset($postdata['status']) ? trim($postdata['status']) : null;

    // Validate dates
    if ($start_date != null && $end_date != null && strtotime($start_date) > strtotime($end_date)) {
        errorreturn('Invalid Date format');
    }

    // Call the function to get apply leaves
    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;

        $apply_leaves_data = getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $subject_leave, $description, $start_date, $end_date, $date_created, $time_created, $status, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset);
    } else {
        $apply_leaves_data = getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $subject_leave, $description, $start_date, $end_date, $date_created, $time_created, $status, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, null);
    }
    successreturn($apply_leaves_data);
}

function getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $subject_leave, $description, $start_date, $end_date, $date_created, $time_created, $status, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset)
{

    $sql_count = "SELECT count(*) as total_rows FROM apply_leaves where institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ?";
    $array_params = [$institution_id, $branch_id, $class_id, $section_id];

    if ($date_created != null) {
        $sql_count .= " AND date_created = ?";
        $array_params[] = $date_created;
    }
    if ($start_date != null && $end_date != null) {
        $sql_count .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $start_date;
        $array_params[] = $end_date;
    }
    if ($search_string != null) {
        $sql_count .= " AND (subject_leave LIKE ? OR description LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];


    // get roles
    $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($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning);
    if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
    }

    $sql = "SELECT * FROM apply_leaves WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ?";
    $array_params = array($institution_id, $branch_id ,$class_id, $section_id);

    $sql_append_data = facultyFilterQueryAppend($sql, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, null, $conn_rjllearning, 1, 1, 1, 1, true);
    $sql = $sql_append_data['sql']; // Get the modified SQL
    $array_params = $sql_append_data['array_params'];

    if ($date_created != null) {
        $sql .= " AND date_created = ?";
        $array_params[] = $date_created;
    }
    if ($start_date != null && $end_date != null) {
        $sql .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $start_date;
        $array_params[] = $end_date;
    }
    if ($search_string != null) {
        $sql .= " AND (subject_leave LIKE ? OR description LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }
    $sql .= " ORDER BY date_created DESC ";
if($limit !='all'){
     $sql .= "LIMIT " . $offset . " ," . $limit . "";
}

    // Prepare and execute the SQL query
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();


   $array_return = [];
    $branch_info_all = [];
    $class_info_all = [];
    $section_info_all = [];
    $subject_info_all = [];

    $leave_info = [];

    foreach ($result as $row) {


        // SQL query to select the student's ID and name
        $student_sql = "SELECT id, name FROM students WHERE institution_id = ? AND user_id = ?";

        // Prepare the statement
        $student_stmt = $conn_rjllearning_specific->prepare($student_sql);

        // Execute the statement with the provided parameters
        $student_stmt->execute([$institution_id, $row['student_id']]);

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


        if ($student_result) {
            // Access data correctly from the associative array
            $student_id = $student_result['id'];
            $student_name = $student_result['name'];
        } else {
            $student_id = null;
            $student_name = null;
        }

        // Process attachment
        if (!empty($row['attachment']) && is_string($row['attachment'])) {
            $data_attachment = json_decode($row['attachment'], true);
            if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_array_attachment = array("filepath" => $aws_attachment, "original_name" => $originalName);
            } else {
                $final_array_attachment = null;
            }
        } else {
            $final_array_attachment = null;
        }


        // Branch Info
        $branch_id = $row['branch_id'];
        if ($branch_id == 'all') {
            $branch_info = array('branch_id' => $branch_id, 'name' => ucwords($branch_id));
        } else {
            // Fetch branch data from database
            $branch_sql = "SELECT * FROM branch WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($branch_sql);
            $stmt->execute([$institution_id, $branch_id]);
            $branch_data = $stmt->fetch();

            $branch_info = array('branch_id' => $branch_data['id'], 'name' => $branch_data['name']);
        }

        // Class Info
        $class_id = $row['class_id'];
        if ($class_id == 'all') {
            $class_info = array('class_id' => $class_id, 'classname' => ucwords($class_id));
        } else {
            // Fetch class data from database
            $class_sql = "SELECT * FROM class_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($class_sql);
            $stmt->execute([$institution_id, $class_id]);
            $class_data = $stmt->fetch();

            $class_info = array('class_id' => $class_data['id'], 'classname' => $class_data['classname']);
        }

        // Section Info
        $section_id = $row['section_id'];
        if ($section_id == 'all') {
            $section_info = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
        } else {
            // Fetch section data from database
            $section_sql = "SELECT * FROM section_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($section_sql);
            $stmt->execute([$institution_id, $section_id]);
            $section_data = $stmt->fetch();

            $section_info = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
        }

        // Merge branch, class, and section info arrays
        $branch_info_all = $branch_info;
        $class_info_all = $class_info;
        $section_info_all = $section_info;

        // Get subject info
        // Get subject info
        $subject_id = $row['subject_id'];

        if ($subject_id == 'all') {
            $subject_info = array('subject_id' => $subject_id, 'subject_name' => ucwords($subject_id));
        } else {
            // Fetch section data from database
            $section_sql = "SELECT * FROM subject_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($section_sql);
            $stmt->execute([$institution_id, $subject_id]);
            $subject_data = $stmt->fetch();

            $subject_info = array('section_id' => $subject_data['id'], 'subject_name' => $subject_data['subject_name']);
        }
        // Create the response array
        $array_return[] = [
            'student_id' => $student_id,
            'name' => $student_name,
            'branch_info' => $branch_info_all,
            'class_info' => $class_info_all,
            'section_info' => $section_info_all,
            'subject_info' => $subject_info,
            'apply_leave_id' => $row['id'],
            'attachment' => $final_array_attachment,
            'subject_leave' => $row['subject_leave'],
            'description' => $row['description'],
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date'],
            'date_created' => $row['date_created'],
            'time_created' => $row['time_created'],
            'status' => $row['status'],

        ];
    }



    // Return the array
    // return $array_return;

    if (count($result) < 50) {

        return array('total_rows' => $totalrows, 'leave_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'leave_info' => $array_return, 'maxreach' => 0);
    }
}
