<?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);
}

$restaurantId = (int) ($_POST['restaurant_id'] ?? 0);
$menuItemId = (int) ($_POST['menu_item_id'] ?? 0);
$eventType = trim($_POST['event_type'] ?? 'add_to_cart');

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

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

$db = Database::getInstance();

$item = $db->query(
    "SELECT id, category_id FROM menu_items WHERE id = ? AND restaurant_id = ?",
    [$menuItemId, $restaurantId]
)->fetch();

if (!$item) {
    jsonResponse(false, 'Item not found');
}

$categoryId = $item['category_id'];
$sessionId = $_SESSION['menu_session_id'] ?? ('sess_' . bin2hex(random_bytes(16)));
$deviceType = getDeviceType();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

$db->insert('menu_view_logs', [
    'restaurant_id' => $restaurantId,
    'category_id'   => $categoryId,
    'menu_item_id'  => $menuItemId,
    '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');
