<?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 . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.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 . 'admin_api/global_settings/otp_settings/functions.php';
require_once $base_path_to_learning . 'admin_api/modules/gate_pass/validate_otp_for_gatepass.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/firebase_notification/faculty_and_principal_notification_function.php';

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

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

// Validate required fields
$requiredFields = ['institution_id', 'branch_id', 'type', 'user_id', 'api_signature', 'function_type', 'jwt_token', 'purpose'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        // errorreturn("All * fields are required.");
        errorreturn("Field '$field' is required and cannot be empty.");
    }
}

validateApiSignature($postdata['api_signature']);

// Validate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user details from JWT
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$type = $postdata['type']; // "student" or "faculty"
$user_id = $postdata['user_id'];
$purpose = $postdata['purpose'];


// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$check_academic_confirmation_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($check_academic_confirmation_id != true) {
    errorreturn("Access denied. Academic session not active.");
}

$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
}

$authorized_by = isset($postdata['authorized_by']) ? ucwords(strtolower(trim($postdata['authorized_by']))) : null;
$proofdocument = (isset($_FILES['proof_document']) && $_FILES['proof_document']['error'] === 0) ? $_FILES['proof_document'] : null;
$approved_time = isset($postdata['approved_time']) ? trim($postdata['approved_time']) : null;


$req_date = isset($postdata['req_date']) ? trim($postdata['req_date']) : date("Y-m-d");
$req_time = isset($postdata['req_time']) ? strtotime(trim($postdata['req_time'])) : time();

$currentDate = date("Y-m-d");
$currentTime = time();

if (strtotime($req_date) < strtotime($currentDate)) {
    // If req_date is in the past, override with current date and time
    $req_date = $currentDate;
    $req_time = $currentTime;
} elseif (strtotime($req_date) == strtotime($currentDate)) {
    // If req_date is today, ensure req_time is not in the past
    if ($req_time < $currentTime) {
        $req_time = $currentTime;
    }
}


if ($postdata['function_type'] == "validate_otp") {
    try {

        $sql = "SELECT otp_setting FROM institution_global_settings WHERE institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $branch_id]);
        $otp_setting = $stmt->fetch(PDO::FETCH_ASSOC);

        $otp_settings_array = json_decode($otp_setting['otp_setting'], true);

        if (isset($otp_settings_array['gate_pass_otp']) && $otp_settings_array['gate_pass_otp'] == 1) {

            if (!isset($postdata['otp']) || empty($postdata['otp'])) {
                errorreturn("OTP is required for gate pass requests.");
            }

            $otp = $postdata['otp'];
            $user_token = $postdata['user_token'];

            $sql = "SELECT otp, user_token FROM otp_store WHERE otp = ? AND otp_type = 'gate_pass_otp' AND status = 0";
            $stmt = $conn_rjllearning->prepare($sql);
            $stmt->execute([$otp]);
            $stored_otp_data = $stmt->fetch();

            if (!$stored_otp_data) {
                errorreturn("Invalid OTP");
            }

            if ($otp === $stored_otp_data['otp']) {



                // Mark OTP as used
                $update_sql = "UPDATE otp_store SET status = 1 WHERE otp = ? AND username = ? AND otp_type = 'gate_pass_otp'";
                $update_stmt = $conn_rjllearning->prepare($update_sql);
                $update_stmt->execute([$otp, $username]);
            } else {
                errorreturn("OTP validation failed.");
            }
        }
        
        if ($proofdocument != null) {
            $currentYear = date('Y');
            $currentMonth = date('n');
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/homework/" . $currentYear . "/" . $currentMonth . "/";

            $file_name = $proofdocument['name'];
            $fileTmpName = $proofdocument["tmp_name"];
            $fileSize = $proofdocument["size"];
            $fileType = $proofdocument["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'];

            // Check file validation
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

            // Create a unique filename
            $image_name = uniqid() . "." . $file_extension;
            $proofdocument_path = $directoryPathMain . $image_name;

            // Upload to S3
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $proofdocument_path,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
            }
            $proofdocument = json_encode(["filepath" => $proofdocument_path, "original_name" => $file_name]);
        }

        $insert_sql = "INSERT INTO gate_pass (institution_id, branch_id, academic_id, type, user_id, req_date, req_time, purpose, requested_by, authorized_by, proof_document, approved_time, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $insert_stmt = $conn_rjllearning_specific->prepare($insert_sql);
        $insert_stmt->execute([$institution_id, $branch_id, $check_academic_confirmation_id, $type, $user_id, $req_date, $req_time, $purpose, $username, $authorized_by, $proofdocument, $approved_time, 0]);
        $gate_pass_id = $conn_rjllearning_specific->lastInsertId();
        // ✅ Fixed: use $gate_pass_id instead of overwriting $user_id
        sendGatePassStudentRequestNotificationToPrincipalAndFaculty($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $user_id);

        successreturn("Successfully added gate_pass request.");
    } catch (PDOException $e) {
        errorreturn("Database error: " . $e->getMessage());
    }
} else {
    errorreturn("Invalid Function Type.");
}
