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

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

try {
    $user_id = $_POST['user_id'] ?? null;
    $property_id = $_POST['property_id'] ?? null;
    $email = $_POST['user_email'] ?? null;

    if($_POST["record_id"]){
        $harware_setting = fetchDataSingle('hardwares_settings', ['id' => $_POST["record_id"]]);
        $file_name = "";
        $snap_image = "";
        if(isset($harware_setting['id']) && !empty($harware_setting['id'])){
            $door_data = fetchDataSingle('gate_doors', ['id' => $harware_setting['assigned_door']]);
            if(isset($door_data['id']) && !empty($door_data['id'])){
                $save_snap = storeSnapshotImage($door_data['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'];
                }
            }
        }
        
        $utcTime = new DateTime('now', new DateTimeZone('UTC'));
        $eventData = [
            'eventName' => $_POST["action"],
            'eventType' => $_POST["action"],
            'eventDetail' => $_POST["additional_info"],
            'timestamp' => $utcTime->format('Y-m-d\TH:i:s\Z'),
            'eventOf' => $_POST["record_id"],
            'URL' => $_POST['completeUrl'] ?? null,
            'file_name' => $file_name, 
            'camera_snap' => $snap_image,
            'created_by' => $_POST["user_id"] ?? null,
            'property_id' => $_POST['property_id'] ?? null,
        ];
        $status_saved = insertData('hardwares_settings_events',  $eventData);
    }

    createAuditLog(
        $_POST["user_id"],
        $_POST["action"],
        $_POST["table_name"],
        $_POST["record_id"] ?? null,
        $email ?? null,
        $property_id ?? null,
        null,
        null,
        $_POST['additional_info'],
        'INFO',
        'Schedule'
    );

    sendJsonResponse(200, [
        "success" => true,
        "message" => "Schedule Action Event Added"
    ]);
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);
}
