<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', [], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$restaurantId = (int) ($input['restaurant_id'] ?? 0);
$eventType = trim($input['event_type'] ?? '');
$categoryId = (int) ($input['category_id'] ?? 0);
$menuItemId = (int) ($input['menu_item_id'] ?? 0);

if ($restaurantId <= 0) {
    jsonResponse(false, 'Invalid restaurant');
}

$validEvents = ['menu_view', 'category_view', 'item_view', 'add_to_cart', 'remove_from_cart', 'search', 'checkout_start', 'order_placed'];
if (!in_array($eventType, $validEvents)) {
    jsonResponse(false, 'Invalid event type');
}

$db = Database::getInstance();

$sessionId = $_SESSION['menu_session_id'] ?? ('sess_' . bin2hex(random_bytes(16)));
if (!isset($_SESSION['menu_session_id'])) {
    $_SESSION['menu_session_id'] = $sessionId;
}
$deviceType = getDeviceType();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

$db->insert('menu_view_logs', [
    'restaurant_id' => $restaurantId,
    'category_id'   => $categoryId ?: null,
    'menu_item_id'  => $menuItemId ?: null,
    'session_id'    => $sessionId,
    'event_type'    => $eventType,
    'device_type'   => $deviceType,
    'user_agent'    => substr($userAgent, 0, 500),
    'created_at'    => date('Y-m-d H:i:s'),
]);

jsonResponse(true, 'Event tracked');
