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

//validation file
require_once $base_path_to_learning_resources . "lib/validate_function.php";
require_once $base_path_to_learning . "user_management/authenticate.php";

//db access function
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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

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

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

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$visitorid = trim($postdata['visitor_log_id']);
$status = trim($postdata['status']);
$remarks = isset($postdata['remarksby_authoriser']) ? ucwords(strtolower(trim($postdata['remarksby_authoriser']))) : null;

//Specific Db Connection
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $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);

//Validate institution_id and branch_id
$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

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

$sql = "SELECT id, status, entry_time FROM visitors_log WHERE id = ? AND institution_id = ? AND branch_id = ? " ;
$checkvisitor_id = $conn_rjllearning_specific->prepare($sql);
$checkvisitor_id->execute(array($visitorid, $institution_id,$branch_id));
$visitor = $checkvisitor_id->fetch();

if (!$visitor) {
    errorreturn("Invalid Visitor ID");
}

if ($visitor['status'] == '-1') {
    errorreturn("Visitor's request is declined and status cannot be changed.");
}

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

    if ($visitor['status'] == '2') {
        // If the visitor's status is already '2', do not allow any changes
        errorreturn("Visitor's visit is completed; no further updates allowed.");
    }

    if ($status == '1') {
        $entry_time = time();
        $sql_update = $conn_rjllearning_specific->prepare("UPDATE visitors_log SET entry_time = ? ,remarksby_authoriser = ?,status = ?,authorized_by = ? WHERE id = ? AND institution_id = ? AND branch_id = ?");
        $update_success = $sql_update->execute(array($entry_time,$remarks, $status, $username, $visitorid, $institution_id,$branch_id));

        if ($update_success) {
            successreturn("Visitor's entry time updated successfully.");
        } else {
            errorreturn("Failed to update visitor's entry time.");
        }
    } elseif ($status == '2') {
        if (empty($visitor['entry_time'])) {
            errorreturn("Entry time must be set before setting exit time.");
        }
        $exittime = time();
        $sql_update = $conn_rjllearning_specific->prepare("UPDATE visitors_log SET exit_time = ?,status = ? WHERE id = ? AND institution_id = ? AND branch_id = ?");
        $update_success = $sql_update->execute(array($exittime, $status,  $visitorid, $institution_id,$branch_id));
        
        if ($update_success) {
            successreturn("Visitor's visit Completed");
            
        } else {
            errorreturn("Failed to update visitor's exit time.");
        }
    } elseif ($status == '-1') {
        $rejected_time = time();
        $sql_update = $conn_rjllearning_specific->prepare("UPDATE visitors_log SET rejected_time = ?,status = ?,remarksby_authoriser = ?,authorized_by = ? WHERE id = ? AND institution_id = ?");
        $update_success = $sql_update->execute(array($rejected_time, $status, $remarks,$username, $visitorid, $institution_id));

        if ($update_success) {
            successreturn("Visitor's Request Declined");
        } else {
            errorreturn("Unable to decline request");
        }
    } else {
        errorreturn("Invalid Status");
    }
} else {
    errorreturn("Invalid Function_type");
}
