<?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 . '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';

// 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';

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

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

$postdata = $_POST;

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

// Check if required fields are present
$required_fields = ['class_id', 'section_id', '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;
$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,["teacher"], 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
// $institution_id = trim($postdata['institution_id']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$subject_id = trim($postdata['subject_id']);
$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;

$date_created = date('Y-m-d');
$time_created = date('H:i:s'); // Define $time_created with the current time

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academic_id) {
    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.");
    }
}

// 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.");
    }
}

$function_type = $postdata['function_type'];
$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.");
}
if ($function_type === "create_apply_leaves") {
    $sql_check_leave = $conn_rjllearning_specific->prepare("SELECT id FROM apply_leaves WHERE institution_id = ? AND branch_id = ? AND subject_id = ? AND subject_leave = ? AND start_date = ? AND end_date = ?");
    $sql_check_leave->execute([$institution_id, $branch_id, $subject_id, $subject_leave, $start_date, $end_date]);
    $existing_leave = $sql_check_leave->fetch(PDO::FETCH_ASSOC);

    if ($existing_leave !== false && count($existing_leave) >= 1) {
        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 . "/" . $branch_id . "/apply_leaves/" . $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 insert leave application
        $sql = "INSERT INTO apply_leaves (institution_id, academic_id, class_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, $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());
    }
} elseif ($function_type === "update_apply_leaves") {
    // Check if the id is present in the request
    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 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($existing_attachment, true);
        $filePath = $data_attachment['filepath'];
    }

    if ($attachment != null) {
        $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay = date('d');
        if ($old_attachment == null) {
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/" . $branch_id . "/apply_leaves/" . $currentYear . "/" . $currentMonth . "/";
        } else {
            $directoryPathMain = substr($filePath, 0, strrpos($filePath, '/') + 1);
        }
        $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 apply_leaves SET academic_id = ?, class_id = ?, section_id = ?, subject_id = ?, subject_leave = ?, start_date = ?, end_date = ?, description = ? WHERE id = ? AND institution_id = ? AND branch_d = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$academic_id, $class_id, $section_id, $subject_id, $subject_leave, $start_date, $end_date, $description, $leave_id, $institution_id, $branch_id]);
       
        if ($remove_bool == 1 and $existing_attachment != null) {
            $sql_image = $conn_rjllearning_specific->prepare("SELECT attachment FROM  apply_leaves  where id = ? and institution_id = ?");
            $sql_image->execute(array($leave_id, $institution_id));
            $result_image = $sql_image->fetchAll();
            if (count($result_image) == 1) {
                $existing_attachment = $result_image[0]['attachment'];
                $data_attachment = json_decode($existing_attachment, true);
                $filePath = $data_attachment['filepath'];
                awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
                $sql = "UPDATE apply_leaves SET attachment = ? WHERE id = ? and institution_id= ?";
                $conn_rjllearning_specific->prepare($sql)->execute(array(null, $leave_id, $institution_id));
            }
        }

        if ($remove_bool == 1 and $attachment !=  null) {
            $image_name = "student_leave" . $id . "." . $file_extension; // Define the image name dynamically
            $image_path = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $image_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $image_path, "original_name" => $file_name));
            $sql_logo = "UPDATE 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());
    }
}
