<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../assets/vendor/phpqrcode/qrlib.php';

$restaurantId = (int) ($_GET['restaurant_id'] ?? 0);
$singleTableId = (int) ($_GET['table_id'] ?? 0);
$printAll = isset($_GET['all']);

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

$db = Database::getInstance();

$restaurant = $db->query("SELECT * FROM restaurants WHERE id = ? AND status = 'active'", [$restaurantId])->fetch();
if (!$restaurant) {
    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);
$scanText = $operatingMode == 2 ? 'Scan to Order' : 'Scan to View Menu';

$tables = [];
if ($singleTableId > 0) {
    $table = $db->query("SELECT * FROM tables WHERE id = ? AND restaurant_id = ?", [$singleTableId, $restaurantId])->fetch();
    if ($table) $tables[] = $table;
} elseif ($printAll) {
    $tables = $db->query("SELECT * FROM tables WHERE restaurant_id = ? AND is_active = 1 ORDER BY table_number ASC", [$restaurantId])->fetchAll();
}

$qrUrl = getBaseUrl() . '/menu.php?r=' . urlencode($restaurant['slug']);
$wifiName = $settings['wifi_name'] ?? '';
$wifiPass = $settings['wifi_password'] ?? '';
$logoPath = !empty($restaurant['logo']) ? $restaurant['logo'] : '';

$tmpDir = sys_get_temp_dir();
$mainQRFile = $tmpDir . DIRECTORY_SEPARATOR . 'qr-main-' . $restaurantId . '.png';
QRcode::png($qrUrl, $mainQRFile, 'M', 8, 2);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Codes - <?php echo sanitize($restaurant['name']); ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #333; }

        .qr-card {
            width: 210mm;
            min-height: 297mm;
            padding: 20mm;
            margin: 0 auto;
            page-break-after: always;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
        }

        .qr-card:last-child { page-break-after: avoid; }

        .qr-restaurant-logo {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-bottom: 16px;
        }

        .qr-restaurant-logo-placeholder {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 16px;
        }

        .qr-restaurant-name {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 4px;
            color: #212529;
        }

        .qr-subtitle {
            font-size: 14px;
            color: #6c757d;
            margin-bottom: 24px;
        }

        .qr-code-image {
            width: 250px;
            height: 250px;
            border: 3px solid #e9ecef;
            border-radius: 16px;
            padding: 12px;
            background: #fff;
            margin-bottom: 24px;
        }

        .qr-code-image img {
            width: 100%;
            height: 100%;
        }

        .qr-scan-text {
            font-size: 20px;
            font-weight: 700;
            color: #e74c3c;
            margin-bottom: 8px;
        }

        .qr-table-number {
            font-size: 36px;
            font-weight: 800;
            color: #2c3e50;
            margin-bottom: 8px;
        }

        .qr-table-name {
            font-size: 16px;
            color: #6c757d;
            margin-bottom: 20px;
        }

        .qr-wifi {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 16px 24px;
            margin-top: 16px;
            display: inline-block;
        }

        .qr-wifi-label {
            font-size: 12px;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 4px;
        }

        .qr-wifi-name {
            font-size: 16px;
            font-weight: 700;
            color: #212529;
        }

        .qr-wifi-pass {
            font-size: 14px;
            color: #495057;
            font-family: monospace;
        }

        .qr-footer {
            margin-top: 32px;
            font-size: 11px;
            color: #adb5bd;
        }

        .toolbar {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: #fff;
            border-bottom: 1px solid #e9ecef;
            padding: 12px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 1000;
        }

        .toolbar h5 { margin: 0; }
        .toolbar-actions { display: flex; gap: 8px; }
        .toolbar-actions button {
            padding: 8px 16px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            background: #fff;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
        }
        .toolbar-actions button.primary {
            background: #e74c3c;
            color: #fff;
            border-color: #e74c3c;
        }

        @media print {
            .toolbar { display: none !important; }
            body { margin: 0; }
            .qr-card { margin: 0; padding: 15mm; }
        }
    </style>
