<?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';
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['getDoorsRequest'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        $sql = "
        SELECT 
            gate_doors.id,
            gate_doors.group_by,
            gate_doors.door_name,
            gate_doors.door_image,
            gate_doors.property_id,
            gate_doors.location,
            gate_doors.access_code,
            gate_doors.status,
            gate_doors.hardware_id,
            gate_doors.is_primary,
            gate_doors.complete_url_assigned,
            gate_doors.type,
            gate_doors.door_key,
            gate_doors.schedulesId,
            gate_doors.description,
            gate_doors.connectionStatus,
            gate_doors.output_assign,
            gate_doors.input_assign,
            gate_doors.iiNumber,
            gate_doors.iiToneOpenNumber,
            gate_doors.CreatedBy,
            gate_doors.camera_id,
            gate_doors.created_at AS gate_created_at,
            gate_doors.updated_at AS gate_updated_at,
            
            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 
            gate_doors
        LEFT JOIN 
            live_camera_streaming_data ON gate_doors.camera_id = live_camera_streaming_data.id
        WHERE 
            gate_doors.property_id = :userid;
        ";

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

        // $response = fetchData( 'gate_doors', conditions: ['CreatedBy' => $_SESSION['userid']]);
        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data ']);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

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

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

        if (isset($_FILES['door_image']) && $_FILES['door_image']['error'] == 0) {
            $isUploaded = uploadToAllImages('door_image', $propertyId,);
            if ($isUploaded['success']) {
                $imagePath = $isUploaded['image_path'];
            } else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }
        
        $_POST['door_image'] = $imagePath ?? null;
        $_POST['CreatedBy'] = $_SESSION['userid'];

        if(isset($_POST['is_primary']) && $_POST['is_primary']==1 && empty($_POST['iiNumber'])){
            sendJsonResponse(500, ["error" => "Phone number is required if the door is primary"]);
            exit;
        }elseif(isset($_POST['is_primary']) && $_POST['is_primary']==1 && !empty($_POST['iiNumber'])){
            $is_already = fetchData('gate_doors', ['property_id' => $_POST['property_id'], 'iiNumber' => $_POST['iiNumber'],'is_primary' => 1]);
            if(!empty($is_already) && is_array($is_already)){
                sendJsonResponse(500, ["error" => "Primary door with this phone number already exists"]);
                exit;
            }
        }

        if(!empty($_POST['iiNumber'])){
            $is_already = fetchData('gate_doors', ['property_id' => $_POST['property_id'], 'iiNumber' => $_POST['iiNumber']]);
            if(!empty($is_already) && is_array($is_already)){
                for ($i=0; $i < count($is_already); $i++) { 
                    if($is_already[$i]['door_key'] == $_POST['door_key']){
                        sendJsonResponse(500, ["error" => "Door key already found"]);
                        exit;
                    }
                }
            }
        }


        $keys = ['group_by', 'is_primary', 'property_id', 'door_name', 'door_key', 'location', 'access_code', 'status', 'door_image', 'hardware_id', 'type', 'description', 'connectionStatus', 'outputInputAssign', 'iiNumber', 'iiToneOpenNumber', 'CreatedBy'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('gate_doors', $data);
        $last_door_id = getLastInsertId();
        $last_door_data = fetchDataSingle('gate_doors', ['id' => $last_door_id]);
        if ($response == false) {
            sendJsonResponse(500, ["error" => "Could not add data " . $response]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'gate_doors',
            null,
            $_SESSION["email"],
            $_POST['property_id'] ?? null,
            null,
            json_encode($last_door_data),
            'A new door added',
            'high',
            'Doors'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => "Data has been added successfully",
        ]);
    }

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

        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        $propertyId = $_POST['property_id'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        $dataById = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        if (empty($dataById)) {
            sendJsonResponse(500, ["error" => 'Data not found against the id ' . $_POST['id']]);
            exit;
        }

        if (isset($_FILES['door_image']) && $_FILES['door_image']['error'] == 0) {
            $message = deleteSingleImageFromAllImages($dataById['door_image']);
            $isUploaded = uploadToAllImages('door_image', $propertyId);
            if($isUploaded['success']){
                $_POST['door_image']=$isUploaded['image_path'];
            }else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }
        
        if(isset($_POST['is_primary']) && $_POST['is_primary']==1 && !empty($_POST['iiNumber'])){
            $is_already = fetchData('gate_doors', ['property_id' => $_POST['property_id'], 'iiNumber' => $_POST['iiNumber'], 'is_primary' => 1]);
            if(!empty($is_already) && is_array($is_already)){
                $is_duplicate = false;
                foreach($is_already as $door){
                    if($door['id'] != $_POST['id']){
                        $is_duplicate = true;
                        break;
                    }
                }
                if($is_duplicate){
                    sendJsonResponse(500, ["error" => "Primary door with this phone number already exists"]);
                    exit;
                }
            }
        }
        
        if(!empty($_POST['iiNumber'])){
            $is_already = fetchData('gate_doors', ['property_id' => $_POST['property_id'], 'iiNumber' => $_POST['iiNumber']]);
            if(!empty($is_already) && is_array($is_already)){
                for ($i=0; $i < count($is_already); $i++) { 
                    if($is_already[$i]['id'] != $_POST['id'] && $is_already[$i]['door_key'] == $_POST['door_key']){
                        sendJsonResponse(500, ["error" => "Door key already found"]);
                        exit;
                    }
                }
            }
        }
        
        if ($_POST['is_primary']) {
            $is_primary_door = fetchData('gate_doors', ['property_id' => $_POST['property_id'], 'is_primary' => 1, 'group_by' => $group_by]);
            if (isset($is_primary_door[0]['id'])) {
                $update_data = [
                    'is_primary' => 0
                ];
                $where = 'id = :id';
                $params = ['id' => $is_primary_door[0]['id']];
                updateTable('gate_doors', $update_data, $where, $params);
            }
        }
        $keys = ['group_by', 'is_primary', 'property_id', 'door_name', 'door_key', 'location', 'door_image', 'access_code', 'status', 'hardware_id', 'type', 'description', 'connectionStatus', 'outputInputAssign', 'iiNumber', 'iiToneOpenNumber'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $old_door_data = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        $updateSuccess = updateTable('gate_doors', $data, $where, $params);
        $updated_door_data = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        
        $response = $updateSuccess;
        if ($response == false) sendJsonResponse(500, ["error" => "Could not add data " . $response]);

        createAuditLog(
            $_SESSION["userid"],
            'update',
            'gate_doors',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'],
            json_encode($old_door_data),
            json_encode($updated_door_data),
            'Updated door',
            'high',
            'Doors'
        );

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

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

        $dataById = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        if (empty($dataById)) {
            sendJsonResponse(500, ["error" => 'Data not found against the id ' . $_POST['id']]);
            exit;
        }

        if(!empty($dataById['door_image'])) $message = deleteSingleImageFromAllImages($dataById['door_image']);

        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        
        $response = deleteData('gate_doors',  'id',  $_POST['id']);
        if ($response == false) sendJsonResponse(500, ["error" => "Could not delete the hardware"]);

        $today_date = date('Y-m-d');
        $created_date = date('Y-m-d', strtotime($deleted_camera_data['created_at'] . ' +1 month'));
        if($created_date < $today_date){
            $created_at = date('Y-m-d H:i:s', strtotime($created_date));
            insertData('delete_gate_doors', [
                'data' => json_encode($dataById),
                'property_id' => $dataById['property_id'],
                'created_at' => $created_date,
                'deleted_at' => date('Y-m-d H:i:s'),
            ]);
        }
        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'gate_doors',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            json_encode($dataById),
            null,
            'Door deleted',
            'high',
            'Doors'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

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

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

        $alreadyAdded = fetchDataSingle("gate_door_group", ['property_id' => $_POST['property_id'], "groupName" => $_POST['groupName']]);
        if (!empty($alreadyAdded)) {
            sendJsonResponse(500, ["error" => 'You already have this group.Please change']);
            exit;
        }
        $keys = ['groupName', 'property_id'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('gate_door_group', $data);
        $group_id = getLastInsertId();
        $group_data = fetchDataSingle('gate_door_group', ['id' => $group_id]);
        if ($response == false) sendJsonResponse(500, ["error" => "Could not add data"]);
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'gate_door_group',
            $group_id ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'] ?? null,
            null,
            json_encode($group_data),
            'Group Added',
            'high',
            'Group'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response,
            "message" => "Group added successfully"
        ]);
    }

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

        $doorId = $_POST['door_id'] ?? null;
        if (!$doorId) {
            sendJsonResponse(400, ["error" => "Missing door_id"]);
            exit;
        }

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

        $old_group = "";
        if(isset($old_group_data['group_by']) && !empty($old_group_data['group_by'])){
            $old_group = $old_group_data['group_by'];
        }

        $stmt = $pdo->prepare("
            UPDATE gate_doors 
            SET group_by = '' 
            WHERE id = :door_id
        ");
        $stmt->execute([':door_id' => $doorId]);
       
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'gate_doors',
            $doorId ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property'] ?? null,
            $old_group,
            "",
            'Group removed from door',
            'high',
            'Gate Door'
        );
        
        sendJsonResponse(200, [
            "success" => true,
            "message" => "Door removed from group"
        ]);
    }


    if (isset($_POST['quick_change_group_by_request'])) {
        $doorId = $_POST['id'] ?? null;
        if (!$_POST['id']) {
            sendJsonResponse(400, ["error" => "Missing door_id"]);
            exit;
        }
        if(empty($_POST["property_id"])) $_POST["property_id"]=$_SESSION['property'];
        if(empty($_POST["property_id"])){
            sendJsonResponse(500, ["error" => "Property id is missing"]);
            exit;
        }

        $keys = ['group_by','is_primary'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $old_group_data = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        $updateSuccess = updateTable('gate_doors', $data, $where, $params);

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'gate_doors',
            $doorId ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property'] ?? null,
            $old_group_data['group_by'],
            $_POST['group_by'],
            'Group added to the door',
            'high',
            'Gate Door'
        );

        sendJsonResponse(200, [
            "success" => true,
            "message" => "Group added to the door"
        ]);
    }

    if (isset($_POST['getDoorByIdRequest'])) {
        $response = fetchDataWithId('gate_doors', $_POST['id']);
        if ($response == false) sendJsonResponse(500, ["error" => "Could not add data " . $response]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

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

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

    if (isset($_POST['get_selected_cameras_request'])) {
        $response = fetchData('door_cameras', ['door_id' => $_POST['door_id']]);
        if ($response === false) sendJsonResponse(500, ["error" => "Could not get doors group"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

    if (isset($_POST['add_camera_to_door_request'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')) {
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        $camera_ids = json_decode($_POST['all_cameras'], true);;
        $door_cameras = fetchData('door_cameras', ['door_id' => $_POST['id']]);
        if (!empty($door_cameras)) {
            deleteData('door_cameras', 'door_id', $_POST['id']);
        }
        if (!empty($camera_ids) && is_array($camera_ids)) {
            foreach ($camera_ids as $camera_id) {
                $cameraDataToAdd = [
                    'door_id' => $_POST['id'],
                    'camera_id' => $camera_id
                ];
                $insertCameraResponse = insertData('door_cameras', $cameraDataToAdd);
            }
        }
        if (empty($_POST['camera_id']) || $_POST['camera_id'] == "") {
            $_POST['camera_id'] = null;
            deleteData("door_cameras", "door_id", $_POST['id']);
        }
        $keys = ['camera_id'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $old_door = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        $updateSuccess = updateTable('gate_doors', $data, $where, $params);
        $updated_door = fetchDataSingle('gate_doors', ['id' => $_POST['id']]);
        $response = $updateSuccess;
        if ($response === false) sendJsonResponse(500, ["error" => "Could not add data " . $response]);
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'gate_doors',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_POST['property_id'],
            json_encode($old_door),
            json_encode($updated_door),
            'Camera Added to door',
            'high',
            'Doors'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

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

        if (empty($_POST['id']) || empty($_POST['newGroupName'])) {
            sendJsonResponse(500, ["error" => "Group ID and new name are required"]);
            exit;
        }

        // First get the old group name
        $oldGroup = fetchDataSingle('gate_door_group', ['id' => $_POST['id']]);
        if (empty($oldGroup)) {
            sendJsonResponse(500, ["error" => "Group not found"]);
            exit;
        }

        // Update all doors with the old group name to use the new group name
        $update_data = [
            'group_by' => $_POST['newGroupName']
        ];
        $where = 'group_by = :oldGroupName AND property_id = :property_id';
        $params = [
            'oldGroupName' => $oldGroup['groupName'],
            'property_id' => $_POST['property_id']
        ];
        
        $updateSuccess = updateTable('gate_doors', $update_data, $where, $params);
        
        if ($updateSuccess === false) {
            sendJsonResponse(500, ["error" => "Could not update group name in doors"]);
            exit;
        }

        // Update the group name in gate_door_group table
        $group_update_data = [
            'groupName' => $_POST['newGroupName']
        ];
        $group_where = 'id = :id';
        $group_params = ['id' => $_POST['id']];
        $old_group_data = fetchDataSingle('gate_door_group', ['id' => $_POST['id']]);
        $groupUpdateSuccess = updateTable('gate_door_group', $group_update_data, $group_where, $group_params);
        $updated_group_data = fetchDataSingle('gate_door_group', ['id' => $_POST['id']]);
        
        if ($groupUpdateSuccess === false) {
            sendJsonResponse(500, ["error" => "Could not update group name"]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'door_groups',
            $_POST['id'],
            $_SESSION["email"],
            $_POST['property_id'],
            json_encode($old_group_data),
            json_encode($updated_group_data),
            "Updated group name from {$oldGroup['groupName']} to {$_POST['newGroupName']}",
            'medium',
            'Doors'
        );

        sendJsonResponse(200, [
            "success" => true,
            "message" => "Group name updated successfully"
        ]);
    }

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

        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['groupName'])) {
            sendJsonResponse(500, ["error" => "Group name is required"]);
            exit;
        }

        // First update all doors in this group to have no group
        $update_data = [
            'group_by' => null
        ];
        $where = 'group_by = :groupName AND property_id = :property_id';
        $params = [
            'groupName' => $_POST['groupName'],
            'property_id' => $_POST['property_id']
        ];
        
        $updateSuccess = updateTable('gate_doors', $update_data, $where, $params);
        
        if ($updateSuccess === false) {
            sendJsonResponse(500, ["error" => "Could not remove group from doors"]);
            exit;
        }

        // Then delete the group from gate_door_group table
        $deleted_group_data = fetchDataSingle('gate_door_group', ['id' => $_POST['id']]);
        $deleteSuccess = deleteData('gate_door_group', 'id', $_POST['id']);
        
        if ($deleteSuccess === false) {
            sendJsonResponse(500, ["error" => "Could not delete group"]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'door_groups',
            null,
            $_SESSION["email"],
            $_POST['property_id'],
            json_encode($deleted_group_data),
            null,
            "Deleted group {$_POST['groupName']}",
            'medium',
            'Doors'
        );

        sendJsonResponse(200, [
            "success" => true,
            "message" => "Group deleted successfully"
        ]);
    }

    if(isset($_POST['chec_valid_door_key'])){
        $door_key = $_POST['door_key'];
        $door_number = $_POST['door_number'];
        $door_key_check = fetchDataSingle('gate_doors', ['door_key' => $door_key, 'iiNumber' => $door_number]);
        if(isset($door_key_check['id'])){
            echo 0;
        }
        else{
            echo 1;
        }
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);
    createAuditLog(
        $_SESSION["userid"] ?? null,
        $_POST['getDoorsRequest'] ?? $_POST['add_camera_to_door_request'] ?? $_POST['get_camera_request'] ?? $_POST['GetDoorsGroupRequest'] ?? $_POST['getDoorByIdRequest'] ?? $_POST['addGroupRequest'] ?? $_POST['addGroupRequest'] ?? $_POST['deleteDoorByIdRequest'] ?? $_POST['update_Gate_door_request'] ?? $_POST['add_Gate_door_request'] ?? $_POST['getDoorsRequest'] ?? null,
        null,
        null,
        $_SESSION["email"] ?? null,
        $_POST['property_id'],
        null,
        null,
        $th->getMessage(),
        'highest',
        'Doors'
    );
}
