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

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

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

checkIfNoPhpContentsReceive();

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

$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);

function get_gatepass_details($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, $offset, $status)
{
    $sql_count = "SELECT  count(*) as total_rows FROM gate_pass where institution_id =? AND status = ?";
    $array_params = [$institution_id, $status];
    if ($branch_id == 'all') {
            $sql_count .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql_count .= " AND branch_id = ? ";
            $array_params[] = $branch_id;
    }
    // if ($search_string != null) {
    //         $sql_count .= " AND (gp.purpose LIKE ? OR s.name LIKE ? OR f.name LIKE ?) ";
    //         $array_params[] = '%' . $search_string . '%';
    //         $array_params[] = '%' . $search_string . '%';
    //         $array_params[] = '%' . $search_string . '%';
    // }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {

        $sql_session = "SELECT gp.*,
        CASE 
        WHEN gp.type = 'student' THEN s.name
        WHEN gp.type = 'faculty' THEN f.name
        END as name
        FROM gate_pass gp
        LEFT JOIN students s ON gp.user_id = s.id AND gp.type = 'student'
        LEFT JOIN faculty_info f ON gp.user_id = f.id AND gp.type = 'faculty'
        LEFT JOIN class_info c ON s.class_id = c.id
        LEFT JOIN section_info sec ON s.section_id = sec.id
        WHERE gp.institution_id = ? AND gp.branch_id = ? AND gp.status = ?";
        $array_params = [$institution_id, $branch_id, $status];

        if ($search_string != null) {
            $sql_session .= " AND (gp.purpose LIKE ? OR s.name LIKE ? OR f.name LIKE ? OR s.admission_number LIKE ? OR s.username LIKE ? 
            OR s.mobile LIKE ? OR f.designation LIKE ? OR f.role LIKE ? OR c.classname LIKE ? OR sec.section_name LIKE ?) ";
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
        }

        $sql_session .=  "order by gp.req_date DESC, gp.req_time DESC";
    } else {
        $sql_session = "SELECT gp.*,
        CASE 
        WHEN gp.type = 'student' THEN s.name
        WHEN gp.type = 'faculty' THEN f.name
        END as name
        FROM gate_pass gp
        LEFT JOIN students s ON gp.user_id = s.id AND gp.type = 'student'
        LEFT JOIN faculty_info f ON gp.user_id = f.id AND gp.type = 'faculty'
        LEFT JOIN class_info c ON s.class_id = c.id
        LEFT JOIN section_info sec ON s.section_id = sec.id
        WHERE gp.institution_id = ? AND gp.branch_id = ? AND gp.status = ?";
        $array_params = [$institution_id, $branch_id, $status];

        if ($search_string != null) {
            $sql_session .= " AND (gp.purpose LIKE ? OR s.name LIKE ? OR f.name LIKE ? OR s.admission_number LIKE ? OR s.username LIKE ? 
            OR s.mobile LIKE ? OR f.designation LIKE ? OR f.role LIKE ? OR c.classname LIKE ? OR sec.section_name LIKE ?) ";
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
            $array_params[] = '%' . $search_string . '%';
        }

        $sql_session .= " order by gp.req_date DESC, gp.req_time DESC ";
        $sql_session .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();

    $gatepass_info  = [];

    foreach ($session_rows as $rows) {
        $type = $rows['type'];
        $user_id = $rows['user_id'];
        
        $user_details = [];

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

            // Fetch class and section details
            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, mobile, father_name 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 ($rows['proof_document'] != null and !is_array($rows['proof_document'])) {
            $data_attachment = json_decode($rows['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, $rows['branch_id']);

        $gatepass = [
            "gatepass_id" => $rows['id'],
            "institution_id" => $rows['institution_id'],
            "branch" => $branch,
            "type" => $rows['type'],
            $type . "_details" => $user_details, // This dynamically adds student_details or faculty_details
            "req_date" => $rows['req_date'],
            "purpose" => $rows['purpose'],
            "proof_document" => $final_array_attachment,
            "status" => $rows['status']
        ];
        $gatepass_info[] = $gatepass;
    }

    if (empty($gatepass_info)) {
        errorreturn("No data found.");
    }

    $maxreach = (count($session_rows) < $limit) ? 1 : 0;

    return array('total_rows' => $totalrows, 'gatepass_info' => $gatepass_info, 'maxreach' => $maxreach);
}

if ($postdata['function_type'] == "fetch_gatepass_details") {
    // $institution_id = trim($postdata['institution_id']);
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    // $branch_id = isset($postdata['branch_id']) && !empty($postdata['branch_id']) ? trim($postdata['branch_id']) : null;
    
    $search_string = isset($postdata['search_string']) && !empty($postdata['search_string']) ? trim($postdata['search_string']) : null;

    $status = isset($postdata['status']) ? trim($postdata['status']) : null;
    if ($status === null) {
        errorreturn("Status is required.");
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = get_gatepass_details($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, $offset, $status);
        successreturn($success);
    } else {
        $success['data'] = get_gatepass_details($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, null, $status);
        successreturn($success);
    }
} else {
    errorreturn("Invalid Function Type");
}
