<?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 . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.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';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['gatepass_id']) or !checkIfIssetAndNotEmpty($postdata['gatepass_id'])  or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;
$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 . '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);

function getspecific_gatepass($conn_rjllearning_specific, $institution_id, $gatepass_id, $branch_id)
{
    $sql = $conn_rjllearning_specific->prepare("SELECT * FROM gate_pass WHERE id = ? AND institution_id = ? AND branch_id = ?");
    $sql->execute(array($gatepass_id, $institution_id, $branch_id));
    $result = $sql->fetchAll(PDO::FETCH_ASSOC);

    $array_return = array();

    if (count($result) === 1) {
        foreach ($result as $res) {
            $type = $res['type'];
            $user_id = $res['user_id'];

            if ($type === 'student') {
                $sql = "SELECT name, class_id, fathername, admission_number, section_id FROM students WHERE id = ?";
                $stmt_user = $conn_rjllearning_specific->prepare($sql);
                $stmt_user->execute([$user_id]);
                $user_details = $stmt_user->fetch(PDO::FETCH_ASSOC);

                if (!empty($user_details)) {
                    $class_id = $user_details['class_id'];
                    $section_id = $user_details['section_id'];

                    $class_details = getClass($conn_rjllearning_specific, $institution_id, $class_id);


                    $section_details = getSection($conn_rjllearning_specific, $institution_id, $section_id);

                    $user_details['class_details'] = $class_details;
                    $user_details['section_details'] = $section_details;
                }
            } elseif ($type === 'faculty') {
                $sql = "SELECT name, designation FROM faculty_info WHERE id = ?";
                $stmt_user = $conn_rjllearning_specific->prepare($sql);
                $stmt_user->execute([$user_id]);
                $user_details = $stmt_user->fetch(PDO::FETCH_ASSOC);
            }
            
            if ($res['proof_document'] != null and !is_array($res['proof_document'])) {
                $data_attachment = json_decode($res['proof_document'], true);
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_array_attachment   = array("filepath" => $aws_attachment, "original_name" => $originalName);
            } else {
                $final_array_attachment =  null;
            }

            $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $res['branch_id']);
            $gatepass_info = array(
                "gatepass_id" => $res['id'],
                "institution_id" => $res['institution_id'],
                "branch" => $branch,
                "type" => $res['type'],
                "date" => $res['req_date'],
                $type . "_details" => $user_details,
                "purpose" => $res['purpose'],
                "proof_document" => $final_array_attachment,
                "requested_by" => $res['requested_by']
            );
            if (!empty($res['gatepass_id'])) {
                $gatepass_info['gatepass_id'] = $res['gatepass_id'];
            }
            $array_return[] = $gatepass_info;
        }
        return $array_return;
    } else {
        errorreturn("Gatepass not found");
    }
}

if ($postdata['function_type'] == "fetch_specific_gatepass") {
    $gatepass_id = trim($postdata['gatepass_id']);
    
    $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('fetch_gatepass_details', $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.");
    }

    $gatepass_data = getspecific_gatepass($conn_rjllearning_specific, $institution_id, $gatepass_id, $branch_id);
    successreturn($gatepass_data);
}
