<?php
ini_set('display_errors', 1);
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);
// checkIfNoPhpContentsReceive();
$postdata = $_POST;
// Check if required fields are present
$required_fields = [

    'subject_id',
    'start_date',
    'end_date',
    'subject_leave',
    'description',
    'api_signature',
    'function_type',
    'jwt_token'
];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}
// Validate API signature
validateApiSignature($postdata['api_signature']);
// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract data from JWT token
$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';


$sql_global = $conn_rjllearning_specific->prepare("
    SELECT attendance_system 
    FROM institution_global_settings 
    WHERE institution_id = ? 
      AND branch_id = ?
");
$sql_global->execute([$institution_id, $branch_id]);
$attendance_type = $sql_global->fetchColumn();

// Validate subject_id
$subject_id = trim(strtolower($postdata['subject_id'])); // Convert to lowercase for consistency

if ($attendance_type === 'subject_wise' && $subject_id === 'all') {
    errorreturn('Invalid subject selection. Please select a specific subject.');
} elseif ($attendance_type === 'day_wise') {
    // If attendance is day-wise, force subject_id to be 'all'
    $subject_id = 'all';
}



$subject_leave = ucwords(trim($postdata['subject_leave']));
$start_date = trim(date('Y-m-d', strtotime($postdata['start_date'])));
$end_date = trim(date('Y-m-d', strtotime($postdata['end_date'])));
$description = trim($postdata['description']);
$attachment = (isset($_FILES['attachment']) && !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;
// print_r($attachment);
// die();
$date_created = date('Y-m-d');
$time_created = date('H:i:s'); // Define $time_created with the current time
if (!CheckStartDate($start_date)) {
    errorreturn('Invalid Start Date Format');
}
if (!CheckStartDate($end_date)) {
    errorreturn('Invalid End Date Format');
}
if ($start_date > $end_date) {
    errorreturn('Invalid Date Range');
}
// Validate branch
if ($branch_id != "all") {
    $sql_branch = $conn_rjllearning_specific->prepare("SELECT id, name FROM branch WHERE id = ? AND institution_id = ?");
    $sql_branch->execute([$branch_id, $institution_id]);
    $branch = $sql_branch->fetch(PDO::FETCH_ASSOC);
    if (!$branch) {
        errorreturn("Branch does not exist in the specified institution.");
    }
}

// Validate subject
if ($subject_id != "all") {
    $sql_subject = $conn_rjllearning_specific->prepare("SELECT id, subject_name FROM subject_info WHERE id = ? AND institution_id = ?");
    $sql_subject->execute([$subject_id, $institution_id]);
    $subject = $sql_subject->fetch(PDO::FETCH_ASSOC);
    if (!$subject) {
        errorreturn("Subject does not exist in the specified institution.");
    }
}
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}
// print_R($userid);
if ($postdata['function_type'] === "create_apply_leaves") {

    $sql_check_leave = $conn_rjllearning_specific->prepare("
    SELECT id FROM apply_leaves 
    WHERE institution_id = ? 
    AND subject_id = ? 

    AND student_id = ? 
    AND (
        (start_date <= ? AND end_date >= ?) OR  
        (start_date <= ? AND end_date >= ?) OR  
        (start_date >= ? AND end_date <= ?)     
    )
");

    $sql_check_leave->execute([
        $institution_id,
        $subject_id,

        $userid,
        $start_date,
        $start_date, // Overlap check for the start of the new leave
        $end_date,
        $end_date,     // Overlap check for the end of the new leave
        $start_date,
        $end_date    // Overlap check for an existing leave within the new leave
    ]);

    $existing_leave = $sql_check_leave->fetch(PDO::FETCH_ASSOC);

    if ($existing_leave !== false) { // No need to check count, fetch returns false if no rows are found
        errorreturn("Apply leave already exists for the given dates.");
    }

    if ($attachment == null) {
        $attachment = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay = date('d');

        // Define directory path
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/apply_leaves/" . $userid . "/" . $currentYear . "/" . $currentMonth . "/";

        // File properties
        $file_name = $_FILES['attachment']['name'];
        $fileTmpName = $_FILES['attachment']["tmp_name"];
        $fileSize = $_FILES['attachment']["size"];
        $fileType = $_FILES['attachment']["type"];
        $fileError = $_FILES['attachment']["error"];
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Allowed file types and extensions
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2 * 1024 * 1024; // 2MB

        // Validate the file
        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }


    try {
        // Prepare and execute SQL statement to insert leave application
        $sql = "INSERT INTO apply_leaves (institution_id,academic_id, class_id,student_id, section_id, branch_id, subject_id, subject_leave, start_date, end_date, description, added_by, attachment, date_created, time_created, status) VALUES ( ?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $status = 0;
        $stmt = $conn_rjllearning_specific->prepare($sql);

        $stmt->execute([$institution_id,$academic_id, $class_id, $userid, $section_id, $branch_id, $subject_id, $subject_leave, $start_date, $end_date, $description, $username, null, $date_created, $time_created, $status]);

        $id = $conn_rjllearning_specific->lastInsertId();
        if ($attachment !=  null) {
            $image_name = "student_leave_" . $id . "." . $file_extension; // Define the image name dynamically
            $student_attachment_path = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $student_attachment_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $student_attachment_path, "original_name" => $file_name));
            $sql_logo = "UPDATE apply_leaves SET attachment = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $id));
        }

        successreturn(array('id' => $id, 'successmsg' => "Successfully apply_leave added."));
    } catch (PDOException $e) {
        errorreturn("Error: " . $e->getMessage());
    }
}
