<?php
// header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

if (session_status() === PHP_SESSION_NONE) session_start();
include '../../helper_functions/data_request.php';
include '../../../db.php';
include '../../auth/auth_functions.php';

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized to access. Please login"]);
    exit;
}

try {
    if (isset($_POST['addHardwareRequest'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $_POST['created_by'] = $_SESSION['userid'];

        if(!isset($_POST["http_port"]) || $_POST["http_port"]==""){
            $_POST["http_port"]=null;
        }
        $validationResult = validatePayload($_POST);
        if(!$validationResult["success"]){
            sendJsonResponse(400, ["error" => json_encode($validationResult["errors"])]);
            exit;
        }
        $keys = ['property_id','sms_io_duration','invisible_intercom_control_number','sms_io_number','complete_url','user_name','password','hardware_is_active', 'model', 'device_type', 'image_path', 'ip_address', 'subnet', 'gateway', 'dns1', 'dns2', 'http_port', 'https_port', 'smtp_port', 'created_by']; 
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('hardware_devices', $data);
        $last_hardware_id = getLastInsertId();
        $last_data = fetchDataSingle('hardware_devices', ['id' => $last_hardware_id]);
        if ($response == false) sendJsonResponse(500, ["error" => "Could not add hardware"]);
        createAuditLog(
            $_SESSION["userid"],
            'Create hardware',
            'hardware_devices',
            $response['id']??null,
            $_SESSION["email"]??null,
            $_POST['property_id']??null,
            null,
            json_encode($last_data),
            'Hardware added',
            'high',
            'Hardware'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['getHardwareRequest'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $response = fetchData('hardware_devices', ['property_id' => $_POST['property_id']]);
        if ($response === false) sendJsonResponse(500, ["error" => "Could not get hardwares"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['deleteHardwareDevice'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')){
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $hardware_data = fetchDataSingle('hardware_devices', ['id' => $_POST['id']]);
        $response = deleteData('hardware_devices', 'id',  $_POST['id']);
        if ($response == false) sendJsonResponse(500, ["error" => "Could not delete the hardware"]);

        createAuditLog(
            $_SESSION["userid"],
            'Delete hardware',
            'hardware_devices',
            $_POST['id'],
            $_SESSION["email"],
            $_POST['property_id'] ?? null,
            json_encode($hardware_data),
            null,
            'Hardware device deleted',
            'high',
            'Hardware'
        );
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['getHardwareById'])) {
        $response = fetchDataWithId('hardware_devices', $_POST['id']);
        if ($response == false) sendJsonResponse(500,  ["error" => "Could not get hardware by id"]);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['editHardwareRequest'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $_POST['created_by'] = $_SESSION['userid'];

        if(!isset($_POST["http_port"]) || $_POST["http_port"]==""){
            $_POST["http_port"]=null;
        }

        $validationResult = validatePayload($_POST);
        if(!$validationResult["success"]){
            sendJsonResponse(400, ["error" => json_encode($validationResult["errors"])]);
            exit;
        }
        $keys = ['property_id','sms_io_duration','invisible_intercom_control_number','sms_io_number','complete_url','user_name','password','hardware_is_active', 'model', 'device_type', 'image_path', 'ip_address', 'subnet', 'gateway', 'dns1', 'dns2', 'http_port', 'https_port', 'smtp_port', 'created_by']; 
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $old_hardware_data = fetchDataSingle('hardware_devices', ['id' => $_POST['id']]);
        $updateSuccess = updateTable('hardware_devices',  $data,  $where,  $params);
        $updated_hardware_data = fetchDataSingle('hardware_devices', ['id' => $_POST['id']]);
        $response = $updateSuccess;
        if ($response == false) sendJsonResponse(500,  ["error" => "Could not Edit hardware"]);
        createAuditLog(
            $_SESSION["userid"],
            'Update hardware',
            'hardware_devices',
            $_POST['id'] ?? null,
            $_SESSION["email"]??null,
            $_POST['property_id'] ?? null,
            json_encode($old_hardware_data),
            json_encode($updated_hardware_data),
            'Hardware updated',
            'high',
            'Hardware'
        );
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['checkHardwareStatusRequest'])) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $_POST['request_url'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_DIGEST,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode( 
                    ($_POST['userName'] ?? '') . ':' . ($_POST['password'] ?? '')
                )
            ),
        ));

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $response = curl_exec($curl);
        $curlError = curl_error($curl);
        curl_close($curl);
        if ($response == false) sendJsonResponse(500,  ["error" => "Could not get Status of " . $_POST['request_url']]);
        if ($httpCode === 404 || $httpCode === 401 || $httpCode === 403 || strpos($response,"401 Error") || strpos($response, '404 Not Found') !== false) {
            $bodyText = strip_tags($response);
            $responseCode=404;
            if(strpos($response,"401 Error")) $responseCode=401;
            if(strpos($response,"403 Error")) $responseCode=403;

            sendJsonResponse($responseCode, [
                "success" => false,
                "data" => $bodyText
            ]);
            exit;
        } 
        if(!empty($curlError)){
            sendJsonResponse(500,  ["error" => "Could not get Status of " . $_POST['request_url']]);
            exit;
        }

        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['addHardwareSettingsRequest'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        // sendJsonResponse(400,  ["error" => "Please select property id.". $_POST['ipPort']]);
        // exit;
        $_POST['created_by'] = $_SESSION['userid'];
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;

        if(!isset($_POST['property_id'])){
            sendJsonResponse(400,  ["error" => "Please select property id."]);
            exit;
        }
        $isDoorAssigned=fetchData("hardwares_settings",["property_id"=>$_POST['property_id'],"assigned_door"=>$_POST['assigned_door']]);
        if(isset($isDoorAssigned) && isset($isDoorAssigned[0])){
            sendJsonResponse(400,  ["error" => "Door is already assigned to a device. Please choose another door", "errorData" => $isDoorAssigned[0]]);
            exit;
        }
        if(isset($_POST['timer']) && $_POST['timer']=='null'){
            $_POST['timer']=null;
        }
        if(!isset($_POST['ipPort']) || $_POST['ipPort']==""){
            $_POST['ipPort']=null;
        }

        if(!isset($_POST['created_by'])){
            $_POST['created_by']=$_SESSION['userid'] ?? null;
            $_POST['created_by_email']=$_SESSION['email'] ?? null;
        }

        $keys = ['device_id', 'property_id','sms_duration', 'assigned_door', 'timer', 'inputs', 'output', 'status', 'ipAddress', 'ipPort', 'completeUrl', 'created_by', 'created_by_email','status_check_date'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('hardwares_settings',  $data);
        $last_hardware_setting_id = getLastInsertId();
        $last_hardware_setting_data = fetchDataSingle('hardwares_settings', ['id' => $last_hardware_setting_id]);
        if ($response == false) sendJsonResponse(500,  ["error" => "Could not add hardware settings"]);
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'hardwares_settings',
            $response['id']??null,
            $_SESSION["email"]??null,
            $_POST['property_id']??null,
            null,
            json_encode($last_hardware_setting_data),
            'Hardware settings created',
            'high',
            'Hardware'
        );
        
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['EditHardwareSettingsRequest'])) {
        if (empty($_POST['command_center_update']) && !currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        if(isset($_POST['timer']) && $_POST['timer']=='null'){
            $_POST['timer']=null;
        }
        if(!isset($_POST['ipPort']) || $_POST['ipPort']==""){
            $_POST['ipPort']=null;
        }

        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        if(!isset($_POST['property_id'])){
            sendJsonResponse(400,  ["error" => "Please select property id."]);
            exit;
        }
        if(!empty($_POST['assigned_door'])){
            $isDoorAssigned=fetchData("hardwares_settings",["property_id"=>$_POST['property_id'],"assigned_door"=>$_POST['assigned_door']]);
            if(!empty($isDoorAssigned) && !empty($isDoorAssigned[0])){
                if($isDoorAssigned[0]["id"]==$_POST['id'] && $isDoorAssigned[0]["assigned_door"]==$_POST['assigned_door']){
                }else {
                    sendJsonResponse(400,  ["error" => "Door is already assigned to a device. Please choose another door", "errorData" => $isDoorAssigned[0]]);
                    exit;
                } 
            }
        }

        $keys = ['device_id', 'assigned_door', 'sms_duration' , 'timer', 'inputs', 'output', 'status', 'ipAddress', 'ipPort', 'completeUrl', 'created_by','status_check_date'];
        $data = array_intersect_key($_POST, array_flip($keys));
        if (isset($data['timer']) && $data['timer'] === '') {
            $data['timer'] = null;
        }
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $old_setting_data = fetchDataSingle('hardwares_settings', ['id' => $_POST['id']]);
        $response = updateTable('hardwares_settings',  $data,  $where,  $params);
        $new_setting_data = fetchDataSingle('hardwares_settings', ['id' => $_POST['id']]);
        if ($response == false) sendJsonResponse(500,  ["error" => "Could not add hardware settings"]);
        
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'hardwares_settings',
            $_POST['id']?? null,
            $_SESSION["email"],
            $_SESSION['property']?? null,
            json_encode($old_setting_data),
            json_encode($new_setting_data),
            'Hardware settings for door updated',
            'high',
            'Hardware'
        );

        sendJsonResponse(200,  [
            "success" => true,
            "data" => "Its edited Now "
        ]);
    }

    if (isset($_POST['getHardwareSettingsDataRequest'])) {
        $sql = "
            SELECT 
                hardwares_settings.id, 
                hardwares_settings.device_id, 
                hardwares_settings.section, 
                hardwares_settings.assigned_door, 
                hardwares_settings.inputs, 
                hardwares_settings.sms_duration, 
                hardwares_settings.output, 
                hardwares_settings.function, 
                hardwares_settings.status, 
                hardwares_settings.timer, 
                hardwares_settings.ipAddress, 
                hardwares_settings.ipPort, 
                hardwares_settings.completeUrl, 
                hardwares_settings.status_check_date, 
                hardwares_settings.created_at, 
                hardwares_settings.updated_at,
                gate_doors.door_name, 
                gate_doors.id AS gate_door_id ,
                calendar_added_events.title,
                calendar_added_events.start,
                calendar_added_events.end,
                calendar_added_events.backgroundColor,
                calendar_added_events.borderColor,
                calendar_added_events.allDay,
                calendar_added_events.created_at AS calendar_event_created_at,
                calendar_added_events.id AS calendarId
            FROM 
                hardwares_settings 
             JOIN 
                gate_doors ON hardwares_settings.assigned_door = gate_doors.id 
            LEFT JOIN 
                calendar_added_events ON hardwares_settings.timer = calendar_added_events.id
            WHERE 
                hardwares_settings.device_id = :id;
        ";
        $response = fetchDataWithJoins($sql, [':id' => $_POST['id']]);

        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get hardware settings"]);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['deleteHardwareSettingsDataRequest'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')){
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }
        $hardware_settings_data = fetchDataSingle('hardwares_settings', ['id' => $_POST['id']]);
        $response = deleteData('hardwares_settings', 'id',  $_POST['id']);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not Delete hardware settings"]);

        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'hardwares_settings',
            $_POST['id']?? null,
            $_SESSION["email"],
            $_SESSION['property']?? null,
            json_encode($hardware_settings_data),
            null,
            'Hardware settings for door has deleted',
            'high',
            'Hardware'
        );
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['getAllHardwareSettingsDataRequest'])) {
        $sql = "
            SELECT 
                hardwares_settings.id, 
                hardwares_settings.device_id, 
                hardwares_settings.section, 
                hardwares_settings.assigned_door, 
                hardwares_settings.inputs, 
                hardwares_settings.output, 
                hardwares_settings.function, 
                hardwares_settings.status, 
                hardwares_settings.timer, 
                hardwares_settings.ipAddress, 
                hardwares_settings.ipPort, 
                hardwares_settings.completeUrl, 
                hardwares_settings.created_at, 
                hardwares_settings.updated_at,
                gate_doors.door_name, 
                gate_doors.door_image, 
                gate_doors.id AS gate_door_id,
                
                calendar_added_events.title,
                calendar_added_events.start,
                calendar_added_events.end,
                calendar_added_events.backgroundColor,
                calendar_added_events.borderColor,
                calendar_added_events.allDay,
                calendar_added_events.created_at AS calendar_event_created_at,
                calendar_added_events.id AS calendarId
            FROM 
                hardwares_settings 
            JOIN 
                gate_doors ON hardwares_settings.assigned_door = gate_doors.id 
            LEFT JOIN 
                calendar_added_events ON hardwares_settings.timer = calendar_added_events.id
            WHERE 
                hardwares_settings.created_by = :id
        ";
        $response = fetchDataWithJoins($sql,  [':id' => $_SESSION['userid']]);

        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get hardware settings"]);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['getScheduleRequest'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (!$_POST['property_id']) {
            sendJsonResponse(400, ["error" => "Property ID is required."]);
            exit;
        }

        if(($_POST['type'] ?? '') == 'visitor'){
            $response = fetchData('calendar_added_events', ['property_id'=>$_POST['property_id'],'schedule_type'=>'visitor']);
        }elseif(($_POST['type'] ?? '') == 'door'){
            $response = fetchData('calendar_added_events', ['property_id'=>$_POST['property_id'],'schedule_type'=>'door']);
        }else{
            $response = fetchData('calendar_added_events', ['property_id'=>$_POST['property_id']]);
        }

        if ($response === false){
            sendJsonResponse(500,  ["error" => "Could not get schedules"]);
            exit;
        }
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['add_hardwares_settings_events'])) {
        $_POST['created_by'] = $_SESSION['userid'];
        $utcTime = new DateTime('now', new DateTimeZone('UTC'));
        $_POST['timestamp'] = $utcTime->format('Y-m-d\TH:i:s\Z');
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $event_of = $_POST['eventOf'];
        $file_name = "";
        $snap_image = "";
        if((!empty($event_of)) && ($_POST['eventName'] != "Release")){
            $hardware_event = fetchDataSingle('hardwares_settings', ['id' => $event_of]);
            $door_id = $hardware_event['assigned_door'];
            $save_snap = storeSnapshotImage($door_id, $_POST['property_id']);
            if(isset($save_snap['filename']) && !empty($save_snap['filename'])){
                $file_name = $save_snap['filename'];
            }
            if(isset($save_snap['failSnap']) && !empty($save_snap['failSnap'])){
                $snap_image = $save_snap['failSnap'];
            }
        }
        $_POST['file_name'] = $file_name;
        $_POST['camera_snap'] = $snap_image;

        $keys = ['eventName', 'eventType', 'eventDetail', 'eventOf', 'URL', 'created_by', 'property_id', 'timestamp', 'file_name', 'camera_snap'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('hardwares_settings_events',  $data);
        $last_event_id = getLastInsertId();
        $last_event_data = fetchDataSingle('hardwares_settings_events', ['id' => $last_event_id]);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get schedules"]);

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'hardwares_settings_events',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            null,
            json_encode($last_event_data),
            ''.$_POST['eventName'],
            'medium',
            'Commands'
        );

        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

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

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        $response = fetchData('hardwares_settings_events', ['property_id'=>$_POST['property_id']]);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get the events"]);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['get_hardwares_settings_events'])) {
        $response = fetchData('hardwares_settings_events', ['eventOf' => $_POST['settingId']]);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get schedules"]);
        $limitedResponse = array_slice(array_reverse($response),  0,  10);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $limitedResponse
        ]);
    }
    
    if (isset($_POST['get_signal_wire_credentials'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        $response = fetchData('signalwire_settings', ['is_property' => 1,"user_id"=>$_POST['property_id']]);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get signal wire credentials"]);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }
   
    if (isset($_POST['get_signal_wire_numbers'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $response = fetchData('my_numbers', ['signalwire_id' => $_POST['signalWireId']]);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get signal wire numbers"]);
        $limitedResponse = array_slice(array_reverse($response),  0,  10);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $limitedResponse
        ]);
    }

    if (isset($_POST['getHardwareSettingByDoorId'])) {
        $sql = "
            SELECT 
                hardwares_settings.id, 
                hardwares_settings.device_id, 
                hardwares_settings.section, 
                hardwares_settings.assigned_door, 
                hardwares_settings.inputs, 
                hardwares_settings.output, 
                hardwares_settings.function, 
                hardwares_settings.status, 
                hardwares_settings.timer, 
                hardwares_settings.ipAddress, 
                hardwares_settings.ipPort, 
                hardwares_settings.completeUrl, 
                hardwares_settings.created_at, 
                hardwares_settings.updated_at,
                gate_doors.door_name, 
                gate_doors.door_image, 
                gate_doors.id AS gate_door_id,
                calendar_added_events.title,
                calendar_added_events.start,
                calendar_added_events.end,
                calendar_added_events.backgroundColor,
                calendar_added_events.borderColor,
                calendar_added_events.allDay,
                calendar_added_events.created_at AS calendar_event_created_at,
                calendar_added_events.id AS calendarId
            FROM 
                hardwares_settings 
            JOIN 
                gate_doors ON hardwares_settings.assigned_door = gate_doors.id 
            LEFT JOIN 
                calendar_added_events ON hardwares_settings.timer = calendar_added_events.id
            WHERE 
                hardwares_settings.created_by = :id
                AND hardwares_settings.assigned_door = :eventOf

        ";
        // $response = fetchDataWithJoins($sql,  [':id' => $_SESSION['userid']]);
        $response = fetchDataWithJoins($sql,  [
            ':id' => $_SESSION['userid'],
            ':eventOf' => $_POST['doorId'] // Add new condition here
        ]);



        // $response = fetchData( 'hardwares_settings', ['assigned_door' => $_POST['doorId']]);

        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get schedules"]);
        $limitedResponse = array_slice(array_reverse($response), 0,  10);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $limitedResponse
        ]);
    }
    if (isset($_POST['get_streaming_url_request'])) {
        $response=fetchDataSingle("stream_url");
        if(!empty($response["stream_url"])){
            sendJsonResponse(200, [
                "success" => true,
                "data" => $response["stream_url"]
            ]);
            exit;
        }else {
            sendJsonResponse(200, [
                "success" => true,
                "data" => []
            ]);
        }
    }
    if (isset($_POST['updateSMSIOTableWithStatusRequest'])) {
        if (empty($_POST['command_center_update']) && !currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $keys = ['status','status_check_date'];
        $data = array_intersect_key($_POST, array_flip($keys));
        
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $response = updateTable('hardwares_settings',  $data,  $where,  $params);
        if ($response == false) sendJsonResponse(500,  ["error" => "Could not add hardware settings"]);
        createAuditLog(
            $_SESSION["userid"] ?? null,
            "Status Check",
            "hardwares_settings_events",
            $_POST['id'],
            $_SESSION["email"] ?? null,
            $_POST['property_id'],
            null,
            null,
            "Status Checked by the ". $_SESSION['email'] ?? null,
            'highest',
            'Status Check'
        );
        sendJsonResponse(200,  [
            "success" => true,
            "data" => "Its edited Now "
        ]);
        exit;
    }
    

    // ===============>>>>>>> hardware automation request <<<<<<<===================
    if (isset($_POST['get_hardware_device_details'])) {
        if (empty($_POST['device_id'])){
            sendJsonResponse(500, ["error" => ""]);
            exit;
        }
        
        $doors_query = "
            SELECT 
                hs.*,
                cae.title AS timer_title,
                cae.start AS timer_start,
                cae.end AS timer_end,
                cae.backgroundColor AS timer_backgroundColor,
                cae.borderColor AS timer_borderColor,
                cae.allDay AS timer_allDay,
                cae.created_at AS timer_created_at,
                cae.id AS timer_id
            FROM hardwares_settings hs
            LEFT JOIN calendar_added_events cae ON hs.timer = cae.id
            WHERE hs.id = :device_id
        ";
    
        $device = fetchDataWithJoins($doors_query, ['device_id' => $_POST['device_id']]);

        if ($device == false) sendJsonResponse(500,  ["error" => "Could not add hardware settings"]);
        if(!empty($device) && is_array($device)){
            $device = $device[0];
        }
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $device
        ]);
        exit;
    }
    
    if (isset($_POST['get_inputs_automation_request'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        if(empty($_POST['property_id'])){
            sendJsonResponse(500, ["error" => "Property id is missing"]);
            exit;
        }

        $query = "
            SELECT 
                ha.id AS automation_id,
                ha.input,
                ha.input_status,
                ha.automation_rules_text,
                ha.device_id AS input_device_id,
                ha.output,
                ha.triggered_by,
                ha.user_schedule,
                ha.created_at,
                hs.id AS hardware_id,
                hs.*,
                gd.id AS door_id, 
                gd.door_name
            FROM hardware_automations ha
            JOIN hardwares_settings hs 
                ON ha.device_id = hs.id
            LEFT JOIN gate_doors gd 
                ON hs.assigned_door = gd.id
            WHERE ha.property_id = :property_id
        ";
        
        $hardware_automations = fetchDataWithJoins($query, ['property_id' => $_POST['property_id']]);
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $hardware_automations
        ]);
        exit;
    }
    
    if (isset($_POST['add_automation_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        $automation_rules = json_decode($_POST['automation_rules'], true);

        foreach($automation_rules as $rule){

            $device_details = fetchDataSingle('hardware_automations', ['device_id' => $rule['device_id'],'input'=>$rule['input']]);
            if(!empty($device_details)){

                $keys = ['input', 'input_status', 'device_id', 'output', 'triggered_by', 'user_schedule', 'property_id', 'automation_rules_text', 'created_by_email'];
                $data = array_intersect_key($rule, array_flip($keys));
                $where = 'id = :id';
                $params = ['id' => $device_details['id']];
                $response = updateTable('hardware_automations',  $data,  $where,  $params);
                if ($response == false) sendJsonResponse(500,  ["error" => "Could not update hardware automation"]);
                continue;
            }

            $rule['created_by_email'] = $_SESSION['email'] ?? null;
            $keys = ['input', 'input_status', 'device_id', 'output', 'triggered_by', 'user_schedule', 'property_id', 'automation_rules_text', 'created_by_email'];
            $data = array_intersect_key($rule, array_flip($keys));
            $response = insertData('hardware_automations', $data);
            if ($response == false) sendJsonResponse(500,  ["error" => "Could not add hardware automation"]);

        }

        createAuditLog(
            $_SESSION["userid"] ?? null,
            "Add Automation",
            "hardware_automations",
            $response['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            null,
            json_encode($data),
            "Automation added",
            'highest',
            'Automation'
        );

        sendJsonResponse(200,  [
            "success" => true,
            "data" => $_POST,
            "automation_rules" => $automation_rules,
            "response" => $response
        ]);
        exit;
    }
    
    if (isset($_POST['update_automation_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        $device_details = fetchDataSingle('hardware_automations', ['id' => $_POST['id']]);
        if(!empty($device_details)){

            $keys = ['input', 'input_status', 'device_id', 'output', 'triggered_by', 'user_schedule', 'property_id', 'automation_rules_text', 'created_by_email'];
            $data = array_intersect_key($_POST, array_flip($keys));
            $where = 'id = :id';
            $params = ['id' => $_POST['id']];
            $response = updateTable('hardware_automations',  $data,  $where,  $params);
            if ($response == false) sendJsonResponse(500,  ["error" => "Could not update hardware automation"]);
        }

        createAuditLog(
            $_SESSION["userid"] ?? null,
            "Update Automation",
            "hardware_automations",
            $response['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            null,
            json_encode($data),
            "Automation updated",
            'highest',
            'Automation'
        );

        sendJsonResponse(200,  [
            "success" => true,
            "data" => $_POST,
            "response" => $response
        ]);
        exit;
    }
    
    if (isset($_POST['delete_automation_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')){
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }

        if(empty($_POST['automation_id'])){
            sendJsonResponse(500, ["error" => "Automation id is missing"]);
            exit;
        }

        $response = deleteData('hardware_automations', 'id', $_POST['automation_id']);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not delete hardware automation",'data'=>$response]);

        createAuditLog(
            $_SESSION["userid"] ?? null,
            "Delete Automation",
            "hardware_automations",
            $response['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            null,
            null,
            "Automation deleted",
            'highest',
            'Automation'
        );

        sendJsonResponse(200,  [
            "success" => true,

        ]);
        exit;
    }
    
    if (isset($_POST['get_hardware_automations_by_id_request'])) {
    
        if(empty($_POST['device_id'])){
            sendJsonResponse(500, ["error" => "Device id is missing"]);
            exit;
        }

        $response = fetchData('hardware_automations', ['device_id' => $_POST['device_id']]);
        if ($response === false) sendJsonResponse(500,  ["error" => "Could not get hardware automation",'data'=>$response]);

        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
} catch (\Throwable $th) {
    sendJsonResponse(500,  ["error" => "Server error: " . $th->getMessage()]);
    createAuditLog(
        $_SESSION["userid"] ?? null,
        $_POST['getHardwareSettingByDoorId'] ?? $_POST['get_hardwares_settings_events'] ?? $_POST['getAllHardwareSettingsDataRequest'] ?? $_POST['getScheduleRequest'] ?? $_POST['deleteHardwareSettingsDataRequest']??$_POST['getHardwareSettingsDataRequest']??$_POST['EditHardwareSettingsRequest']??$_POST['addHardwareSettingsRequest']??$_POST['checkHardwareStatusRequest']??$_POST['editHardwareRequest']??$_POST['getHardwareById']?? $_POST['deleteHardwareDevice']??$_POST['addHardwareRequest']?? null,
        null,
        null,
        $_SESSION["email"] ?? null,
        $_POST['property_id'],
        null,
        null,
        $th->getMessage(),
        'highest',
        'Error'
    );
}


/**
 * Function to validate the payload against required fields and types
 */
function validatePayload($payload) {
    $tableStructure = [
        'property_id' => ['required' => true, 'type' => 'int'],
        'sms_io_duration' => ['required' => false, 'type' => 'int'],
        'invisible_intercom_control_number' => ['required' => false, 'type' => 'string'],
        'sms_io_number' => ['required' => false, 'type' => 'string'],
        'complete_url' => ['required' => false, 'type' => 'string'],
        'user_name' => ['required' => false, 'type' => 'string'],
        'password' => ['required' => false, 'type' => 'string'],
        'hardware_is_active' => ['required' => false, 'type' => 'string'],
        'model' => ['required' => true, 'type' => 'string'],
        'device_type' => ['required' => true, 'type' => 'string'],
        'image_path' => ['required' => false, 'type' => 'string'],
        'ip_address' => ['required' => false, 'type' => 'string'],
        'http_port' => ['required' => false, 'type' => 'int'],
        'created_by' => ['required' => true, 'type' => 'int'],
    ];

    $errors = [];

    foreach ($tableStructure as $field => $rules) {
        $value = $payload[$field] ?? null;
        if ($rules['required'] && ($value === null || $value === '')) {
            $errors[] = "Field '{$field}' is required.";
            continue;
        }

        // Skip validation if the field is not required and is null
        if ($value === null) {
            continue;
        }
        // Validate the data type
        switch ($rules['type']) {
            case 'int':
                if (!is_numeric($value)) {
                    $errors[] = "Field '{$field}' must be an integer.";
                } else {
                    // Attempt to convert to an integer
                    $convertedValue = (int)$value;
                    if ($convertedValue != $value) {
                        $errors[] = "Field '{$field}' must be a valid integer.";
                    }
                }
                break;
            case 'string':
                if (!is_string($value)) {
                    $errors[] = "Field '{$field}' must be a string.";
                }
                break;
            default:
                $errors[] = "Field '{$field}' has an unknown data type.";
        }
    }

    return !empty($errors) ? ['success' => false, 'errors' => $errors] : ['success' => true];
}
