<?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'])) {
    sendJsonResponse(401, ["error" => 'Unauthorized to access. Please login']);
    exit;
}


try {

    if (isset($_POST['get_user_menu_for_property_user'])) {
        $response = getMenuByUser($pdo, $_SESSION["userid"]);
        // $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        // $response = fetchData('app_settings', ["property_id" => $_POST['property_id'], "userid" => $_SESSION["userid"]]);
        if ($response === false) sendJsonResponse(500, ["error" => 'Could not fetch data ']);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
    }

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

    if (isset($_POST['add_user_property_preferences'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        if(empty($_POST['property_id'])){
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        if(empty($_POST['starting_property_id'])) $_POST['starting_property_id'] = null;
        $_POST["userid"] = $_SESSION["userid"];
        $_POST["user_email"] = $_SESSION["email"];
        $keys = ['theme_mode', 'time_format', 'time_zone', "starting_property_id", 'auto_logout_time', 'app_start_page', 'property_id', 'userid', 'user_email','is_card_view'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $response = insertData('app_settings', $data);
        if ($response == false) sendJsonResponse(500, ["error" => "Could not add data"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'gate_doors',
            null,
            $_SESSION["email"],
            $_POST['property_id'] ?? null,
            null,
            null,
            'Preference added',
            'high',
            'User management'
        );
    }

    if (isset($_POST['edit_user_property_preferences'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property'] ?? null;
        $_POST["userid"] = $_SESSION["userid"];
        $_POST["user_email"] = $_SESSION["email"];
        if(empty($_POST['starting_property_id'])) $_POST['starting_property_id'] = null;
        $keys = ['theme_mode', 'time_format', 'time_zone','starting_property_id', 'auto_logout_time', 'app_start_page', 'property_id', 'userid', 'user_email','is_card_view'];
        $data = array_intersect_key($_POST, array_flip($keys));

        $where = 'id = :id';
        $params = ['id' => $_POST['id']];

        $response = updateTable('app_settings', $data, $where, $params);
        if ($response === false) sendJsonResponse(500, ["error" => "Could not add data"]);
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'gate_doors',
            null,
            $_SESSION["email"],
            $_POST['property_id'] ?? null,
            null,
            null,
            'A new door added',
            'high',
            'Doors'
        );
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error: " . $th->getMessage()]);

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