<?php

    session_start();
    include '../../db.php';
    include '../helper_functions/data_request.php';
    include '../auth/auth_functions.php';

    function formatPhoneNumber($phoneNumber) {
        $formattedPhone = preg_replace('/[^0-9]/', '', $phoneNumber);
        if (strlen($formattedPhone) == 10) {
            return '(' . substr($formattedPhone, 0, 3) . ') ' . substr($formattedPhone, 3, 3) . '-' . substr($formattedPhone, 6, 4);
        }
        return $phoneNumber;
    }

    function isNumberUnique($number, $currentId = null, $type = null) {
        $currentpropid = $_SESSION['property'];
    
        try {
            $visitorQuery = "
                SELECT COUNT(*) AS count 
                FROM visitors 
                WHERE (phone = :number OR cidphone = :number) 
                AND property_id = :propertyId
                AND status != :status
            ";
            if ($type === 'visitor') {
                $visitorQuery .= " AND (id != :currentId OR :currentId IS NULL)";
            }

            $vendorQuery = "
                SELECT COUNT(*) AS count 
                FROM vendors 
                WHERE (phone = :number OR cidphone = :number) 
                AND property_id = :propertyId
                AND status != :status
            ";
            if ($type === 'vendor') {
                $vendorQuery .= " AND (id != :currentId OR :currentId IS NULL)";
            }

            $params = [
                'number' => $number,
                'propertyId' => $currentpropid,
                'status' => "Expired",
                'currentId' => $currentId
            ];

            if ($currentId === null) {
                unset($params['currentId']);
            }

            $visitorCount = fetchSingleDataWithJoins($visitorQuery, $params)['count'];
            $vendorCount = fetchSingleDataWithJoins($vendorQuery, $params)['count'];

            return ($visitorCount + $vendorCount) === 0;
        } catch (Exception $e) {
            error_log("Error checking number uniqueness: " . $e->getMessage());
            return false;
        }
    }

    function isKeyCodeUnique($number, $type, $currentId = null) {

        $currentpropid = $_SESSION['property'];
    
        try {

            $visitorQuery = "
                SELECT COUNT(*) AS count 
                FROM visitors 
                WHERE (key_code = :number) 
                AND property_id = :propertyId
            ";
            if ($type === 'visitor' && !empty($currentId)) {
                $visitorQuery .= " AND (id != :currentId OR :currentId IS NULL)";
            }

            $vendorQuery = "
                SELECT COUNT(*) AS count 
                FROM vendors 
                WHERE (key_code = :number) 
                AND property_id = :propertyId
            ";
            if ($type === 'vendor' && !empty($currentId)) {
                $vendorQuery .= "AND id != :currentId";
            }

            $params = [
                'number' => $number,
                'propertyId' => $currentpropid,
                'currentId' => $currentId
            ];

            if (empty($currentId)) {
                unset($params['currentId']);
            }

            $visitorCount = fetchSingleDataWithJoins($visitorQuery, $params)['count'];
            $vendorCount = fetchSingleDataWithJoins($vendorQuery, $params)['count'];

            return ($visitorCount + $vendorCount) === 0;
        } catch (Exception $e) {
            // error_log("Error checking number uniqueness: " . $e->getMessage());
            return false;
        }
    }

    function generateUniqKeyCode() {
        $gpin = rand(1000, 9999);
    
        $result = fetchData('visitors', ['key_code' => $gpin, 'property_id' => $_SESSION['property']]);
        $result1 = fetchData('vendors', ['key_code' => $gpin, 'property_id' => $_SESSION['property']]);

        if (empty($result) && empty($result1)) {
            return $gpin;
        } else {
            return generateUniqKeyCode();
        }
    } 

    function format_number($phone_number) {
        // Remove all non-numeric characters
        $phone_number = preg_replace('/[^0-9]/', '', $phone_number);

        // If the number does not start with 1, add it as the country code
        if (strlen($phone_number) === 10) {
            $phone_number = '1' . $phone_number;
        }

        // Ensure the number is now 11 digits long (1 + 10)
        if (strlen($phone_number) === 11 && substr($phone_number, 0, 1) === '1') {
        }
        else if (strlen($phone_number) === 11 && strpos($phone_number, '0') === 0) {
            $phone_number = '44' . substr($phone_number, 1);
        }
        else if (strlen($phone_number) === 12 && strpos($phone_number, '00') === 0) 
        {
            $phone_number = '44' . substr($phone_number, 2);
        }
        return '+' . $phone_number;
    }

    function base_url() {
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $host = preg_replace('/[^a-zA-Z0-9.\-]/', '', $host);
        $host = preg_replace('/\.+/', '.', $host);
        $host = substr($host, 0, 255);
        if (!filter_var("http://$host", FILTER_VALIDATE_URL)) {
            $host = 'localhost';
        }
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        return "$scheme://$host";
    }

    function send_message_to_visitor($property_id, $to_number, $from_number, $body){
        $signalwire_credentials = fetchDataSingle('signalwire_settings', ['user_id' => $property_id, 'is_property' => 1]);

        if(isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id'])){
            $space_url = $signalwire_credentials['space_url'];
            $project_id = $signalwire_credentials['project_id'];
            $api_token = $signalwire_credentials['api_token'];

            $to_number = format_number($to_number);
            $from_number = format_number($from_number);
            $url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Messages.json";
            $base_url = base_url();
            $statusCallback = $base_url . "/signalwire_call/message_call_back.php";
            $ch = curl_init($url);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, "$project_id:$api_token");
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
                'To' => $to_number,
                'From' => $from_number,
                'Body' => $body,
                'StatusCallback' => $statusCallback,
            ]));

            $response = curl_exec($ch);
            curl_close($ch);
            return $response;
        }
        
    }

    function send_message($property_id, $visitorData, $vendor_visitor){
        $door = fetchDataSingle('gate_doors', ['property_id' => $property_id, 'is_primary' => 1]);
        if(isset($door['id']) && !empty($door['id'])){
            $user_name = $_SESSION['name'];
            $door = fetchDataSingle('gate_doors', ['property_id' => $property_id, 'is_primary' => 1]);
            $property = fetchDataSingle('properties', ['id' => $property_id]);
            $property_address = $property['address'];
            $door_name = "";
            $door_number = "";
            if(!empty($door)){
                $door_name = $door['door_name'];
                $door_number = format_number($door['iiNumber']);

                if($vendor_visitor == "visitor"){
                    $type = $visitorData['keytypeList'];
                    if($type == 1){
                        $to_number = format_number($visitorData['callerid_phone']);
                        $body = $user_name . ' has sent you an invisible key for ' . $property_address . '. When you arrive at ' . $door_name . ' Call ' . $door_number . ', press "2" your caller ID will be recognized to allow entry. Reply STOP to opt out.';
                    }
                    else if($type == 2){
                        $door_key = $visitorData['keycode'];
                        $to_number = format_number($visitorData['visitor_phone']);
                        $body = $user_name . ' has sent you an invisible key for ' . $property_address . '. When you arrive at ' . $door_name . ' Call ' . $door_number . ', press "2" enter your code ' . $door_key  . '. Reply STOP to opt out.';
                    }
                    else if($type == 4){
                        $to_number = format_number($visitorData['cidphone']);
                        $door_key = $visitorData['cidcode'];
                        $body = $user_name . ' has sent you an invisible key for ' . $property_address . '. When you arrive at ' . $door_name . ' Call ' . $door_number . ', press "2" your caller ID will be recognized and you must enter code: ' . $door_key  . '. Reply STOP to opt out.';
                    }
                    else{
                        return 0;
                    }
                }
                else{
                    $type = $visitorData['keytypeList1'];
                    if($type == 1){
                        $type = $visitorData['vcallerid_phone']; 
                        $to_number = format_number($visitorData['vcallerid_phone']);
                        $body = $user_name . ' has sent you an invisible key for ' . $property_address . '. When you arrive at ' . $door_name . ' Call ' . $door_number . ', press "2" your caller ID will be recognized to allow entry. Reply STOP to opt out.'; 
                    }
                    else if($type == 2){
                        $door_key = $visitorData['keycode1'];
                        $to_number = format_number($visitorData['vendor_phone']);
                        $body = $user_name . ' has sent you an invisible key for ' . $property_address . '. When you arrive at ' . $door_name . ' Call ' . $door_number . ', press "2" enter your code ' . $door_key . '. Reply STOP to opt out.';
                    }
                    
                    else if($type == 4){
                        $to_number = format_number($visitorData['vcidphone']);
                        $door_key = $visitorData['vcidcode'];
                        $body = $user_name . ' has sent you an invisible key for ' . $property_address . '. When you arrive at ' . $door_name . ' Call ' . $door_number . ', press "2" your caller ID will be recognized and you must enter code: ' . $door_key . '. Reply STOP to opt out.';
                    }
                    else{
                        return 0;
                    } 
                }

                $message = send_message_to_visitor($property_id, $to_number, $door_number, $body);
                if(!empty($message)){
                    return 1;
                }
            }
        }
        return 0;
    } 
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        if (isset($_POST['getKeyType'])) {

            if (!currentUserHasAccess($pdo, 'visitors', 'read')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }
            $data = [];
            $keyType = fetchData('key_type');
            $doors = fetchData('gate_doors', ['property_id' => $_SESSION['property']]);
            $data['keyType'] = $keyType;
            $data['doors'] = $doors;
            $data['property'] = $_SESSION['property'];
            echo json_encode($data);
            exit();
        }

        if (isset($_POST['visitorName'])) {
            if (!currentUserHasAccess($pdo, 'visitors', 'write')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }

            $visitorData = [];
            foreach ($_POST as $key => $value) {
                if (!empty($value)) {
                    $visitorData[$key] = $value;
                }
            }

            if(!isset($_POST['visitor_message'])){
                $visitorData['visitor_message'] = 0;
            }
            if (isset($_POST['visitor_phone']) && !empty($_POST['visitor_phone'])) {
                $keyMappings = [
                    'visitorId' => 'id',
                    'visitorName' => 'name',
                    'callerid_phone' => 'phone',
                    'keycode' => 'key_code',
                    'visitor_message' => 'visitor_message',
                    'visitor_phone' => 'visitor_phone',
                    'magicpassword' => 'magic_password',
                    'keymode' => 'key_mode',
                    'uses' => 'uses',
                    'total_uses' => 'total_uses',
                    'start_date' => 'start_date',
                    'start_time' => 'start_time',
                    'end_date' => 'end_date',
                    'end_time' => 'end_time',
                    'schedule' => 'schedule',
                    'access' => 'access',
                    'status' => 'status',
                    'keytypeList' => 'key_type',
                    'cidphone' => 'cidphone',
                    'cidcode' => 'cidcode'
                ];
            }else {
                $keyMappings = [
                    'visitorId' => 'id',
                    'visitorName' => 'name',
                    'callerid_phone' => 'phone',
                    'keycode' => 'key_code',
                    'visitor_message' => 'visitor_message',
                    'magicpassword' => 'magic_password',
                    'keymode' => 'key_mode',
                    'uses' => 'uses',
                    'total_uses' => 'total_uses',
                    'start_date' => 'start_date',
                    'start_time' => 'start_time',
                    'end_date' => 'end_date',
                    'end_time' => 'end_time',
                    'schedule' => 'schedule',
                    'access' => 'access',
                    'status' => 'status',
                    'keytypeList' => 'key_type',
                    'cidphone' => 'cidphone',
                    'cidcode' => 'cidcode'
                ];
            }
            
        
            $keyTypeToFields = [
                'callerid' => ['phone'],
                'keycode' => ['key_code'],
                'magicpassword' => ['magic_password'],
                'callerid+code' => ['cidphone', 'cidcode']
            ];
        
            $keyModeToFields = [
                'visitor_message' => ['visitor_message'],
                'uses' => ['uses'],
                'total_uses' => ['total_uses'],
                'date' => ['start_date', 'end_date'],
                'time' => ['start_time', 'end_time'],
                'date_time' => ['start_date', 'end_date', 'start_time', 'end_time'],
                'schedule' => ['schedule'],
            ];
            if(isset($visitorData['callerid_phone']) && !empty($visitorData['callerid_phone'])){
                $visitorData['callerid_phone'] = str_replace(['-', '(', ')', ' '], '', $visitorData['callerid_phone']); 
            }
            if(isset($visitorData['visitor_phone']) && !empty($visitorData['visitor_phone'])){
                $visitorData['visitor_phone'] = str_replace(['-', '(', ')', ' '], '', $visitorData['visitor_phone']);   
            }
            if(isset($visitorData['cidphone']) && !empty($visitorData['cidphone'])){
                $visitorData['cidphone'] = str_replace(['-', '(', ')', ' '], '', $visitorData['cidphone']);   
            }
            if(isset($visitorData['uses']) && !empty($visitorData['uses'])){
                $visitorData['total_uses'] = $visitorData['uses'];
            }
            $currentKeyType = $_POST['keytypeList'] ?? '';
            $currentKeyMode = $_POST['keymode'] ?? '';
            $currentVisitorId = $_POST['visitorId'] ?? null;

            if (!empty($visitorData['keycode']) && !isKeyCodeUnique($visitorData['keycode'], 'visitor', $currentVisitorId)) {
                $_SESSION['alert']['message'] = "The Key Code is already in use.";
                $_SESSION['alert']['type'] = "danger";

                header("Location: ../../dashboard.php?tab=visitors");
                exit();
            }
        
            // Validate Phone Number uniqueness for callerid keytype
            if (!empty($visitorData['callerid_phone']) && !isNumberUnique($visitorData['callerid_phone'], $currentVisitorId, 'visitor')) {
                $_SESSION['alert']['message'] = "The Phone Number is already in use.";
                $_SESSION['alert']['type'] = "danger";
                
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
            }
        
            // Validate Phone Number uniqueness for callerid+code keytype
            if (!empty($visitorData['cidphone']) && !isNumberUnique($visitorData['cidphone'], $currentVisitorId, 'visitor')) {
                $_SESSION['alert']['message'] = "The Phone Number is already in use.";
                $_SESSION['alert']['type'] = "danger";
                
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
            }
        
            if ($currentKeyType === 'callerid+code') {
                if (empty($_POST['cidphone']) || empty($_POST['cidcode'])) {
                    $_SESSION['alert']['message'] = "Caller ID and Code are required.";
                    $_SESSION['alert']['type'] = "danger";
                    
                    header("Location: ../../dashboard.php?tab=visitors");
                    exit();
                }
            }
        
            foreach ($keyTypeToFields as $keyType => $fields) {
                if ($keyType !== $currentKeyType) {
                    foreach ($fields as $field) {
                        $dbField = $keyMappings[$field] ?? $field;
                        $modifiedData[$dbField] = null;
                    }
                }
            }
        
            foreach ($keyModeToFields as $keyMode => $fields) {
                if ($keyMode !== $currentKeyMode) {
                    foreach ($fields as $field) {
                        $dbField = $keyMappings[$field] ?? $field;
                        $modifiedData[$dbField] = null;
                    }
                }
            }
        
            if (isset($visitorData['vschedule'])) {
                $visitorData['schedule'] = $visitorData['vschedule'];
                unset($visitorData['vschedule']);
            }
        
            foreach ($visitorData as $key => $value) {
                if (isset($keyMappings[$key])) {
                    $modifiedData[$keyMappings[$key]] = $value;
                } else {
                    $modifiedData[$key] = $value;
                }
            }
        
            $modifiedData['status'] = 'active';
            $modifiedData['user_assoc'] = $_SESSION['userid'];
            $modifiedData['property_id'] = $_SESSION["property"];
        
            if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer' || $_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                $modifiedData['creator_type'] = 'admin';
            }else if ($_SESSION['isMultiPropUser']) {
                $modifiedData['creator_type'] = 'multi';
            }else {
                $modifiedData['creator_type'] = 'user';
            }
        
            $table = 'visitors';
        
            try {
                if (!empty($currentVisitorId)) {
                    // Update existing visitor
                    $where = 'id = :id';
                    $result = updateTable($table, $modifiedData, $where, ['id' => $currentVisitorId]);
        
                    if ($result) {
                        $_SESSION['alert']['message'] = "Visitor data updated successfully!";
                        $_SESSION['alert']['type'] = "success";
                    } else {
                        $_SESSION['alert']['message'] = "Failed to update visitor data.";
                        $_SESSION['alert']['type'] = "danger";
                    }
                } else {
                    $result = insertData($table, $modifiedData);
                    $insert_id = getLastInsertId();
                    if ($result) {
                        $conc_message = "";
                        if($visitorData['visitor_message'] == 1){
                            $sent_message = send_message($_SESSION["property"], $visitorData, "visitor");
                            if($sent_message == 1){
                                $conc_message = " and message has been sent successfully";
                            }   
                        }

                        createAuditLog($_SESSION["userid"], "Create Visitor", "visitors", $insert_id, $_SESSION["email"]??null, $_SESSION['property'], null, json_encode($visitorData), "New Visitor Added", "Medium","Visitors");
                        
                        $_SESSION['alert']['message'] = "Visitor data inserted successfully" . $conc_message . "!";
                        $_SESSION['alert']['type'] = "success";
                    } else {
                        $_SESSION['alert']['message'] = "Failed to insert visitor data.";
                        $_SESSION['alert']['type'] = "danger";
                    }
                }
        
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
        
            } catch (Exception $e) {
                error_log("Error: " . $e->getMessage());
                echo "An error occurred. Please try again later.";
            }
        }
          
        if (isset($_POST['getVisitors'])) {

            if (!currentUserHasAccess($pdo, 'visitors', 'read')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }

            $userLayer = $_SESSION['layer'];
            $userId = $_SESSION['userid'];
            $selectedProperty = $_SESSION['property'];
            $visitorsData = [];
        
            if ($userLayer === 'super_admin' || $userLayer === 'admin' || $userLayer === 'dealer' || $userLayer === 'sub_dealer' || $userLayer === 'organization admin' || $userLayer === 'property admin') {

                $visitorsData = fetchData('visitors', ['property_id' => $selectedProperty]);
        
            } else {

                $visitorsData = fetchData('visitors', [
                    'user_assoc' => $userId,
                    'property_id' => $selectedProperty
                ]);
            }
        
            foreach ($visitorsData as &$visitor) {

                if (!empty($visitor['phone'])) {
                    $visitor['phone'] = formatPhoneNumber($visitor['phone']);
                }
        
                if (!empty($visitor['user_assoc'])) {

                    if ($visitor['creator_type'] === 'admin') {

                        $userAssocData = fetchData('users', ['id' => $visitor['user_assoc']]);
                        if (!empty($userAssocData)) {
                            $visitor['user_assoc'] = $userAssocData[0]['firstname'] . ' ' . $userAssocData[0]['lastname'];
                        }

                    }else if ($visitor['creator_type'] === 'multi') {

                        $userAssocData = fetchData('multi_prop_users', ['user_assoc' => $visitor['user_assoc'], 'property_id' => $selectedProperty]);
                        if (!empty($userAssocData)) {
                            $visitor['user_assoc'] = $userAssocData[0]['firstname'] . ' ' . $userAssocData[0]['lastname'];
                        }
                    }else {

                        $userAssocData = fetchData('property_users_data', ['property_user' => $visitor['user_assoc']]);
                        if (!empty($userAssocData)) {
                            $visitor['user_assoc'] = $userAssocData[0]['firstname'] . ' ' . $userAssocData[0]['lastname'];
                        }
                    }
                }
        
                if (!empty($visitor['property_id'])) {
                    $propertyData = fetchData('properties', ['id' => $visitor['property_id']]);
                    if (!empty($propertyData)) {
                        $visitor['property_id'] = $propertyData[0]['name'];
                    }
                }
                $current_time = date("H:i:s");
                $today_date = date("Y-m-d");
                if($visitor['status'] != "Expired"){
                    $my_chk = 1;
                    if($visitor['key_mode'] == "date"){
                        if(($visitor['start_date'] <= $today_date) && ($visitor['end_date'] >= $today_date)){
                            $my_chk = 1;
                        }
                        else if(($visitor['start_date'] > $today_date) && ($visitor['end_date'] > $today_date)){
                            $my_chk = 2;
                        }
                        else{
                            $my_chk = 0;   
                        }
                    }
                    else if($visitor['key_mode'] == "time"){
                        if(($visitor['start_time'] < $current_time) && ($visitor['end_time'] < $current_time)){
                            $my_chk = 0;
                        }
                        else if(($visitor['start_time'] > $current_time) && ($visitor['end_time'] > $current_time)){
                            $my_chk = 2;
                        }
                    }
                    else if($visitor['key_mode'] == "date_time"){
                        if($visitor['start_date'] > $today_date){
                            $my_chk = 2;
                        }
                        else if(($visitor['start_date'] >= $today_date) && ($visitor['end_date'] >= $today_date) && ($visitor['start_time'] > $current_time)){
                            $my_chk = 2;
                        }
                        else if(($visitor['start_date'] <= $today_date) && ($visitor['end_date'] > $today_date)){
                            $my_chk = 1;
                        }
                        else if(($visitor['end_date'] == $today_date) && ($visitor['end_time'] >= $current_time)){
                            $my_chk = 1;
                        }   
                        else{
                            $my_chk = 0;
                        }
                    }
                    $status = "Active";
                    if($my_chk == 0){
                        $status = "Expired";
                    }
                    else if($my_chk == 2){
                        $status = "Inactive";
                    }
                    $update_data = [
                        'status' => $status,
                    ];
                    $where = 'id = :id';
                    $params = ['id' => $visitor['id']];
                    updateTable('visitors', $update_data, $where, $params);
                    $visitor['status'] = $status;
                }

                // if(!empty($visitor['door_id'])){
                //     $door_data = fetchDataSingle('gate_doors', ['id' => $visitor['door_id']]);
                // }
                // else{
                    $door_data = fetchDataSingle('gate_doors', ['property_id' => $visitor['property_id'], 'is_primary' => 1]);
                // }
                $door_name = "";
                if(!empty($door_data)){
                    $door_name = $door_data['door_name'];
                }
                $visitor['door_name'] = $door_name;
            }

            if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer' || $_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                $flagData = ["type" => "admin"];
            }else if ($_SESSION['layer'] === 'property admin') {
                $flagData = ['type' => "operator"];
            }else {
                $flagData = ["type" => "user"];
            }
            $visitorsData = ["flag" => $flagData, "data" => $visitorsData]; 
        
            echo json_encode($visitorsData);
            exit();
        }

        if (isset($_POST['getVendors'])) {

            if (!currentUserHasAccess($pdo, 'visitors', 'read')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }

            $userLayer = $_SESSION['layer'];
            $userId = $_SESSION['userid'];
            $selectedProperty = $_SESSION['property'];
            $vendorsData = [];
        
            if ($userLayer === 'super_admin' || $userLayer === 'admin' || $userLayer === 'dealer' || $userLayer === 'property admin') {

                $vendorsData = fetchData('vendors', ['property_id' => $selectedProperty]);
        
            } else {

                $vendorsData = fetchData('vendors', [
                    'user_assoc' => $userId,
                    'property_id' => $selectedProperty
                ]);
            }
        
            foreach ($vendorsData as &$vendor) {
                
                if (!empty($vendor['phone'])) {
                    $vendor['phone'] = formatPhoneNumber($vendor['phone']);
                }
        
                if (!empty($vendor['user_assoc'])) {

                    if ($vendor['creator_type'] === 'admin') {

                        $userAssocData = fetchData('users', ['id' => $vendor['user_assoc']]);
                        if (!empty($userAssocData)) {
                            $vendor['user_assoc'] = $userAssocData[0]['firstname'] . ' ' . $userAssocData[0]['lastname'];
                        }

                    }else if ($vendor['creator_type'] === 'multi') {

                        $userAssocData = fetchData('multi_prop_users', ['user_assoc' => $vendor['user_assoc'], 'property_id' => $selectedProperty]);
                        if (!empty($userAssocData)) {
                            $vendor['user_assoc'] = $userAssocData[0]['firstname'] . ' ' . $userAssocData[0]['lastname'];
                        }
                    }else {

                        $userAssocData = fetchData('property_users_data', ['property_user' => $vendor['user_assoc']]);
                        if (!empty($userAssocData)) {
                            $vendor['user_assoc'] = $userAssocData[0]['firstname'] . ' ' . $userAssocData[0]['lastname'];
                        }
                    }
                }

                if (!empty($vendor['property_id'])) {
                    $propertyData = fetchData('properties', ['id' => $vendor['property_id']]);
                    if (!empty($propertyData)) {
                        $vendor['property_id'] = $propertyData[0]['name'];
                    }
                }

                // if($vendor['status'] != "Expired"){
                //     $today_date = date("Y-m-d");
                //     $my_chk = 1;

                //     if($vendor['key_mode'] == "date"){
                //         if($vendor['end_date'] >= $today_date){
                //             $my_chk = 1;
                //         }
                //         else{
                //             $my_chk = 0;
                //         }
                //     }
                //     else if($vendor['key_mode'] == "date_time"){
                //         $current_time = date("H:i:s");
                //         if(($vendor['end_date'] > $today_date)){
                //             $my_chk = 1;
                //         }
                //         else if(($vendor['end_date'] == $today_date) && ($vendor['end_time'] >= $current_time)){
                //             $my_chk = 1;
                //         }   
                //         else{
                //             $my_chk = 0;
                //         }
                //     }

                //     if($my_chk == 0){
                //         $update_data = [
                //             'status' => "Expired",
                //         ];
                //         $where = 'id = :id';
                //         $params = ['id' => $vendor['id']];
                //         updateTable('vendors', $update_data, $where, $params);
                //         $vendor['status'] = "Expired";
                //     }
                // }
                if($vendor['status'] != "Expired"){
                    $today_date = date("Y-m-d");
                    $my_chk = 1;
                    $current_time = date("H:i:s");
                    if($vendor['key_mode'] == "date"){
                        if(($vendor['start_date'] <= $today_date) && ($vendor['end_date'] >= $today_date)){
                            $my_chk = 1;
                        }
                        else if(($vendor['start_date'] > $today_date) && ($vendor['end_date'] > $today_date)){
                            $my_chk = 2;
                        }
                        else{
                            $my_chk = 0;   
                        }
                    }
                    else if($vendor['key_mode'] == "time"){
                        if(($vendor['start_time'] < $current_time) && ($vendor['end_time'] < $current_time)){
                            $my_chk = 0;
                        }
                        else if(($vendor['start_time'] > $current_time) && ($vendor['end_time'] > $current_time)){
                            $my_chk = 2;
                        }
                    }
                    else if($vendor['key_mode'] == "date_time"){
                        if($vendor['start_date'] > $today_date){
                            $my_chk = 2;
                        }
                        else if(($vendor['start_date'] >= $today_date) && ($vendor['end_date'] >= $today_date) && ($vendor['start_time'] > $current_time)){
                            $my_chk = 2;
                        }
                        else if(($vendor['start_date'] <= $today_date) && ($vendor['end_date'] > $today_date)){
                            $my_chk = 1;
                        }
                        else if(($vendor['end_date'] == $today_date) && ($vendor['end_time'] >= $current_time)){
                            $my_chk = 1;
                        }   
                        else{
                            $my_chk = 0;
                        }
                    }
                    $status = "Active";
                    if($my_chk == 0){
                        $status = "Expired";
                    }
                    else if($my_chk == 2){
                        $status = "Inactive";
                    }
                    $update_data = [
                        'status' => $status,
                    ];
                    $where = 'id = :id';
                    $params = ['id' => $vendor['id']];
                    updateTable('vendors', $update_data, $where, $params);
                    $vendor['status'] = $status;
                }

                // if(!empty($vendor['door_id'])){
                //     $door_data = fetchDataSingle('gate_doors', ['id' => $vendor['door_id']]);
                // }
                // else{
                    $door_data = fetchDataSingle('gate_doors', ['property_id' => $vendor['property_id'], 'is_primary' => 1]);
                // }
                $door_name = "";
                if(!empty($door_data)){
                    $door_name = $door_data['door_name'];
                }
                $vendor['door_name'] = $door_name;
            }
        
            echo json_encode($vendorsData);
            exit();
        }
        
        if (isset($_POST['vendorName'])) {

            if (!currentUserHasAccess($pdo, 'visitors', 'write')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }

            $vendorData = [];
            foreach ($_POST as $key => $value) {
                if (!empty($value)) {
                    $vendorData[$key] = $value;
                }
            }
            
            if(!isset($_POST['vendor_message'])){
                $vendorData['vendor_message'] = 0;
            }
            $keyMappings = [
                'vendorId' => 'id',
                'vendorCompany' => 'company',
                'vendorName' => 'name',
                'vcallerid_phone' => 'phone',
                'keycode1' => 'key_code',
                'vendor_message' => 'vendor_message',
                'vendor_phone' => 'vendor_phone',
                'vmagicpassword' => 'magic_password',
                'keymode1' => 'key_mode',
                'vuses' => 'uses',
                'total_uses' => 'total_uses',
                'vstart_date' => 'start_date',
                'vstart_time' => 'start_time',
                'vend_date' => 'end_date',
                'vend_time' => 'end_time',
                'vstart_date1' => 'start_date',
                'vstart_time1' => 'start_time',
                'vend_date1' => 'end_date',
                'vend_time1' => 'end_time',
                'vschedule' => 'schedule',
                'access' => 'access',
                'status' => 'status',
                'keytypeList1' => 'key_type',
                'vcidphone' => 'cidphone',
                'vcidcode' => 'cidcode'
            ];
        
            $keyTypeToFields = [
                'callerid' => ['phone'],
                'keycode' => ['key_code'],
                'magicpassword' => ['magic_password'],
                'callerid+code' => ['cidphone', 'cidcode']
            ];
        
            $keyModeToFields = [
                'visitor_message' => ['vendor_message'],
                'uses' => ['uses'],
                'total_uses' => ['total_uses'],
                'date' => ['start_date', 'end_date'],
                'time' => ['start_time', 'end_time'],
                'date_time' => ['start_date', 'end_date', 'start_time', 'end_time'],
                'schedule' => ['schedule'],
            ];
        
            $currentKeyType = $_POST['keytypeList1'];
            $currentKeyMode = $_POST['keymode1'];
            $currentVendorId = $_POST['vendorId'] ?? null;
            if(isset($vendorData['vcallerid_phone']) && !empty($vendorData['vcallerid_phone'])){
                $vendorData['vcallerid_phone'] = str_replace(['-', '(', ')', ' '], '', $vendorData['vcallerid_phone']);
            }
            if(isset($vendorData['vendor_phone']) && !empty($vendorData['vendor_phone'])){
                $vendorData['vendor_phone'] = str_replace(['-', '(', ')', ' '], '', $vendorData['vendor_phone']);
            }
            if(isset($vendorData['vcidphone']) && !empty($vendorData['vcidphone'])){
                $vendorData['vcidphone'] = str_replace(['-', '(', ')', ' '], '', $vendorData['vcidphone']);
            }
            
            if(isset($vendorData['vuses']) && !empty($vendorData['vuses'])){
                $vendorData['total_uses'] = $vendorData['vuses'];
            }
            // Validate Key Code uniqueness for key_code keytype
            if (!empty($vendorData['keycode1']) && !isKeyCodeUnique($vendorData['keycode1'], 'vendor', $currentVendorId)) {
                $_SESSION['alert']['message'] = "The Key Code is already in use.";
                $_SESSION['alert']['type'] = "danger";
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
            }
        
            // Validate Phone Number uniqueness for callerid keytype
            
            if (!empty($vendorData['vcallerid_phone']) && !isNumberUnique($vendorData['vcallerid_phone'], $currentVendorId, 'vendor')) {
                $_SESSION['alert']['message'] = "The Phone Number is already in use.";
                $_SESSION['alert']['type'] = "danger";
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
            }
        
            // Validate Phone Number uniqueness for callerid+code keytype
            if (!empty($vendorData['vcidphone']) && !isNumberUnique($vendorData['vcidphone'], $currentVendorId, 'vendor')) {
                $_SESSION['alert']['message'] = "The Phone Number is already in use.";
                $_SESSION['alert']['type'] = "danger";
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
            }
        
            if ($currentKeyType === 'callerid+code') {
                if (empty($_POST['vcidphone']) || empty($_POST['vcidcode'])) {
                    $_SESSION['alert']['message'] = "Caller ID and Code are required.";
                    $_SESSION['alert']['type'] = "danger";
                    header("Location: ../../dashboard.php?tab=visitors");
                    exit();
                }
            }
        
            foreach ($keyTypeToFields as $keyType => $fields) {
                if ($keyType !== $currentKeyType) {
                    foreach ($fields as $field) {
                        $dbField = $keyMappings[$field] ?? $field;
                        $modifiedData[$dbField] = null;
                    }
                }
            }
        
            foreach ($keyModeToFields as $keyMode => $fields) {
                if ($keyMode !== $currentKeyMode) {
                    foreach ($fields as $field) {
                        $dbField = $keyMappings[$field] ?? $field;
                        $modifiedData[$dbField] = null;
                    }
                }
            }
        
            foreach ($vendorData as $key => $value) {
                if (isset($keyMappings[$key])) {
                    $modifiedData[$keyMappings[$key]] = $value;
                } else {
                    $modifiedData[$key] = $value;
                }
            }
        
            $modifiedData['status'] = 'active';
            $modifiedData['user_assoc'] = $_SESSION['userid'];
            $modifiedData['property_id'] = $_SESSION["property"];
        
            if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer' || $_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                $modifiedData['creator_type'] = 'admin';
            }else if ($_SESSION['isMultiPropUser']) {
                $modifiedData['creator_type'] = 'multi';
            }else {
                $modifiedData['creator_type'] = 'user';
            }
        
            $table = 'vendors';
        
            try {
                if (!empty($currentVendorId)) {
                    // Update existing vendor
                    $where = 'id = :id';
                    $result = updateTable($table, $modifiedData, $where, ['id' => $currentVendorId]);
        
                    if ($result) {
                        $_SESSION['alert']['message'] = "Vendor data updated successfully!";
                        $_SESSION['alert']['type'] = "success";
                    } else {
                        $_SESSION['alert']['message'] = "Failed to update vendor data.";
                        $_SESSION['alert']['type'] = "danger";
                    }
                } else {
                    // Insert new vendor
                    $result = insertData($table, $modifiedData);
                    $insert_id = getLastInsertId();
                    if ($result) {
                        $conc_message = "";
                        if($vendorData['vendor_message'] == 1){
                            $sent_message = send_message($_SESSION["property"], $vendorData, "vendor");
                            if($sent_message == 1){
                                $conc_message = " and message has been sent successfully";
                            }
                        }
                        createAuditLog($_SESSION["userid"], "Create Vendor", "vendors", $insert_id, $_SESSION["email"]??null, $_SESSION['property'], null, json_encode($vendorData), "New Vendor Added", "Medium","Vendors");
                        $_SESSION['alert']['message'] = "Vendor data inserted successfully!";
                        $_SESSION['alert']['type'] = "success";
                    } else {
                        $_SESSION['alert']['message'] = "Failed to insert vendor data.";
                        $_SESSION['alert']['type'] = "danger";
                    }
                }
        
                header("Location: ../../dashboard.php?tab=visitors");
                exit();
        
            } catch (Exception $e) {
                error_log("Error: " . $e->getMessage());
                echo "An unexpected error occurred. Please try again later.";
            }
        }
        
        if (isset($_POST['deleteVisitor'])) {

            if (!currentUserHasAccess($pdo, 'visitors', 'delete')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }
            $visitor_id = $_POST['userid'];
            $visitor_data = fetchDataSingle('visitors', ['id' => $visitor_id]);
            createAuditLog($_SESSION["userid"], "Delete Visitor", "visitors", $visitor_id, $_SESSION["email"]??null, $_SESSION['property'], json_encode($visitor_data), null, "Deleted Visitor", "Medium", "Visitors");

            deleteData('visitors', 'id', $_POST['userid']);

            echo 'Success';
            return;
        }

        if (isset($_POST['deleteVendor'])) {

            if (!currentUserHasAccess($pdo, 'visitors', 'delete')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }
            
            $vendor_id = $_POST['userid'];
            $vendor_data = fetchDataSingle('vendors', ['id' => $vendor_id]);
            
            createAuditLog($_SESSION["userid"], "Delete Vendor", "vendors", $vendor_id, $_SESSION["email"]??null, $_SESSION['property'], json_encode($vendor_data), null, "Deleted Vendor", "Medium", "Vendors");
            
            deleteData('vendors', 'id', $_POST['userid']);

            echo 'Success';
            return;
        }

        if (isset($_POST['action']) && $_POST['action'] === 'getVisitorDetails') {

            if (!currentUserHasAccess($pdo, 'visitors', 'read')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }

            $visitorId = $_POST['visitorId'];
        
            $visitorData = fetchDataSingle('visitors', ['id' => $visitorId]);
            $door_data = fetchDataSingle('gate_doors', ['id' => $visitorData['door_id']]);
            $keyTypeData = fetchData('key_type');
            $visitorData['key_types'] = $keyTypeData;
            $visitorData['door_data'] = $door_data;
            echo json_encode([
                    'success' => true,
                    'data' => $visitorData
                ]);
            if (empty($visitorData)) {
                
                echo json_encode([
                    'success' => false,
                    'message' => 'Visitor or key type data not found.'
                ]);
            }
        
            exit();
        }

        if (isset($_POST['action']) && $_POST['action'] === 'getVendorDetails') {
            
            if (!currentUserHasAccess($pdo, 'visitors', 'read')) {
                echo json_encode(['error' => 'Access Denied']);
                exit();
            }

            $vendorId = $_POST['vendorId'];
        
            $vendorData = fetchDataSingle('vendors', ['id' => $vendorId]);

            $keyTypeData = fetchData('key_type');
            $vendorData['key_types'] = $keyTypeData;

            if (!empty($vendorData) && !empty($keyTypeData)) {
                echo json_encode([
                    'success' => true,
                    'data' => $vendorData
                ]);
                // echo json_encode([
                //     'success' => true,
                //     'data' => [
                //         'id' => $vendorData[0]['id'],
                //         'company' => $vendorData[0]['company'],
                //         'name' => $vendorData[0]['name'],
                //         'key_mode' => $vendorData[0]['key_mode'],
                //         'uses' => $vendorData[0]['uses'],
                //         'start_date' => $vendorData[0]['start_date'],
                //         'end_date' => $vendorData[0]['end_date'],
                //         'start_time' => $vendorData[0]['start_time'],
                //         'end_time' => $vendorData[0]['end_time'],
                //         'key_type' => $vendorData[0]['key_type'],
                //         'phone' => $vendorData[0]['phone'],
                //         'key_code' => $vendorData[0]['key_code'],
                //         'magic_password' => $vendorData[0]['magic_password'],
                //         'schedule' => $vendorData[0]['schedule'],
                //         'access' => $vendorData[0]['access'],
                //         'status' => $vendorData[0]['status'],
                //         'user_assoc' => $vendorData[0]['user_assoc'],
                //         'creator_type' => $vendorData[0]['creator_type'],
                //         'property_id' => $vendorData[0]['property_id'],
                //         'key_types' => $keyTypeData,
                //         'cidphone' => $vendorData[0]['cidphone'],
                //         'cidcode' => $vendorData[0]['cidcode']
                //     ]
                // ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Vendor or key type data not found.'
                ]);
            }
        
            exit();
        }

        if (isset($_POST['checkKeyCode'])) {
            $resultCode = generateUniqKeyCode();
            echo json_encode($resultCode);
            exit();
        }
        
    }
      