<?php
$pageTitle = 'QR Code Management';
require_once __DIR__ . '/includes/header.php';

$db = Database::getInstance();
$baseUrl = getBaseUrl();

$restaurants = $db->query("SELECT id, name, slug, status FROM restaurants WHERE status = 'active' ORDER BY name ASC")->fetchAll();
$selectedRestaurant = (int) ($_GET['restaurant_id'] ?? 0);
$restaurantData = null;
$tables = [];
$restaurantSettings = null;

if ($selectedRestaurant > 0) {
    $restaurantData = $db->query("SELECT * FROM restaurants WHERE id = ?", [$selectedRestaurant])->fetch();
    if ($restaurantData) {
        $restaurantSettings = $db->query("SELECT * FROM restaurant_settings WHERE restaurant_id = ?", [$selectedRestaurant])->fetch();
        $tables = $db->query(
            "SELECT * FROM tables WHERE restaurant_id = ? ORDER BY table_number ASC",
            [$selectedRestaurant]
        )->fetchAll();
    }
}

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

<div class="row mb-4">
    <div class="col-md-6">
        <h4><i class="fas fa-qrcode me-2"></i>QR Code Management</h4>
    </div>
</div>

<div class="form-card mb-4">
    <form method="GET" class="row g-3 align-items-end">
        <div class="col-md-6">
            <label class="form-label">Select Restaurant</label>
            <select name="restaurant_id" class="form-select" id="restaurantSelect">
                <option value="">-- Select Restaurant --</option>
                <?php foreach ($restaurants as $r): ?>
                <option value="<?php echo $r['id']; ?>" <?php echo $selectedRestaurant == $r['id'] ? 'selected' : ''; ?>>
                    <?php echo sanitize($r['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i>Load QR Codes</button>
        </div>
    </form>
</div>

<?php if ($restaurantData): ?>
<div class="row mb-4">
    <div class="col-md-6">
        <div class="form-card">
            <h6 class="text-primary mb-3"><i class="fas fa-store me-1"></i>Restaurant QR Code</h6>
            <div class="text-center mb-3">
                <div id="restaurantQR" style="background:#fff;padding:16px;border:1px solid #ddd;border-radius:8px;display:inline-block;">
                    <img src="<?php echo $baseUrl; ?>/qrcode.php?restaurant_id=<?php echo $selectedRestaurant; ?>&format=png" alt="Restaurant QR Code" style="width:200px;height:200px;">
                </div>
                <div class="mt-2">
                    <small class="text-muted"><?php echo sanitize($restaurantData['name']); ?> - <?php echo $operatingMode == 2 ? 'Scan to Order' : 'Scan to View Menu'; ?></small>
                </div>
            </div>
            <div class="d-flex justify-content-center gap-2">
                <a href="<?php echo $baseUrl; ?>/qrcode.php?restaurant_id=<?php echo $selectedRestaurant; ?>&format=png" class="btn btn-sm btn-primary" download="qr-<?php echo sanitize($restaurantData['slug']); ?>.png">
                    <i class="fas fa-download me-1"></i>Download PNG
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/qr_print.php?restaurant_id=<?php echo $selectedRestaurant; ?>" class="btn btn-sm btn-outline-secondary" target="_blank">
                    <i class="fas fa-print me-1"></i>Print
                </a>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="form-card">
            <h6 class="text-primary mb-3"><i class="fas fa-info-circle me-1"></i>QR Code Details</h6>
            <table class="table table-sm">
                <tr><td><strong>Restaurant:</strong></td><td><?php echo sanitize($restaurantData['name']); ?></td></tr>
                <tr><td><strong>Slug:</strong></td><td><?php echo sanitize($restaurantData['slug']); ?></td></tr>
                <tr><td><strong>Mode:</strong></td><td><?php echo $operatingMode == 2 ? 'Ordering' : 'View Only'; ?></td></tr>
                <tr><td><strong>Menu URL:</strong></td><td><small><?php echo sanitize(getBaseUrl() . '/menu.php?r=' . $restaurantData['slug']); ?></small></td></tr>
                <?php if (!empty($restaurantSettings['wifi_name'])): ?>
                <tr><td><strong>Wi-Fi:</strong></td><td><?php echo sanitize($restaurantSettings['wifi_name']); ?></td></tr>
                <?php endif; ?>
            </table>
        </div>
    </div>
</div>

<div class="form-card mb-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h6 class="text-primary mb-0"><i class="fas fa-chair me-1"></i>Table QR Codes</h6>
        <div>
            <button class="btn btn-sm btn-primary" onclick="batchGenerateQR()">
                <i class="fas fa-sync me-1"></i>Generate All QR Codes
            </button>
            <button class="btn btn-sm btn-outline-secondary" onclick="printAllQR()">
                <i class="fas fa-print me-1"></i>Print All
            </button>
        </div>
    </div>

    <?php if (empty($tables)): ?>
    <div class="text-center text-muted py-4">
        <i class="fas fa-chair" style="font-size:2rem;opacity:0.3;"></i>
        <p class="mt-2">No tables found. Add tables in the restaurant settings first.</p>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-hover">
            <thead class="table-light">
                <tr>
                    <th>Table #</th>
                    <th>Name</th>
                    <th>Capacity</th>
                    <th>Area</th>
                    <th>QR Preview</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tables as $table): ?>
                <tr>
                    <td><strong><?php echo sanitize($table['table_number']); ?></strong></td>
                    <td><?php echo sanitize($table['table_name'] ?? '-'); ?></td>
                    <td><?php echo $table['capacity']; ?> pax</td>
                    <td><?php echo sanitize($table['area'] ?? '-'); ?></td>
                    <td>
                        <img src="<?php echo $baseUrl; ?>/qrcode.php?restaurant_id=<?php echo $selectedRestaurant; ?>&table_id=<?php echo $table['id']; ?>&format=png"
                             alt="QR" style="width:60px;height:60px;border:1px solid #eee;border-radius:4px;">
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?php echo $baseUrl; ?>/qrcode.php?restaurant_id=<?php echo $selectedRestaurant; ?>&table_id=<?php echo $table['id']; ?>&format=png"
                               class="btn btn-outline-primary" download="qr-table-<?php echo sanitize($table['table_number']); ?>.png" title="Download">
                                <i class="fas fa-download"></i>
                            </a>
                            <a href="<?php echo $baseUrl; ?>/admin/qr_print.php?restaurant_id=<?php echo $selectedRestaurant; ?>&table_id=<?php echo $table['id']; ?>"
                               class="btn btn-outline-secondary" target="_blank" title="Print">
                                <i class="fas fa-print"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
function batchGenerateQR() {
    if (!confirm('Generate QR codes for all tables?')) return;
    var btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Generating...';

    var tables = <?php echo json_encode(array_map(function($t) { return ['id' => $t['id'], 'number' => $t['table_number']]; }, $tables)); ?>;
    var generated = 0;

    tables.forEach(function(table) {
        var img = new Image();
        img.onload = function() {
            generated++;
            if (generated === tables.length) {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-check me-1"></i>All Generated';
                setTimeout(function() {
                    btn.innerHTML = '<i class="fas fa-sync me-1"></i>Generate All QR Codes';
                }, 2000);
            }
        };
        img.src = BASE_URL + '/admin/qr_generate.php?restaurant_id=<?php echo $selectedRestaurant; ?>&table_id=' + table.id;
    });
}

function printAllQR() {
    window.open(BASE_URL + '/admin/qr_print.php?restaurant_id=<?php echo $selectedRestaurant; ?>&all=1', '_blank');
}
</script>

<?php else: ?>
<div class="text-center py-5">
    <i class="fas fa-qrcode" style="font-size:4rem;color:var(--gray-300);"></i>
    <h5 class="mt-3 text-muted">Select a restaurant to manage QR codes</h5>
    <p class="text-muted">Choose a restaurant from the dropdown above to view and generate QR codes.</p>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
