<?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";
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_resources . "includes/specific_db_config.php";

require_once $base_path_to_learning . "vendor/autoload.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.'functions/common_functions.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// $postdata = json_decode(file_get_contents("php://input"), true);
// checkIfNoPhpContentsReceive();

$postdata = $_POST;
$required_fields = ['institution_id', 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$namee = $jwt_validate->data->name;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$request_time = time();
$date = trim(date('Y-m-d', strtotime($postdata['date'])));
// Specific Db Connection
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

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

// Files to Validate Institute_Id & branch_Id


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

$admissionNumber = isset($postdata['studentAdmissionNumber']) ? trim($postdata['studentAdmissionNumber']) : null;
$name = ucwords(strtolower(trim($postdata['name'])));
$organisationname = isset($postdata['organisationname']) ? ucwords(strtolower(trim($postdata['organisationname']))) : null;
$address = isset($postdata['address']) ? trim($postdata['address']) : null;
$authorized_by = isset($postdata['authorized_by']) ? ucwords(strtolower(trim($postdata['authorized_by']))) : null;
$purpose = $postdata['purpose'];
$description = isset($postdata['description']) ? ucwords(strtolower(trim($postdata['description']))) : null;
$remarksby_authoriser = isset($postdata['remarksby_authoriser']) ? ucwords(strtolower(trim($postdata['remarksby_authoriser']))) : null;
$proofdocument = (isset($_FILES['proof_document']) && !empty($_FILES['proof_document'])) ? $_FILES['proof_document'] : null;

// If admission number is provided, look up the student_id
$student_id = null;
if ($admissionNumber) {
    $checkStudentId = $conn_rjllearning_specific->prepare("SELECT id FROM students WHERE admission_number = ? AND institution_id = ?");
    $checkStudentId->execute(array($admissionNumber, $institution_id));
    $result = $checkStudentId->fetch();

    if ($result) {
        $student_id = $result['id'];
    } else {
        errorreturn("Student ID not found.");
    }
}

if ($postdata['function_type'] == "insert_visitors") {
    
    if ($proofdocument == null) {
        $proofdocument = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');
        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/homework/" . $currentYear . "/" . $currentMonth . "/";
        $file_name = $_FILES['proof_document']['name'];
        $fileTmpName = $_FILES['proof_document']["tmp_name"];
        $fileSize = $_FILES['proof_document']["size"];
        $fileType = $_FILES['proof_document']["type"];
        $fileError = $_FILES['proof_document']["error"];
        $file_extension = strtolower(pathinfo($_FILES['proof_document']['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);
    }

    $sql = "INSERT INTO visitors_log (institution_id, branch_id, academic_id, student_id, name, organisationname, address, request_time,status, date, requested_by, authorized_by, purpose, description, remarksby_authoriser, proof_document)
            VALUES (?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?,?)";
    $insertVisitors = $conn_rjllearning_specific->prepare($sql);
    $success = $insertVisitors->execute(array($institution_id, $branch_id, $academicSessionId, $student_id, $name, $organisationname, $address, $request_time,0, $date, $username, $authorized_by, $purpose, $description, $remarksby_authoriser, null));

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

    successreturn("Successfully added visitor.");
 
} else {
    errorreturn("Invalid function_type");
}
