<?php
require_once 'config.php';

$pdo = getDBConnection();

// Pegar IDs da URL
$ids = isset($_GET['ids']) ? explode(',', $_GET['ids']) : [];

if (empty($ids)) {
    die("Nenhum QR code selecionado!");
}

// Buscar QR codes
$placeholders = str_repeat('?,', count($ids) - 1) . '?';
$stmt = $pdo->prepare("SELECT * FROM convidados WHERE id IN ($placeholders) ORDER BY id ASC");
$stmt->execute($ids);
$convidados = $stmt->fetchAll();

if (empty($convidados)) {
    die("Nenhum QR code encontrado!");
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Impressão em Massa - <?= count($convidados) ?> QR Codes</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f6fa;
            padding: 20px;
        }
        
        .header {
            background: linear-gradient(135deg, #0a1465 0%, #081050 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 24px;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            color: white;
            transition: all 0.3s;
        }
        
        .btn-print {
            background: #28a745;
        }
        
        .btn-print:hover {
            background: #218838;
        }
        
        .btn-back {
            background: rgba(255,255,255,0.2);
        }
        
        .btn-back:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .qr-card {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        
        .qr-numero {
            font-size: 24px;
            font-weight: bold;
            color: #0a1465;
            margin-bottom: 15px;
        }
        
        .qr-image-container {
            margin: 15px 0;
            min-height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
        }
        
        .qr-image {
            max-width: 200px;
            width: 100%;
            height: auto;
            display: block;
        }
        
        .qr-nome {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin: 10px 0;
            min-height: 24px;
        }
        
        .qr-nome.disponivel {
            color: #999;
            font-style: italic;
        }
        
        .mesa-badge {
            display: inline-block;
            background: #e7f3ff;
            color: #0a1465;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin: 5px 0;
        }
        
        .qr-evento {
            font-size: 13px;
            color: #666;
            margin-top: 10px;
            font-weight: 500;
        }
        
        .qr-data {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
        
        .qr-local {
            font-size: 12px;
            color: #666;
            margin-top: 3px;
        }
        
        .info-footer {
            text-align: center;
            color: #666;
            font-size: 12px;
            margin-top: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
        
        /* Estilos de impressão */
        @media print {
            body {
                background: white;
                padding: 0;
            }
            
            .header {
                display: none;
            }
            
            .grid-container {
                grid-template-columns: repeat(3, 1fr);
                gap: 15px;
            }
            
            .qr-card {
                border: 2px solid #333;
                page-break-inside: avoid;
                break-inside: avoid;
            }
            
            .info-footer {
                page-break-before: always;
            }
        }
        
        @media print and (max-width: 768px) {
            .grid-container {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Impressão em Massa - <?= count($convidados) ?> QR Codes</h1>
        <div class="btn-group">
            <button onclick="window.print()" class="btn btn-print">Imprimir</button>
            <button onclick="window.close()" class="btn btn-back">← Voltar</button>
        </div>
    </div>
    
    <div class="grid-container">
        <?php foreach ($convidados as $conv): ?>
        <div class="qr-card">
            <div class="qr-numero">#<?= formatarNumero($conv['id']) ?></div>
            
            <div class="qr-image-container">
                <?php if ($conv['qrcode_image'] && file_exists('qrcodes/' . $conv['qrcode_image'])): ?>
                    <img src="qrcodes/<?= htmlspecialchars($conv['qrcode_image']) ?>" 
                         alt="QR Code <?= $conv['id'] ?>" 
                         class="qr-image"
                         onerror="this.parentElement.innerHTML='<div style=\'color:#dc3545;font-size:14px;\'>❌ Imagem não encontrada</div>'">
                <?php else: ?>
                    <div style="color: #dc3545; font-size: 14px;">❌ QR Code não disponível</div>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($conv['nome'])): ?>
                <div class="qr-nome"><?= htmlspecialchars($conv['nome']) ?></div>
                <?php if ($conv['compor_mesa']): ?>
                    <div class="mesa-badge">👥 Mesa</div>
                <?php endif; ?>
            <?php else: ?>
                <div class="qr-nome disponivel">Disponível</div>
            <?php endif; ?>
            
        </div>
        <?php endforeach; ?>
    </div>
    
    <div class="info-footer">
        <strong>Total de QR Codes:</strong> <?= count($convidados) ?> | 
        <strong>Gerado em:</strong> <?= date('d/m/Y às H:i:s') ?>
        <br>
   
    </div>
    
    <script>
        // Verificar se todas as imagens foram carregadas antes de permitir impressão
        window.addEventListener('load', function() {
            console.log('Página carregada - <?= count($convidados) ?> QR codes');
            
            // Verificar imagens
            const images = document.querySelectorAll('.qr-image');
            let loadedCount = 0;
            let errorCount = 0;
            
            images.forEach(img => {
                if (img.complete) {
                    loadedCount++;
                } else {
                    img.addEventListener('load', () => {
                        loadedCount++;
                        console.log('Imagem carregada: ' + loadedCount + '/' + images.length);
                    });
                    img.addEventListener('error', () => {
                        errorCount++;
                        console.error('Erro ao carregar imagem: ' + img.src);
                    });
                }
            });
            
            console.log('Imagens carregadas: ' + loadedCount + '/' + images.length);
            if (errorCount > 0) {
                console.warn('Imagens com erro: ' + errorCount);
            }
        });
        
        // Auto-print ao carregar (opcional - descomente se quiser)
        // window.addEventListener('load', function() {
        //     setTimeout(() => window.print(), 500);
        // });
    </script>
</body>
</html>
