<?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';
// DB access function

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

$postdata = $_POST;

// var_dump($postdata );
// die();

// Check if required fields are present
$required_fields = [
    'staff_id',
    'start_date',
    'end_date',
    'leave_reason',
    'leave_type',
    '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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

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


// Extract and validate input data

// $branch_id = trim($postdata['branch_id']);
$staff_id = trim($postdata['staff_id']);
$leave_type = ucwords(trim($postdata['leave_type']));
$start_date = trim(date('Y-m-d', strtotime($postdata['start_date'])));
$end_date = trim(date('Y-m-d', strtotime($postdata['end_date'])));
$leave_reason = trim($postdata['leave_reason']);
$leave_days = trim($postdata['leave_days']);
$attachment = (isset($_FILES['attachment']) && !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;
$date_created = date('Y-m-d');
$time_created = date('H:i:s');

$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($check_academic_confirmation != true) {
    errorreturn("Access denied. Academic session not active.");
}
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.");
    }
}

if ($postdata['function_type'] === "create_staff_apply_leaves") {
    $sql_check_leave = $conn_rjllearning_specific->prepare("
    SELECT id FROM staff_apply_leaves 
    WHERE institution_id = ? 
    AND leave_type = ? 
    AND staff_id = ? 
    AND branch_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,
        $leave_type,
        $staff_id,
        $branch_id,
        $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');

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/staff_apply_leaves/attachment/" . $currentYear . "/" . $currentMonth . "/";
        $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($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $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 image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }


    try {
        // Prepare and execute SQL statement to insert leave application
        $sql = "INSERT INTO staff_apply_leaves (institution_id, branch_id, staff_id, leave_type, start_date, end_date, leave_reason, leave_days, attachment, created_by, date_created, time_created, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $branch_id, $staff_id, $leave_type, $start_date, $end_date, $leave_reason, $leave_days, null, $username, $date_created, $time_created, 0]);

        $id = $conn_rjllearning_specific->lastInsertId();


        if ($attachment !=  null) {
            $image_name = "staff_apply_leaves_" . $id . "." . $file_extension; // Define the image name dynamically
            $path = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $path, "original_name" => $file_name));
            $sql_logo = "UPDATE staff_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());
    }
} elseif ($function_type === "update_apply_leaves") {
    if (!isset($postdata['id']) || empty($postdata['id'])) {
        errorreturn("Leave application ID is required for updating.");
    }

    $leave_id = $postdata['id'];

    // Check if the leave application exists within the date range
    $sql_check_leave = $conn_rjllearning_specific->prepare("SELECT id, attachment FROM staff_apply_leaves WHERE id = ? AND institution_id = ? AND branch_id = ? AND (start_date BETWEEN ? AND ? OR end_date BETWEEN ? AND ?)");
    $sql_check_leave->execute([$leave_id, $institution_id, $branch_id, $start_date, $end_date, $start_date, $end_date]);
    $leave = $sql_check_leave->fetch(PDO::FETCH_ASSOC);
    if (!$leave) {
        errorreturn("Leave application does not exist for the specified date range.");
    }

    $old_attachment = $leave['attachment'];
    if ($old_attachment !=  null) {
        $data_attachment = json_decode($old_attachment, true);
        $filePath = $data_attachment['filepath'];
    }

    if ($attachment != null) {
        $currentYear = date('Y');
        $currentMonth = date('n');
        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/staff_apply_leaves/attachment/" . $currentYear . "/" . $currentMonth . "/";
        $file_name = $_FILES['attachment']['name'];
        $fileTmpName = $_FILES['attachment']["tmp_name"];
        $fileSize = $_FILES['attachment']["size"];
        $fileType = $_FILES['attachment']["type"];
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

        $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'];

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    try {
        // Prepare and execute SQL statement to update leave application
        $sql = "UPDATE staff_apply_leaves SET  class_id = ?, section_id = ?, branch_id = ?, subject_id = ?, subject_leave = ?, start_date = ?, end_date = ?, description = ? WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$class_id, $section_id, $branch_id, $subject_id, $subject_leave, $start_date, $end_date, $description, $leave_id, $institution_id, $branch_id]);

        if ($remove_bool == 1 and $old_attachment != null) {
            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
            $sql = "UPDATE staff_apply_leaves SET attachment = ? WHERE id = ? and institution_id= ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array(null, $leave_id, $institution_id));
        }

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


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