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

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

require_once __DIR__ . '/../assets/vendor/phpqrcode/qrlib.php';

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

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

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

$db = Database::getInstance();

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

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

$qrDir = UPLOAD_PATH . DIRECTORY_SEPARATOR . 'qrcodes';
if (!is_dir($qrDir)) {
    mkdir($qrDir, 0755, true);
}

$filename = 'qr-' . $restaurantId;
if ($tableId > 0) {
    $filename .= '-table-' . $tableNumber;
}
$filename .= '.png';
$filepath = $qrDir . DIRECTORY_SEPARATOR . $filename;

QRcode::png($qrUrl, $filepath, 'M', 8, 2);

 jsonResponse(true, 'QR code generated', [
    'path' => 'uploads/qrcodes/' . $filename,
    'url'  => $qrUrl,
]);