</head>
<body>
    <div class="toolbar" id="toolbar">
        <h5><i class="fas fa-qrcode me-2"></i>QR Codes - <?php echo sanitize($restaurant['name']); ?></h5>
        <div class="toolbar-actions">
            <button onclick="window.print()" class="primary"><i class="fas fa-print me-1"></i>Print</button>
            <button onclick="window.close()"><i class="fas fa-times me-1"></i>Close</button>
        </div>
    </div>

    <div style="height:60px;"></div>

    <div class="qr-card">
        <?php if ($logoPath): ?>
        <img class="qr-restaurant-logo" src="<?php echo getBaseUrl() . '/' . sanitize($logoPath); ?>" alt="Logo">
        <?php else: ?>
        <div class="qr-restaurant-logo-placeholder">
            <?php echo strtoupper(substr($restaurant['name'], 0, 2)); ?>
        </div>
        <?php endif; ?>

        <div class="qr-restaurant-name"><?php echo sanitize($restaurant['name']); ?></div>
        <div class="qr-subtitle"><?php echo $scanText; ?></div>

        <div class="qr-code-image">
            <img src="data:image/png;base64,<?php echo base64_encode(file_get_contents($mainQRFile)); ?>" alt="QR Code">
        </div>

        <div class="qr-scan-text"><i class="fas fa-mobile-alt me-1"></i> <?php echo $scanText; ?></div>

        <?php if (!empty($wifiName)): ?>
        <div class="qr-wifi">
            <div class="qr-wifi-label"><i class="fas fa-wifi me-1"></i> Connect to Wi-Fi</div>
            <div class="qr-wifi-name"><?php echo sanitize($wifiName); ?></div>
            <?php if (!empty($wifiPass)): ?>
            <div class="qr-wifi-pass">Password: <?php echo sanitize($wifiPass); ?></div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="qr-footer">Powered by Tap2Order</div>
    </div>

    <?php foreach ($tables as $table):
        $tableQRFile = $tmpDir . DIRECTORY_SEPARATOR . 'qr-table-' . $restaurantId . '-' . $table['id'] . '.png';
        $tableUrl = $qrUrl . '&table=' . urlencode($table['table_number']);
        QRcode::png($tableUrl, $tableQRFile, 'M', 8, 2);
    ?>
    <div class="qr-card">
        <?php if ($logoPath): ?>
        <img class="qr-restaurant-logo" src="<?php echo getBaseUrl() . '/' . sanitize($logoPath); ?>" alt="Logo">
        <?php else: ?>
        <div class="qr-restaurant-logo-placeholder">
            <?php echo strtoupper(substr($restaurant['name'], 0, 2)); ?>
        </div>
        <?php endif; ?>

        <div class="qr-restaurant-name"><?php echo sanitize($restaurant['name']); ?></div>
        <div class="qr-table-number">Table <?php echo sanitize($table['table_number']); ?></div>
        <?php if (!empty($table['table_name'])): ?>
        <div class="qr-table-name"><?php echo sanitize($table['table_name']); ?></div>
        <?php endif; ?>
        <div class="qr-subtitle"><?php echo $scanText; ?></div>

        <div class="qr-code-image">
            <img src="data:image/png;base64,<?php echo base64_encode(file_get_contents($tableQRFile)); ?>" alt="QR Code - Table <?php echo sanitize($table['table_number']); ?>">
        </div>

        <div class="qr-scan-text"><i class="fas fa-mobile-alt me-1"></i> <?php echo $scanText; ?></div>

        <?php if (!empty($wifiName)): ?>
        <div class="qr-wifi">
            <div class="qr-wifi-label"><i class="fas fa-wifi me-1"></i> Wi-Fi</div>
            <div class="qr-wifi-name"><?php echo sanitize($wifiName); ?></div>
            <?php if (!empty($wifiPass)): ?>
            <div class="qr-wifi-pass"><?php echo sanitize($wifiPass); ?></div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="qr-footer">Powered by Tap2Order</div>
    </div>
    <?php endforeach; ?>
</body>
</html>
<?php
@unlink($mainQRFile);
foreach ($tables as $table) {
    $f = $tmpDir . DIRECTORY_SEPARATOR . 'qr-table-' . $restaurantId . '-' . $table['id'] . '.png';
    @unlink($f);
}
