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

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

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

try {

    $property_id = $_SESSION['property'];

    if (isset($_POST['get_command_center_data_request'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;  
        if (!isset($_POST['property_id'])) {
            sendJsonResponse(400, ["error" => 'please set the property id from header menu']);
            exit;
        }

        if (isset($_SESSION['role']) && ($_SESSION['role']  == 6 || $_SESSION['role']  == 5 || $_SESSION['role']  == 3 || $_SESSION['role']  == 1 || $_SESSION['role']  == 2)) {

            $property_permission = fetchData('property_permissions', ['property_id' => $_POST['property_id']]);
            $sql = "
                SELECT 
                    hardwares_settings.id AS hardware_setting_id,
                    hardwares_settings.device_id,
                    hardwares_settings.section,
                    hardwares_settings.assigned_door,
                    hardwares_settings.sms_duration,
                    hardwares_settings.output,
                    hardwares_settings.property_id,
                    hardwares_settings.inputs,
                    hardwares_settings.function,
                    hardwares_settings.status,
                    hardwares_settings.timer,
                    hardwares_settings.ipAddress,
                    hardwares_settings.ipPort,
                    hardwares_settings.completeUrl,
                    hardwares_settings.created_by,
                    hardwares_settings.created_at AS hardware_created_at,
                    hardwares_settings.updated_at AS hardware_updated_at,
                    
                    gate_doors.id AS gate_door_id,
                    gate_doors.door_name,
                    gate_doors.door_image,
                    gate_doors.property_id,
                    gate_doors.complete_url_assigned,
                    gate_doors.type,
                    gate_doors.door_key,
                    gate_doors.CreatedBy AS door_created_by,
                    gate_doors.camera_id,
                    
                    live_camera_streaming_data.id AS camera_table_id,
                    live_camera_streaming_data.streamingUrl,
                    live_camera_streaming_data.cameraName,
                    live_camera_streaming_data.cameraModel,
                    live_camera_streaming_data.userName,
                    live_camera_streaming_data.password,
                    live_camera_streaming_data.IP,
                    live_camera_streaming_data.liveImageURL,
                    live_camera_streaming_data.liveImagePort,
                    live_camera_streaming_data.RTSP_PORT,
                    live_camera_streaming_data.user AS camera_user,
                    live_camera_streaming_data.ftp_host,

                    calendar_added_events.id AS calendar_event_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_created_at,

                    hardware_devices.id AS hardware_device_id,
                    hardware_devices.model AS device_model,
                    hardware_devices.device_type,
                    hardware_devices.ip_address AS device_ip_address,
                    hardware_devices.password AS device_password,
                    hardware_devices.user_name AS device_user_name,
                    hardware_devices.sms_io_duration AS device_sms_io_duration,
                    hardware_devices.http_port AS device_http_port,
                    hardware_devices.invisible_intercom_control_number AS device_invisible_intercom_control_number,
                    hardware_devices.sms_io_number AS device_sms_io_number,
                    hardware_devices.complete_url AS device_complete_url

                FROM 
                    hardwares_settings
                LEFT JOIN 
                    gate_doors ON hardwares_settings.assigned_door = gate_doors.id
                LEFT JOIN 
                    live_camera_streaming_data ON gate_doors.camera_id = live_camera_streaming_data.id
                LEFT JOIN 
                    calendar_added_events ON hardwares_settings.timer = calendar_added_events.id
                LEFT JOIN 
                    hardware_devices ON hardwares_settings.device_id = hardware_devices.id
                WHERE 
                    hardwares_settings.property_id = :property_id;
            ";
            $hardwaresData = fetchDataWithJoins($sql, [':property_id' => $_POST['property_id']]);
            sendJsonResponse(200, [
                "success" => true,
                "data" => $hardwaresData,
                "actions" => $property_permission,
                "all_permissions" => true,
                "onlyOpenCommand" => false
            ]);
        } else {
            $all_doors = fetchData('hardwares_settings', ['property_id' => $_POST['property_id']]);
            $user_permissions = fetchData('property_permissions', ['property_id' => $_POST['property_id'], 'user_email' => $_SESSION['email']]);
            $user_default_permissions = fetchDataSingle('property_default_permissions', ['property_id' => $_POST['property_id']]);

            $data = [];
            $user_permissions_data_for_testing = [];
            foreach ($all_doors as $key => $value) {
                $user_permission = fetchDataSingle('property_permissions', ['property_id' => $_POST['property_id'], 'door_id' => $value['id'], 'user_email' => $_SESSION['email']]);
                $user_permission_data=[];
                if(!empty($user_permission)){
                    $user_permission_data=$user_permission;
                }else if(!empty($user_default_permissions) && check_global_permissions_exists($user_default_permissions)){
                    $user_permission_data = [
                        "id" => $user_default_permissions['id'] ?? null,
                        "property_id" => $user_default_permissions['property_id'] ?? null,
                        'user_id' => null,
                        'user_email' => $_SESSION['email'] ?? null,
                        'actions_to_perform' => $user_default_permissions['actions_to_perform'] ?? null,
                        'is_keep_open_to' => $user_default_permissions['is_keep_open_to'] ?? null,
                        'is_individual' => 0,
                        'permission_created_at' => $user_default_permissions['created_at'] ?? null,
                        'permission_updated_at' => $user_default_permissions['updated_at'] ?? null,
                        'global_permission' => true,
                    ];
                }else {
                    // Skip this door if no permissions are found
                    continue;
                }

                $user_permissions_data_for_testing[] = $user_permission_data;

                $assigned_gate_door = fetchDataWithId('gate_doors', $value['assigned_door']);
                $camera_data = [];
                if(!empty($assigned_gate_door)){
                    $assigned_camera = fetchDataWithId('live_camera_streaming_data', $assigned_gate_door['camera_id']);
                    $camera_data = [
                        'camera_table_id' => $assigned_camera['id'] ?? null,
                        'streamingUrl' => $assigned_camera['streamingUrl'] ?? null,
                        'cameraName' => $assigned_camera['cameraName'] ?? null,
                        'cameraModel' => $assigned_camera['cameraModel'] ?? null,
                        'userName' => $assigned_camera['userName'] ?? null,
                        'password' => $assigned_camera['password'] ?? null,
                        'IP' => $assigned_camera['IP'] ?? null,
                        'liveImageURL' => $assigned_camera['liveImageURL'] ?? null,
                        'liveImagePort' => $assigned_camera['liveImagePort'] ?? null,
                        'RTSP_PORT' => $assigned_camera['RTSP_PORT'] ?? null,
                        'camera_user' => $assigned_camera['user'] ?? null,
                    ];
                }

                $calendar_data = [];
                if(!empty($value['timer'])){
                    $calendar_data = fetchDataWithId('calendar_added_events', $value['timer']);
                    $calendar_data = [
                        'calendar_event_id' => $calendar_data['id'] ?? null,
                        'title' => $calendar_data['title'] ?? null,
                        'start' => $calendar_data['start'] ?? null,
                        'end' => $calendar_data['end'] ?? null,
                        'backgroundColor' => $calendar_data['backgroundColor'] ?? null,
                        'borderColor' => $calendar_data['borderColor'] ?? null,
                        'allDay' => $calendar_data['allDay'] ?? null,
                        'calendar_created_at' => $calendar_data['created_at'] ?? null,
                    ];
                }

                $hardware_device_data = [
                    'hardware_device_id' => $hardware_device['id'] ?? null,
                    'device_model' => $hardware_device['model'] ?? null,
                    'device_type' => $hardware_device['device_type'] ?? null,
                    'device_password' => $hardware_device['password'] ?? null,
                    'device_invisible_intercom_control_number' => $hardware_device['invisible_intercom_control_number'] ?? null,
                ];

                $hardware_device = fetchDataWithId('hardware_devices', $value['device_id']);

                $data[] = [
                    'hardware_setting_id' => $value['id'] ?? null,
                    'property_id' => $value['property_id'] ?? null,
                    'assigned_door' => $value['assigned_door'] ?? null,
                    'sms_duration' => $value['sms_duration'] ?? null,
                    'device_id' => $value['device_id'] ?? null,
                    'output' => $value['output'] ?? null,
                    'inputs' => $value['inputs'] ?? null,
                    'function' => $value['function'] ?? null,
                    'status' => $value['status'] ?? null,
                    'timer' => $value['timer'] ?? null,
                    'ipAddress' => $value['ipAddress'] ?? null,
                    'ipPort' => $value['ipPort'] ?? null,
                    'section' => $value['section'] ?? null,
                    'completeUrl' => $value['completeUrl'] ?? null,
                    'hardware_created_by' => $value['created_by'] ?? null,
                    'hardware_created_at' => $value['created_at'] ?? null,
                    'hardware_updated_at' => $value['updated_at'] ?? null,
                    //====================== permission data
                    'permission_id' => $user_permission_data['id'] ?? null,
                    // 'door_id' => $user_permission['door_id'] ?? null,
                    'user_id' => $user_permission_data['user_id'] ?? null,
                    'user_email' => $user_permission_data['user_email'] ?? null,
                    'actions_to_perform' => $user_permission_data['actions_to_perform'] ?? null,
                    'is_keep_open_to' => $user_permission_data['is_keep_open_to'] ?? null,
                    'created_by' => $user_permission_data['created_by'] ?? null,
                    'is_individual' => $user_permission_data['is_individual'] ?? null,
                    'permission_created_at' => $user_permission_data['created_at'] ?? null,
                    'permission_updated_at' => $user_permission_data['updated_at'] ?? null,
                    //====================== assigned camera data
                    'camera_table_id' => $camera_data['camera_table_id'] ?? null,
                    'door_name' => $assigned_gate_door['door_name'] ?? null,
                    'streamingUrl' => $camera_data['streamingUrl'] ?? null,
                    'cameraName' => $camera_data['cameraName'] ?? null,
                    'cameraModel' => $camera_data['cameraModel'] ?? null,
                    'userName' => $camera_data['userName'] ?? null,
                    'password' => $camera_data['password'] ?? null,
                    'IP' => $camera_data['IP'] ?? null,
                    'liveImageURL' => $camera_data['liveImageURL'] ?? null,
                    'liveImagePort' => $camera_data['liveImagePort'] ?? null,
                    'RTSP_PORT' => $camera_data['RTSP_PORT'] ?? null,
                    'camera_user' => $camera_data['camera_user'] ?? null,
                    //====================== assigned schedule data
                    'calendar_event_id' => $calendar_data['calendar_event_id'] ?? null,
                    'title' => $calendar_data['title'] ?? null,
                    'start' => $calendar_data['start'] ?? null,
                    'end' => $calendar_data['end'] ?? null,
                    'backgroundColor' => $calendar_data['backgroundColor'] ?? null,
                    'borderColor' => $calendar_data['borderColor'] ?? null,
                    'allDay' => $calendar_data['allDay'] ?? null,
                    'calendar_created_at' => $calendar_data['created_at'] ?? null,
                    //====================== assigned hardware device data
                    'hardware_device_id' => $hardware_device['id'] ?? null,
                    'device_model' => $hardware_device['model'] ?? null,
                    'device_type' => $hardware_device['device_type'] ?? null,
                    'device_ip_address' => $hardware_device['ip_address'] ?? null,
                    'device_password' => $hardware_device['password'] ?? null,
                    'device_user_name' => $hardware_device['user_name'] ?? null,
                    'device_sms_io_duration' => $hardware_device['sms_io_duration'] ?? null,
                    'device_http_port' => $hardware_device['http_port'] ?? null,
                    'device_invisible_intercom_control_number' => $hardware_device['invisible_intercom_control_number'] ?? null,
                    'device_sms_io_number' => $hardware_device['sms_io_number'] ?? null,
                    'device_complete_url' => $hardware_device['complete_url'] ?? null
                ];
            }
            
            sendJsonResponse(200, [
                "success" => true,
                "data" => $data, // create data using above loop and data 
                "actions" => null,
                "all_permissions" => false,
                "onlyOpenCommand" => false,
            ]);
            exit;
        }
    }

    if (isset($_POST['image_streaming'])) {
        $imageUrl = $_POST['imageUrl'] ?? '';
    
        $validation = isSafeCommandCenterImageUrl($imageUrl);
        if (!$validation['status']) {
            http_response_code(400);
            echo json_encode(['error' => $validation['message']]);
            exit;
        }
    
        // Proceed with curl request
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $imageUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 0);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        $header_response = curl_exec($ch);
    
        if ($header_response === false) {
            $error = curl_error($ch);
            http_response_code(500);
            echo json_encode(["error" => "Could not fetch image. Error: $error"]);
            exit;
        }
    
        $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        curl_close($ch);
    
        if (strpos($content_type, 'image') === false) {
            http_response_code(400);
            echo json_encode(["error" => "The URL does not point to an image."]);
            exit;
        }
    
        echo json_encode(["image" => base64_encode($header_response)]);
        exit;
    }

    if (isset($_POST['get_all_cameras_of_door_request'])) {
        $query = "
            SELECT 
                door_cameras.id AS door_camera_id,
                door_cameras.door_id,
                door_cameras.camera_id,
                live_camera_streaming_data.id AS camera_table_id,
                live_camera_streaming_data.streamingUrl,
                live_camera_streaming_data.cameraName,
                live_camera_streaming_data.cameraModel,
                live_camera_streaming_data.userName,
                live_camera_streaming_data.password,
                live_camera_streaming_data.IP,
                live_camera_streaming_data.RTSP_PORT,
                live_camera_streaming_data.user,
                live_camera_streaming_data.created_at AS camera_created_at,
                live_camera_streaming_data.updated_at AS camera_updated_at
            FROM 
                door_cameras
            JOIN 
                live_camera_streaming_data 
                ON door_cameras.camera_id = live_camera_streaming_data.id
            WHERE 
                door_cameras.door_id = :door_id
        ";
        $response = fetchDataWithJoins($query, [':door_id' => $_POST['door_id']]);
        if ($response === false) sendJsonResponse(500, ["error" => "cannot any cameras for this door"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['get_device_events_request'])) {
        $response = fetchData('hardwares_settings_events', ['eventOf' => $_POST['event_of']]);
        if ($response === false) sendJsonResponse(500, ["error" => "cannot get device events"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

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

        $response = fetchData('don_not_disturb', ["property_id"=>$_POST['property_id'],"user_email"=>$_SESSION["email"]]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => isset($response[0])?$response[0]:[],
            "is_property_user" => true
        ]);
        exit;
    }

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

        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        $_POST['user_email'] = $_SESSION["email"];

        $response = fetchData('don_not_disturb', ["property_id"=>$_POST['property_id'],"user_email"=>$_POST['user_email']]);
        $new_value = $_POST['isDontDisturb'];
        $old_value = 1;
        if($new_value == 1){
            $old_value = 0;
        }
        if(!empty($response) && !empty($response[0])) {
            $userDisturb=$response[0];
            $userDisturb["isDontDisturb"] = $_POST['isDontDisturb'];
            $where = 'id = :id';
            $params = ['id' => $userDisturb['id']];
            $response = updateTable('don_not_disturb',  $userDisturb,  $where,  $params);
            $new_res = fetchDataSingle('don_not_disturb', ["id" => $userDisturb['id']]);
            update_do_not_disturb($new_res['user_id'], $new_res['property_id'], $_POST['isDontDisturb']);
            createAuditLog(
                $_SESSION["userid"],
                'Update',
                'don_not_disturb',
                $userDisturb['id'],
                $_SESSION["email"],
                $_POST['property_id'] ?? null,
                $old_value,
                $new_value,
                'user don\'t disturb updated',
                'high',
                'User management '
            );
            sendJsonResponse(200, [
                "success" => true,
                "added" => null,
                "updated"=>$response 
            ]);
            
            exit;
        }

        $_POST['user_id'] = $_SESSION["userid"];
        $validationResult = validatePostData($_POST);

        if(!$validationResult["success"]){
            sendJsonResponse(400, ["error" => json_encode($validationResult["errors"])]);
            exit;
        }
        
        $keys = ['property_id','user_id','user_email',"isDontDisturb"]; 
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('don_not_disturb', $data);
        $last_insert_id = getLastInsertId();
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'don_not_disturb',
            $last_insert_id,
            $_SESSION["email"],
            $_POST['property_id'] ?? null,
            $old_value,
            $new_value,
            'user don\'t disturb updated',
            'high',
            'User management '
        );

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

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'multi_prop_users',
            $multipropertyUsers['id'],
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Property user don\'t disturb added',
            'INFO',
            'User management '
        );
        exit;
    }

    if (isset($_POST['EditDoorInSettingsRequest'])) {
        $keys = ['camera_id'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('gate_doors', $data, $where, $params);
        $response = $updateSuccess;
        if ($response === false) sendJsonResponse(500, ["error" => "cannot update door"]);
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'gate_doors',
            $_POST['id']??null,
            $_SESSION["email"]??null,
            $_POST['property_id'],
            null,
            null,
            'Camera updated to door',
            'high',
            'Doors'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['getCommandDays'])) {
        $schedule_periods = fetchData("schedule_periods", ['schedule_id' => $_POST['id']]);
        if (!empty($schedule_periods)) {
            foreach ($schedule_periods as &$period) {
                $period['days'] = fetchData("schedule_period_days", ['period_id' => $period['id'], 'is_active' => 1]);
            }
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => $schedule_periods
        ]);
    }

    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(400, ["error" => "Could not find the nodejs url. please add voip url in super admin settings"]);
            exit;
        }
    }

    if (isset($_POST['addNewAuditLog'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        createAuditLog(
            $_SESSION["userid"],
            $_POST['action'],
            $_POST['table_name'],
            $_POST['id']??null,
            $_SESSION["email"]??null,
            $_POST['property_id']??null,
            null,
            null,
            $_POST['additional_info'],
            $_POST['log_level'],
            $_POST['module_name']
        );
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);
}


function validatePostData($postData) {
    $tableStructure = [
        'property_id' => ['required' => true, 'type' => 'int'],
        'isDontDisturb' => ['required' => false, 'type' => 'boolean'],
        'user_id' => ['required' => true, 'type' => 'int'],
        'user_email' => ['required' => true, 'type' => 'string'],
    ];

    $errors = [];

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

        if ($value === null) {
            continue;
        }

        switch ($rules['type']) {
            case 'int':
                if (!is_numeric($value)) {
                    $errors[] = "Field '{$field}' must be an integer.";
                } else {
                    $convertedValue = (int)$value;
                    if ($convertedValue != $value) {
                        $errors[] = "Field '{$field}' must be a valid integer.";
                    }
                }
                break;

            case 'boolean':
                if (!is_bool($value) && $value !== '0' && $value !== '1') {
                    $errors[] = "Field '{$field}' must be a boolean value (0 or 1).";
                }
                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];
}

function isSafeCommandCenterImageUrl(string $imageUrl): array
{
    if (!filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        return ['status' => false, 'message' => 'Invalid URL format.'];
    }

    $parsedUrl = parse_url($imageUrl);
    $scheme = strtolower($parsedUrl['scheme'] ?? '');
    if (!in_array($scheme, ['http', 'https'])) {
        return ['status' => false, 'message' => 'Only HTTP and HTTPS protocols are allowed.'];
    }

    $host = $parsedUrl['host'] ?? '';
    if (empty($host)) {
        return ['status' => false, 'message' => 'Invalid host in URL.'];
    }

    $ip = gethostbyname($host);
    if (
        filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false ||
        in_array($ip, ['127.0.0.1', '::1'])
    ) {
        return ['status' => false, 'message' => 'Access to private/internal IPs is not allowed.'];
    }

    return ['status' => true];
}

function update_call_flow_disturb($call_flow_id, $disturb_number, $is_disturb){
    $update_data = [
        $disturb_number => $is_disturb,
    ];
    $where = 'id = :id';
    $params = ['id' => $call_flow_id];
    updateTable('my_call_flow', $update_data,  $where,  $params);
}

function update_call_flow_numbers_disturb($mobile_number, $property_id, $is_disturb){
    $first_number_check = fetchDataSingle('my_call_flow', ['first_number' => $mobile_number, 'property_id', $property_id]);
    if(isset($first_number_check['id'])){
        update_call_flow_disturb($first_number_check['id'], 'first_number_disturb', $is_disturb);    
    }
    $second_number_check = fetchDataSingle('my_call_flow', ['second_number' => $mobile_number, 'property_id', $property_id]);
    if(isset($second_number_check['id'])){
        update_call_flow_disturb($second_number_check['id'], 'second_number_disturb', $is_disturb);    
    }
    $third_number_check = fetchDataSingle('my_call_flow', ['third_number' => $mobile_number, 'property_id', $property_id]);
    if(isset($third_number_check['id'])){
        update_call_flow_disturb($third_number_check['id'], 'third_number_disturb', $is_disturb);
    }
    
}

function update_do_not_disturb($user_id, $property_id, $is_disturb){
    $user_data = fetchDataSingle('property_users_data', ['property_user' => $user_id, 'property_id' => $property_id]);
    if(isset($user_data['id']) && !empty($user_data['id'])){
        if(!empty($user_data['phone_number'])){
            update_call_flow_numbers_disturb($user_data['phone_number'], $property_id, $is_disturb);
        }
        if(!empty($user_data['home_number'])){
            update_call_flow_numbers_disturb($user_data['home_number'], $property_id, $is_disturb);
        }
    }
    else{

    }
}

function check_global_permissions_exists($permissions) {
    if (empty($permissions) || empty($permissions['actions_to_perform'])) {
        return false;
    }

    // Decode the JSON string to an associative array
    $actions = json_decode($permissions['actions_to_perform'], true);

    // Check if decoding failed or result is not an array
    if (!is_array($actions)) {
        return false;
    }

    // If all values are false, return false
    if (array_filter($actions) === [] && $permissions['is_keep_open_to'] == 0) {
        return false;
    }

    return true;
}
