<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'phpqrcode' . DIRECTORY_SEPARATOR . 'qrlib.php';

$restaurantId = (int) ($_GET['restaurant_id'] ?? 0);
$tableId = (int) ($_GET['table_id'] ?? 0);
$format = strtolower(trim($_GET['format'] ?? 'png'));

if ($restaurantId <= 0) {
    http_response_code(400);
    echo 'Invalid restaurant ID';
    exit;
}

$db = Database::getInstance();

$restaurant = $db->query("SELECT * FROM restaurants WHERE id = ? AND status = 'active'", [$restaurantId])->fetch();
if (!$restaurant) {
    http_response_code(404);
    echo 'Restaurant not found';
    exit;
}

$settings = $db->query("SELECT * FROM restaurant_settings WHERE restaurant_id = ?", [$restaurantId])->fetch();
$operatingMode = (int) ($settings['operating_mode'] ?? $restaurant['operating_mode'] ?? 1);

$qrUrl = getBaseUrl() . '/menu.php?r=' . urlencode($restaurant['slug']);

$tableNumber = null;
if ($tableId > 0) {
    $table = $db->query("SELECT * FROM tables WHERE id = ? AND restaurant_id = ?", [$tableId, $restaurantId])->fetch();
    if ($table) {
        $tableNumber = $table['table_number'];
        $qrUrl .= '&table=' . urlencode($tableNumber);
    }
}

if ($format === 'svg') {
    header('Content-Type: image/svg+xml');
    echo QRcode::svg($qrUrl, false, 'M', 6, 2);
} else {
    QRcode::png($qrUrl, false, 'M', 6, 2);
}
