<?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";
require_once $base_path_to_learning . 'functions/common_functions.php';

//db access function
require_once $base_path_to_learning_resources . "includes/specific_db_config.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 . "user_management/functions/functions.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['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['jwt_token']) or !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("all fields are required.");
}

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;
$name = $jwt_validate->data->name;


//Files to Validate Institute_Id & branch_Id
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

//Validate institution_id and branch_id



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

function getvisitorslog($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $search_string, $branch_id, $limit, $offset, $name, $organisation, $typeofrequest, $sort)
{
    $sql = "SELECT count(*) as total_rows FROM visitors_log WHERE institution_id = ?";
    $array_params = [$institution_id];

    if ($branch_id != 'all') {
        $sql .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($search_string != null) {
        $sql .= " AND (name LIKE ? OR organisationname LIKE ?)";
        $array_params[] = "%" . $search_string . "%";
        $array_params[] = "%" . $search_string . "%";
    }
    if (!is_null($typeofrequest)) {
        if ($typeofrequest == 'current') {
            $sql .= " AND status IN (0,1)";
        } elseif ($typeofrequest == 'history') {
            $sql .= " AND status IN (2,-1)";
        } else {
            errorreturn("Invalid typeofrequest " . $typeofrequest);
        }
    }


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

    if ($sort == 'timedesc') {
        $sort_order = 'request_time DESC';
    } elseif ($sort == 'timeasc') {
        $sort_order = 'request_time ASC';
    } elseif ($sort == 'nameasc') {
        $sort_order = 'name ASC';
    } elseif ($sort == 'namedesc') {
        $sort_order = 'name DESC';
    } else {
        $sort_order = 'request_time DESC';
    }


    if ($limit == 'all') {
        $sql = "SELECT * FROM visitors_log WHERE institution_id = ?";
        $array_params = [$institution_id];
        if ($branch_id != 'all') {
            $sql .= " AND branch_id = ?";
            $array_params[] = $branch_id;
        }

        if ($search_string != null) {
            $sql .= " AND (name LIKE ? OR organisationname LIKE ?)";
            $array_params[] = "%" . $search_string . "%";
            $array_params[] = "%" . $search_string . "%";
        }

        if (!is_null($typeofrequest)) {
            if ($typeofrequest == 'current') {
                $sql .= " AND status IN (0,1)";
            } elseif ($typeofrequest == 'history') {
                $sql .= " AND status IN (2,-1)";
            }
        }

        $sql .= " ORDER BY " . $sort_order;
    } else {
        $sql = "SELECT * FROM visitors_log WHERE institution_id = ?";
        $array_params = [$institution_id];
        if ($branch_id != 'all') {
            $sql .= " AND branch_id = ?";
            $array_params[] = $branch_id;
        }

        if ($search_string != null) {
            $sql .= " AND (name LIKE ? OR organisationname LIKE ?)";
            $array_params[] = "%" . $search_string . "%";
            $array_params[] = "%" . $search_string . "%";
        }

        if (!is_null($typeofrequest)) {
            if ($typeofrequest == 'current') {
                $sql .= " AND status IN (0,1)";
            } elseif ($typeofrequest == 'history') {
                $sql .= " AND status IN (2,-1)";
            }
        }

        $sql .= " ORDER BY " . $sort_order;
        $sql .= " LIMIT " . $offset . " ," . $limit . "";
    }

  
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();
   
    $array_return = array();

    foreach ($result as $rows) {
        $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
        // $authorized_by_name = $rows['authorized_by'] != null and $rows['authorized_by'] != '' ? getSpecificUsernameName($conn_rjllearning, $institution_id, $rows['authorized_by']) : null; 
        // $authorized
        
        if($rows['authorized_by'] !=null){
        $authorized_by_name =  getSpecificUsernameName($conn_rjllearning, $institution_id,$GLOBALS['workspace_id'], $rows['authorized_by']) ; 
        }else{
            $authorized_by_name =null;
        }
        
        $entry_time = $rows['entry_time'] !== null ? date('H:i a', $rows['entry_time']) : null; // Check for null & Formatting entry_time
        $exit_time = $rows['exit_time'] !== null ? date('H:i a', $rows['exit_time']) : null; // and exit_time  to show only the time
        $rejected_time = $rows['rejected_time'] !== null ? date('H:i a', $rows['rejected_time']) : null;
        
        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;
        }
        
        $array_return[] = array(
            "visitors_log_id" => $rows['id'],
            "student_id" => $rows['student_id'],
            'branch_id' => $branch,
            "name" => $rows['name'],
            "organisationname" => $rows['organisationname'],
            "address" => $rows['address'],
            // "request_time" => $rows['request_time'],
            "request_time" => date('H:i a', $rows['request_time']),
            "date" => $rows['date'],
            "entry_time" => $entry_time,
            "exit_time" => $exit_time,
            "rejected_time" => $rejected_time,
            "requested_by" => $rows['requested_by'],
            "authorized_by" => $authorized_by_name,
            "purpose" => $rows['purpose'],
            "description" => $rows['description'],
            "remarksby_authoriser" => $rows['remarksby_authoriser'],
            "proof_document" => $final_array_attachment,
            'status' => $rows['status']
        );
    }

    if (count($result) < 50) {
        return array('total_rows' => $totalrows, 'visitor_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'visitor_info' => $array_return, 'maxreach' => 0);
    }
}


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

    $institution_id = trim($postdata['institution_id']);
    $specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
    if (!$specific_db_name) {
        errorreturn('Access denied.');
    } else {
        $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
    }
    $academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($academic_id == false) {
        errorreturn("Access denied. Academic session not active.");
    }
    


    if (isset($postdata['branch_id']) and !empty($postdata['branch_id']) and trim($postdata['branch_id'])) {
        $branch_id = trim($postdata['branch_id']);
    } else {
        $branch_id = 'all';
    }
    if (isset($postdata['sort']) and !empty($postdata['sort']) and trim($postdata['sort'])) {
        $sort = trim($postdata['sort']);
    } else {
        $sort = 'all';
    }
    

    $typeofrequest = trim($postdata['typeofrequest']);
    
    // $branch_id = trim($postdata['branch_id']);
    
    //Specific Db Connection

    $name = isset($postdata['name']) ? trim($postdata['name']) : null;
    $organisation = isset($postdata['organisationname']) ? trim($postdata['organisationname']) : null;
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }
    $limit = $postdata['limit'];
    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int) $postdata['page'] : 1;
    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
    } else {
        $offset = null;
    }

    $success['data'] = getvisitorslog($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $search_string, $branch_id, $limit, $offset, $name, $organisation, $typeofrequest, $sort);
    successreturn($success);
}
