<?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['save_property_settings'])) {

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

        // =$_POST["is_keep_open_to"]
        $_POST['created_by'] = $_SESSION['userid'];
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        if ($_POST['is_individual'] == 0) {
            // Upsert the global default
            $default = fetchDataSingle('property_default_permissions', ['property_id' => $_POST['property_id']]);
            $data = [
                'property_id' => htmlspecialchars($_POST['property_id'], ENT_QUOTES, 'UTF-8'),
                'actions_to_perform' => $_POST['actions_to_perform'],
                'is_keep_open_to' => htmlspecialchars($_POST['is_keep_open_to'], ENT_QUOTES, 'UTF-8'),
                'created_by' => htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8')
            ];

            if ($default) {
                $stmt = $pdo->prepare("
                    UPDATE property_default_permissions 
                    SET actions_to_perform = :actions_to_perform, is_keep_open_to = :is_keep_open_to, created_by = :created_by
                    WHERE property_id = :property_id
                ");

                $stmt->execute($data);
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO property_default_permissions 
                    (property_id, actions_to_perform, is_keep_open_to, created_by) 
                    VALUES (:property_id, :actions_to_perform, :is_keep_open_to, :created_by)
                ");

                $stmt->execute($data);
            }

            createAuditLog(
                $_SESSION["userid"],
                'Set Default',
                'property_default_permissions',
                $default['id'] ?? null,
                $_SESSION["email"] ?? null,
                $_POST['property_id'],
                null,
                null,
                'Default permissions set for property',
                'medium',
                'Permissions'
            );

            sendJsonResponse(200, [
                "success" => true,
                "data" => "Default permissions saved"
            ]);
            exit;
        }

        if (isset($_POST['user_id']) && isset($_POST['door_id'])) {
            $alreadyAdded = fetchData('property_permissions', [
                'user_id' => $_POST['user_id'],
                'door_id' => $_POST['door_id'],
                'user_email' => $_POST['user_email'],
                'user_type' => $_POST['user_type'] ?? 'property_user' // fallback for legacy
            ]);
            if (isset($alreadyAdded[0]['id'])) {
                $keys = ['property_id', 'door_id', 'user_type', 'user_id', 'is_keep_open_to', 'actions_to_perform', 'created_by', 'is_individual','user_email'];
                $data = array_intersect_key($_POST, array_flip($keys));
                $where = 'id = :id';
                $params = ['id' => $alreadyAdded[0]['id']];
                $old_permission = fetchDataSingle('property_permissions', ['id' => $alreadyAdded[0]['id']]);
                updateTable('property_permissions', $data, $where, $params);
                $new_updated_permission = fetchDataSingle('property_permissions', ['id' => $alreadyAdded[0]['id']]);
                createAuditLog(
                    $_SESSION["userid"],
                    'Update',
                    'property_permissions',
                    $_POST['id'] ?? null,
                    $_SESSION["email"] ?? null,
                    $_POST['property_id'] ?? null,
                    json_encode($old_permission),
                    json_encode($new_updated_permission),
                    'Property permissions added for user with the id of ' . $alreadyAdded[0]['id'],
                    'high',
                    'Permissions'
                );
                sendJsonResponse(200, [
                    "success" => true,
                    "data" => "Updated successfully"
                ]);
                exit;
            }
        }

        $keys = ['property_id', 'door_id', 'user_type', 'user_id', 'is_keep_open_to', 'actions_to_perform', 'created_by', 'is_individual','user_email'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('property_permissions', $data);
        $last_id = getLastInsertId();
        $inserted_reason_data = fetchDataSingle('property_permissions', ['id' => $last_id]);
        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data ']);
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'property_permissions',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            null,
            json_encode($inserted_reason_data),
            'Property permissions added for user with the id of ' . $last_id,
            'high',
            'Permissions'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => "New data inserted"
        ]);
    }

    if (isset($_POST['edit_property_settings'])) {
        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;

        $keys = ['property_id', 'door_id', 'is_keep_open_to', 'user_id', 'actions_to_perform', 'created_by', 'is_individual','user_email'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $old_permission_values = fetchDataSingle('property_permissions', ['id' => $_POST['id']]);
        $updateSuccess = updateTable('property_permissions', $data, $where, $params);
        $updated_permission_values = fetchDataSingle('property_permissions', ['id' => $_POST['id']]);
        $response = $updateSuccess;
        if ($response == false) sendJsonResponse(500, ["error" => "Could not add data " . $response]);
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'property_permissions',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'],
            json_encode($old_permission_values),
            json_encode($updated_permission_values),
            'Permissions updated for a user with the id of ' . $_POST['id'],
            'high',
            'Permissions'
        );
        sendJsonResponse(200,  [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['delete_property_setting'])) {
        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;

        $perm = fetchDataSingle('property_permissions', ['id' => $_POST['id']]);
        if (!$perm) {
            sendJsonResponse(404, ["error" => "Permission not found"]);
            exit;
        }

        $response = deleteData('property_permissions', 'id', $_POST['id']);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not delete the property setting"]);
            exit;
        }

        if ($perm['is_individual'] == 1) {
            $default = fetchDataSingle('property_default_permissions', ['property_id' => $perm['property_id']]);

            if ($default) {
                $data = [
                    'property_id' => htmlspecialchars($perm['property_id'], ENT_QUOTES, 'UTF-8'),
                    'user_id' => htmlspecialchars($perm['user_id'], ENT_QUOTES, 'UTF-8'),
                    'door_id' => htmlspecialchars($perm['door_id'], ENT_QUOTES, 'UTF-8'),
                    'actions_to_perform' => $default['actions_to_perform'],
                    'is_keep_open_to' => htmlspecialchars($default['is_keep_open_to'], ENT_QUOTES, 'UTF-8'),
                    'is_individual' => htmlspecialchars(0, ENT_QUOTES, 'UTF-8'),
                    'created_by' => htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8')
                ];
                $stmt = $pdo->prepare("
                    INSERT INTO property_permissions 
                    (property_id, door_id, user_id, actions_to_perform, is_keep_open_to, is_individual, created_by) 
                    VALUES (:property_id, :user_id, :door_id, :actions_to_perform, :is_keep_open_to, :is_individual, :created_by)
                ");

                $stmt->execute($data);
            }
        }

        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'property_permissions',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'],
            json_encode($perm),
            null,
            'Permissions Deleted for a user with the id of ' . $_POST['id'],
            'high',
            'Permissions'
        );        
        
        sendJsonResponse(200, [
            "success" => true,
            "data" => "Permission deleted and fallback (if needed) assigned"
        ]);
    }

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

        $sql = "
            -- Permissions for single-property users (property_user)
            SELECT 
                pp.id AS permission_id,
                pp.property_id,
                pp.door_id,
                pp.user_id,
                pp.actions_to_perform,
                pp.is_keep_open_to,
                pp.created_by,
                pp.is_individual,
                pp.created_at AS permission_created_at,
                pp.updated_at AS permission_updated_at,
    
                p.id AS property_id,
                p.name AS property_name,
                p.address AS property_address,
                p.city AS property_city,
                p.state AS property_state,
                p.zipcode AS property_zipcode,
                p.contact AS property_contact,
                p.contact_phone_number AS property_contact_phone,
    
                gd.door_name AS door_name,
    
                pu.id AS user_id_in_users_table,
                pu.email AS user_email,
                pu.role AS user_role,
                pu.role_type AS user_role_type,
                pu.status AS user_status,
    
                pud.firstname AS firstname,
                pud.lastname AS lastname,
    
                'property_user' AS user_source,
    
                hs.id AS hardware_id,
                hs.device_id AS hardware_device_id, 
                hd.id AS device_id,
                hd.model AS device_model,
                hd.device_type AS device_type
    
            FROM property_permissions pp
            JOIN properties p ON pp.property_id = p.id
            LEFT JOIN hardwares_settings hs ON pp.door_id = hs.id
            LEFT JOIN gate_doors gd ON hs.assigned_door = gd.id
            LEFT JOIN property_users pu ON pp.user_id = pu.id
            LEFT JOIN property_users_data pud ON pp.user_id = pud.property_user
            LEFT JOIN hardware_devices hd ON hs.device_id = hd.id
            WHERE pp.property_id = :property_id
              AND pp.user_type = 'property_user'
    
            UNION ALL
    
            -- Permissions for multi-property users (multi_prop)
            SELECT 
                pp.id AS permission_id,
                pp.property_id,
                pp.door_id,
                pp.user_id,
                pp.actions_to_perform,
                pp.is_keep_open_to,
                pp.created_by,
                pp.is_individual,
                pp.created_at AS permission_created_at,
                pp.updated_at AS permission_updated_at,
    
                p.id AS property_id,
                p.name AS property_name,
                p.address AS property_address,
                p.city AS property_city,
                p.state AS property_state,
                p.zipcode AS property_zipcode,
                p.contact AS property_contact,
                p.contact_phone_number AS property_contact_phone,
    
                gd.door_name AS door_name,
    
                pu.id AS user_id_in_users_table,
                pu.email AS user_email,
    
                mp.role AS user_role,
                mp.role_type AS user_role_type,
                mp.status AS user_status,
    
                mp.firstname AS firstname,
                mp.lastname AS lastname,
    
                'multi_prop' AS user_source,
    
                hs.id AS hardware_id,
                hs.device_id AS hardware_device_id, 
                hd.id AS device_id,
                hd.model AS device_model,
                hd.device_type AS device_type
    
            FROM property_permissions pp
            JOIN properties p ON pp.property_id = p.id
            LEFT JOIN hardwares_settings hs ON pp.door_id = hs.id
            LEFT JOIN gate_doors gd ON hs.assigned_door = gd.id
            LEFT JOIN multi_prop_users mp ON pp.user_id = mp.id
            LEFT JOIN property_users pu ON mp.user_assoc = pu.id  -- map back to main user for email
            LEFT JOIN hardware_devices hd ON hs.device_id = hd.id
            WHERE pp.property_id = :property_id
              AND pp.user_type = 'multi_prop';
        ";

        $response = fetchDataWithJoins($sql, [':property_id' => $_POST['property_id']]);
        $default = fetchDataSingle('property_default_permissions', ['property_id' => $_POST['property_id']]);

        if ($response === false) {
            sendJsonResponse(500, ["error" => 'Could not fetch data']);
        } else {
            sendJsonResponse(200, [
                "success" => true,
                "data" => $response,
                "default" => $default
            ]);
        }
    }

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

        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $sql = "
            SELECT 
                hardwares_settings.id AS hardware_setting_id,
                hardwares_settings.device_id,
                hardwares_settings.section,
                hardwares_settings.assigned_door,
                hardwares_settings.output,
                hardwares_settings.inputs,
                hardwares_settings.function,
                hardwares_settings.status,
                hardwares_settings.timer,
                hardwares_settings.ipAddress,
                hardwares_settings.ipPort,
                hardwares_settings.property_id,
                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 AS 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,

                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.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;

        ";

        // $all_doors = fetchDataWithJoins($sql);
        $response = fetchDataWithJoins($sql, [':property_id' => $_POST['property_id']]);

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

    if (isset($_POST['set_active_property_tab'])) {
        $_SESSION['active_property_tab'] = $_POST['active_tab'] ?? $_SESSION['active_property_tab'] = "doors";
        sendJsonResponse(200, [
            "success" => true,
            "data" => "added"
        ]);
        exit;
    }

    if (isset($_POST['get_active_property_tab'])) {
        sendJsonResponse(200, [
            "success" => true,
            "active_tab" => $_SESSION['active_property_tab'] ?? null
        ]);
        exit;
    }

    if (isset($_POST['get_property_users_request'])) {
        $userRole = fetchDataSingle("roles", ['name' => "user"]);
        if (empty($userRole['id'])) {
            sendJsonResponse(500, ["error" => 'Could not find the role "user" in the DB. Internal error']);
            exit;
        }
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        $propertyId = $_POST['property_id'];

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

    if (isset($_POST['get_cameras_for_permissions'])) {
        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("live_camera_streaming_data", ["property_id" => $_POST['property_id']]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response ?? null
        ]);
        exit;
    }

    if (isset($_POST['add_permissions_for_cameras'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        if ($_POST["isIndividual"] == "true") {
            $already_camera_permission = fetchDataSingle("camera_permissions", ["property_user_email" => $_POST["property_user_email"],"camera_id"=>$_POST["camera_id"] ,"property_id" => $_POST["property_id"]]);
            if (empty($already_camera_permission)) {
                $keys = ['property_id', 'property_user_id', 'property_user_name', 'have_view_permission', 'camera_id', 'property_user_email'];
                $data = array_intersect_key($_POST, array_flip($keys));
                $response = insertData("camera_permissions", $data);
                $camera_permission_id = getLastInsertId();
                $permission_data = fetchDataSingle("camera_permissions", ["id" => $camera_permission_id]);
                createAuditLog(
                    $_SESSION["userid"] ?? null,
                    'Create',
                    'camera_permissions',
                    $camera_permission_id,
                    $_SESSION["email"] ?? null,
                    $_POST['property_id'] ?? null,
                    null,
                    json_encode($permission_data),
                    'Camera permissions added',
                    'high',
                    'Permissions'
                );
            } else {
                $response = "already have this permission";
            }
        } else {
            $default = fetchDataSingle("camera_permissions_global", ["property_id" => $_POST['property_id']]);
            $keys = ['camera_ids', 'property_id'];
            $data = array_intersect_key($_POST, array_flip($keys));

            if (empty($default)) {
                $response = insertData("camera_permissions_global", $data);
                $camera_ids = json_decode($data["camera_ids"]);
                $users = getPropertyUsers($_POST['property_id']);
                deleteData("camera_permissions", "property_id", $_POST['property_id']);
                foreach ($users as $user) {
                    foreach ($camera_ids as $camera_id) {
                        $payload_data = [
                            "property_id" => $_POST['property_id'],
                            "property_user_id" => $user['id'],
                            "property_user_email" => $user['email'] ?? "",
                            "property_user_name" => $user['firstname'] . " " . $user['lastname'],
                            "have_view_permission" => 1,
                            "camera_id" => $camera_id,
                        ];
                        insertData("camera_permissions", $payload_data);
                    }
                }
            } else {
                $camera_ids = json_decode($data["camera_ids"]);
                $users = getPropertyUsers($_POST['property_id']);
                deleteData("camera_permissions", "property_id", $_POST['property_id']);
                foreach ($users as $user) {
                    foreach ($camera_ids as $camera_id) {
                        $payload_data = [
                            "property_id" => $_POST['property_id'],
                            "property_user_id" => $user['id'],
                            "property_user_email" => $user['email'] ?? "",
                            "property_user_name" => $user['firstname'] . " " . $user['lastname'],
                            "have_view_permission" => 1,
                            "camera_id" => $camera_id,
                        ];
                        insertData("camera_permissions", $payload_data);
                    }
                }

                $where = 'id = :id';
                $params = ['id' => $default['id']];
                $response = updateTable('camera_permissions_global', $data, $where, $params);
                sendJsonResponse(200, [
                    "success" => true,
                    "data" => $users ?? null
                ]);
                exit;
            }
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response ?? null
        ]);
        exit;
    }

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

        if ($_POST["isIndividual"] == "true") {
            $keys = ['property_id', 'property_user_id', 'property_user_name', 'have_view_permission', 'camera_id', 'property_user_email'];
            $data = array_intersect_key($_POST, array_flip($keys));
            $where = 'id = :id';
            $params = ['id' => $_POST['id']];
            $old_permission_data = fetchDataSingle("camera_permissions", ["id" => $_POST['id']]);
            $response = updateTable('camera_permissions', $data, $where, $params);
            $new_permission_data = fetchDataSingle("camera_permissions", ["id" => $_POST['id']]);
            createAuditLog(
                $_SESSION["userid"],
                'Update',
                'camera_permissions',
                $_POST['id'] ?? null,
                $_SESSION["email"] ?? null,
                $_SESSION['property'],
                json_encode($old_permission_data),
                json_encode($new_permission_data),
                'Camera Permissions Updated',
                'high',
                'Permissions'
            );
        }else {
            $default = fetchDataSingle("camera_permissions_global", ["property_id" => $_POST['property_id']]);
            $keys = ['camera_ids', 'property_id'];
            $data = array_intersect_key($_POST, array_flip($keys));

            if (empty($default)) {
                $response = insertData("camera_permissions_global", $data);
                $camera_ids = json_decode($data["camera_ids"]);
                $users = getPropertyUsers($_POST['property_id']);
                deleteData("camera_permissions", "property_id", $_POST['property_id']);
                foreach ($users as $user) {
                    foreach ($camera_ids as $camera_id) {
                        $payload_data = [
                            "property_id" => $_POST['property_id'],
                            "property_user_id" => $user['id'],
                            "property_user_email" => $user['email'] ?? "",
                            "property_user_name" => $user['firstname'] . " " . $user['lastname'],
                            "have_view_permission" => 1,
                            "camera_id" => $camera_id,
                        ];
                        insertData("camera_permissions", $payload_data);
                    }
                }
            } else {
                $camera_ids = json_decode($data["camera_ids"]);
                $users = getPropertyUsers($_POST['property_id']);
                deleteData("camera_permissions", "property_id", $_POST['property_id']);
                foreach ($users as $user) {
                    foreach ($camera_ids as $camera_id) {
                        $payload_data = [
                            "property_id" => $_POST['property_id'],
                            "property_user_id" => $user['id'],
                            "property_user_email" => $user['email'] ?? "",
                            "property_user_name" => $user['firstname'] . " " . $user['lastname'],
                            "have_view_permission" => 1,
                            "camera_id" => $camera_id,
                        ];
                        insertData("camera_permissions", $payload_data);
                    }
                }

                $where = 'id = :id';
                $params = ['id' => $default['id']];
                $response = updateTable('camera_permissions_global', $data, $where, $params);
                sendJsonResponse(200, [
                    "success" => true,
                    "data" => $users ?? null
                ]);
                exit;
            }
        }

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

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

        $camera_permissions = fetchData("camera_permissions", ["property_id" => $_POST['property_id']]);

        if (!empty($camera_permissions) && is_array($camera_permissions)) {
            foreach ($camera_permissions as &$permission) {
                if (!empty($permission['camera_id'])) {
                    $cameraData = fetchDataSingle("live_camera_streaming_data", ["id" => $permission['camera_id']]);
                    $permission['camera_data'] = $cameraData;
                }
            }
        }

        $camera_global_permissions = fetchDataSingle("camera_permissions_global", ["property_id" => $_POST['property_id']]);
        if (!empty($camera_global_permissions)) {
            $camera_ids = json_decode($camera_global_permissions['camera_ids']);
            if (!empty($camera_ids)) {
                $camera_global_permissions['cameras'] = [];
                foreach ($camera_ids as $id) {
                    $camera = fetchDataSingle("live_camera_streaming_data", ["id" => $id]);
                    if ($camera) {
                        $camera_global_permissions['cameras'][] = $camera; // Appends to the array
                    }
                }
            }
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => $camera_permissions ?? null,
            "global_permissions" => $camera_global_permissions ?? null
        ]);
        exit;
    }

    if (isset($_POST['delete_camera_permission'])) {
        if (empty($_POST['id'])) {
            sendJsonResponse(400, ["error" => 'Id is missing ']);
            exit;
        }
        $camera_permission_data = fetchDataSingle('camera_permissions', ['id' => $_POST['id']]);
        $response = deleteData('camera_permissions', 'id', $_POST['id']);
        
        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'camera_permissions',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property'],
            json_encode($camera_permission_data),
            null,
            'Camera Permissions Deleted',
            'high',
            'Permissions'
        );    

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response ?? null
        ]);
        exit;
    }
    
    if (isset($_POST['get_global_camera_properties'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        $response = fetchDataSingle('camera_permissions_global',["property_id"=>$_POST["property_id"]]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response ?? null,
            "message"=> "Successfully fetch data"
        ]);
        exit;
    }
    
    if (isset($_POST['edit_global_permissions_for_cameras'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        if (empty($_POST['id'])) {
            sendJsonResponse(500, ["error" => 'id is missing']);
            exit;
        }

        $keys = ['property_id', 'camera_ids'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $response = updateTable('camera_permissions_global', $data, $where, $params);

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response ?? null,
            "message"=> "Successfully updated the data"
        ]);
        exit;
    }
    
    if (isset($_POST['delete_global_camera_properties'])) {
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        $response = deleteData('camera_permissions_global','property_id',$_POST["property_id"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response ?? null,
            "message"=> "Deleted successfully"
        ]);
        exit;
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);

    createAuditLog(
        $_SESSION["userid"] ?? null,
        $_POST['getHardwareSettingByDoorId'] ?? $_POST['get_hardwares_settings_events'] ?? null,
        null,
        null,
        $_SESSION["email"] ?? null,
        $_POST['property_id'] ?? null,
        null,
        null,
        $th->getMessage(),
        'highest',
        'Error'
    );
}


function getPropertyUsers($propertyId, $roleName = "user")
{
    $userRole = fetchDataSingle("roles", ['name' => $roleName]);
    if (empty($userRole['id'])) {
        throw new Exception('Could not find the role "' . $roleName . '" in the DB');
    }
    $propertyUsersSql = "
        SELECT 
            pu.*,
            pud.firstname,
            pud.lastname,
            'property_user' AS user_source
        FROM 
            property_users pu
        LEFT JOIN 
            property_users_data pud ON pu.id = pud.property_user
        WHERE 
            pu.property_id = :property_id
            AND pu.role = :role_id
            AND pu.deleted_at IS NULL
    ";

    $propertyUsers = fetchDataWithJoins($propertyUsersSql, [
        ':property_id' => $propertyId,
        ':role_id' => $userRole['id']
    ]) ?: [];

    $multiPropUsersSql = "
        SELECT 
            mp.*,
            pu.email,
            mp.firstname,
            mp.lastname,
            'multi_prop' AS user_source
        FROM 
            multi_prop_users mp
        LEFT JOIN 
            property_users pu ON mp.user_assoc = pu.id
        WHERE 
            mp.property_id = :property_id
            AND mp.role = :role_id
            AND mp.deleted_at IS NULL
    ";

    $multiPropUsers = fetchDataWithJoins($multiPropUsersSql, [
        ':property_id' => $propertyId,
        ':role_id' => $userRole['id']
    ]) ?: [];

    return array_merge($propertyUsers, $multiPropUsers);
}
