<?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 . 'admin_api/global_settings/otp_settings/functions.php';
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_resources . 'lib/cron_jobs/sms_function/sms_function.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;
$postdata = json_decode(file_get_contents('php://input'), true);

// Validate required fields
$requiredFields = ['type', 'user_id', 'api_signature', 'function_type', 'jwt_token'];
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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

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

// Validate user access and get specific database name
$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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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);

$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;
// $user_token = isset($postdata['user_token']) ? trim($postdata['user_token']) : null;

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

if ($postdata['function_type'] == "generate_gate_pass_otp") {
    
    $faculty_id = $result_faculty['id'];
    $faculty_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    
    $class_section_subjects  = $faculty_data['class_section_subjects'];
    $class_incharge_roles = $faculty_data['class_incharge_roles'];
    $staff_access_modules = $faculty_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
    }
    $userToken = generateGatePassOTP(
        $conn_rjllearning,
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $user_id,
        $type,
        $username,
        $workspace_id,
        $web_app_title
    );
    // Return the success response with the user_token
    successreturn(array(
        'user_Token' => $userToken,
    ));
// } elseif ($postdata['function_type'] == "validate_otp") {

//     $requiredFields = ['otp', 'purpose'];
//     foreach ($requiredFields as $field) {
//     if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
//         errorreturn("All * fields are required.");
//     }
//     }
//     $otp = $postdata['otp'];
//     $purpose = $postdata['purpose'];
    
//     try {
//         $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();
//         // var_dump($stored_otp_data);

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

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

//             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 image types
//                 $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]);
//             }

//             $req_date = date("Y-m-d");
//             $req_time = time();

//             $insert_sql = "INSERT INTO gate_pass (institution_id, branch_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, $type, $user_id, $req_date, $req_time, $purpose, $username, $authorized_by, $proofdocument, $approved_time, 0]);
//             // 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]);

//             $user_id = $conn_rjllearning_specific->lastInsertId();
//             successreturn("Successfully added gate_pass request.");
//         } else {
//             errorreturn("OTP validation failed.");
//         }
//     } catch (PDOException $e) {
//         errorreturn("Database error: " . $e->getMessage());
//     }
} else {
    errorreturn("Invalid Function Type.");
}
