<?php
include 'includes/header.php';
require './assets/qrcode/qrlib.php'; // Biblioteca QR Code

$dbFile = './a/qrcodes.db';
$qrFile = 'assets/qrcodes/qrcode.png';
$jsonFile = 'assets/qrcodes/qrcode.json';

if (!is_dir('assets/qrcodes')) mkdir('assets/qrcodes', 0777, true);

try {
    $db = new PDO('sqlite:' . $dbFile);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("
        CREATE TABLE IF NOT EXISTS qrcodes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            link TEXT NOT NULL,
            texto_superior TEXT,
            texto_inferior TEXT,
            criado_em TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
} catch (Exception $e) {
    die("Erro ao conectar SQLite: " . $e->getMessage());
}

$jsonMessage = '';
$jsonContent = '';

// Limpar tudo
if (isset($_POST['limpar'])) {
    if (file_exists($qrFile)) unlink($qrFile);
    if (file_exists($jsonFile)) unlink($jsonFile);
    $db->exec("DELETE FROM qrcodes");
    echo "<script>alert('Tudo limpo!'); window.location='';</script>";
    exit;
}

// Receber dados do formulário
$link = $_POST['link'] ?? '';
$topText = $_POST['texto_superior'] ?? '';
$bottomText = $_POST['texto_inferior'] ?? '';

// Se submeteu o formulário, gerar QR e JSON
if ($link) {
    QRcode::png($link, $qrFile, 'H', 200, 2);

    // Inserir ou atualizar banco
    $stmt = $db->query("SELECT id FROM qrcodes LIMIT 1");
    $exists = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($exists) {
        $update = $db->prepare("UPDATE qrcodes SET link=?, texto_superior=?, texto_inferior=?, criado_em=CURRENT_TIMESTAMP WHERE id=?");
        $update->execute([$link, $topText, $bottomText, $exists['id']]);
    } else {
        $insert = $db->prepare("INSERT INTO qrcodes (link, texto_superior, texto_inferior) VALUES (?, ?, ?)");
        $insert->execute([$link, $topText, $bottomText]);
    }

    // Gerar JSON
    $jsonData = [
        'texto_superior' => $topText,
        'texto_inferior' => $bottomText,
        'imagem' => $qrFile
    ];
    file_put_contents($jsonFile, json_encode($jsonData, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}

// Agora: **sempre checar se o JSON existe**, para exibir os cards mesmo sem submissão
if (file_exists($jsonFile)) {
    $jsonMessage = true;
    $jsonContent = file_get_contents($jsonFile);
    $currentData = json_decode($jsonContent, true);

    $topText = $currentData['texto_superior'] ?? '';
    $bottomText = $currentData['texto_inferior'] ?? '';
    $qrFile = $currentData['imagem'] ?? $qrFile;
}

// Pegar dados atuais do QR do banco (opcional)
$stmt = $db->query("SELECT * FROM qrcodes LIMIT 1");
$current = $stmt->fetch(PDO::FETCH_ASSOC);
?>


<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerador de QR Code Futurista</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Exo+2:wght@300;400;600&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, #0A0F1C 0%, #141B2D 50%, #0A0F1C 100%);
            font-family: 'Exo 2', sans-serif;
            color: #E0F7FF;
            min-height: 100vh;
            overflow-x: hidden;
        }

        .cyber-grid {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: 
                linear-gradient(rgba(0, 212, 255, 0.05) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 212, 255, 0.05) 1px, transparent 1px);
            background-size: 50px 50px;
            z-index: -1;
        }

        .neon-glow {
            position: fixed;
            width: 300px;
            height: 300px;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 212, 255, 0.15) 0%, rgba(0, 212, 255, 0) 70%);
            filter: blur(40px);
            z-index: -1;
        }

        .glow-1 {
            top: -100px;
            right: -100px;
        }

        .glow-2 {
            bottom: -100px;
            left: -100px;
            background: radial-gradient(circle, rgba(255, 71, 87, 0.15) 0%, rgba(255, 71, 87, 0) 70%);
        }

        .futuristic-container {
            max-width: 850px;
            margin: 40px auto;
            padding: 0 20px;
            position: relative;
            z-index: 1;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
            position: relative;
        }

        .header::after {
            content: '';
            position: absolute;
            bottom: -15px;
            left: 50%;
            transform: translateX(-50%);
            width: 200px;
            height: 3px;
            background: linear-gradient(90deg, transparent, #00D4FF, transparent);
        }

        .futuristic-title {
            font-family: 'Orbitron', sans-serif;
            font-weight: 900;
            font-size: 3.2rem;
            background: linear-gradient(90deg, #00D4FF, #0099FF, #00D4FF);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            text-transform: uppercase;
            letter-spacing: 3px;
            margin-bottom: 10px;
            text-shadow: 0 0 15px rgba(0, 212, 255, 0.5);
            animation: textGlow 3s infinite alternate;
        }

        .subtitle {
            font-size: 1.2rem;
            color: #B0B7C3;
            font-weight: 300;
            letter-spacing: 1px;
        }

        .futuristic-form {
            background: rgba(16, 21, 34, 0.8);
            border: 1px solid rgba(0, 212, 255, 0.3);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 40px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            position: relative;
            overflow: hidden;
        }

        .futuristic-form::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #00D4FF, #0099FF, #00D4FF);
        }

        .input-group {
            margin-bottom: 25px;
            position: relative;
        }

        .input-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #00D4FF;
            font-size: 1rem;
            letter-spacing: 1px;
        }

        .input-field {
            width: 100%;
            padding: 16px 20px;
            background: rgba(26, 31, 44, 0.9);
            border: 1px solid rgba(0, 212, 255, 0.2);
            border-radius: 12px;
            color: #E0F7FF;
            font-size: 1rem;
            font-family: 'Exo 2', sans-serif;
            transition: all 0.3s ease;
        }

        .input-field:focus {
            outline: none;
            border-color: #00D4FF;
            box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.2);
            background: rgba(26, 31, 44, 1);
        }

        .input-field::placeholder {
            color: rgba(176, 183, 195, 0.6);
        }

        .input-icon {
            position: absolute;
            right: 20px;
            top: 45px;
            color: #00D4FF;
            font-size: 1.1rem;
        }

        .button-group {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .futuristic-btn {
            flex: 1;
            padding: 18px 25px;
            border: none;
            border-radius: 12px;
            font-weight: 700;
            cursor: pointer;
            font-size: 1.1rem;
            letter-spacing: 1px;
            font-family: 'Exo 2', sans-serif;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            position: relative;
            overflow: hidden;
        }

        .futuristic-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.7s;
        }

        .futuristic-btn:hover::before {
            left: 100%;
        }

        .futuristic-btn-primary {
            background: linear-gradient(135deg, #00D4FF, #0099FF);
            color: #000;
        }

        .futuristic-btn-primary:hover {
            background: linear-gradient(135deg, #00C4FF, #0088FF);
            transform: translateY(-3px);
            box-shadow: 0 7px 20px rgba(0, 212, 255, 0.4);
        }

        .futuristic-btn-danger {
            background: linear-gradient(135deg, #FF4757, #FF3742);
            color: #fff;
        }

        .futuristic-btn-danger:hover {
            background: linear-gradient(135deg, #FF3742, #FF1E2D);
            transform: translateY(-3px);
            box-shadow: 0 7px 20px rgba(255, 71, 87, 0.4);
        }

        .qr-section {
            margin-top: 40px;
        }

        .section-title {
            font-family: 'Orbitron', sans-serif;
            font-size: 1.8rem;
            color: #00D4FF;
            margin-bottom: 25px;
            text-align: center;
            letter-spacing: 2px;
        }

        .futuristic-qr-preview {
            background: rgba(16, 21, 34, 0.8);
            border: 1px solid rgba(0, 212, 255, 0.3);
            border-radius: 20px;
            padding: 30px;
            margin: 0 auto;
            max-width: 500px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            position: relative;
            overflow: hidden;
        }

        .futuristic-qr-preview::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #00D4FF, #0099FF, #00D4FF);
        }

        .qr-container {
            position: relative;
            margin: 20px 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 250px;
        }

        .futuristic-qr-image {
            width: 220px;
            height: 220px;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.5);
            animation: pulse 2s infinite alternate;
            border: 1px solid rgba(0, 212, 255, 0.3);
        }

        .qr-text {
            font-weight: 600;
            font-size: 1.3rem;
            color: #E0F7FF;
            padding: 12px 20px;
            background: rgba(26, 31, 44, 0.7);
            border-radius: 10px;
            margin: 15px 0;
            letter-spacing: 1px;
            border-left: 4px solid #00D4FF;
        }

        .qr-text-top {
            border-left-color: #00D4FF;
        }

        .qr-text-bottom {
            border-left-color: #FF4757;
        }

        .json-section {
            margin-top: 40px;
        }

        .futuristic-card {
            background: rgba(16, 21, 34, 0.8);
            border: 1px solid rgba(0, 212, 255, 0.3);
            border-radius: 20px;
            overflow: hidden;
            margin-top: 20px;
            transition: all 0.3s ease;
            cursor: pointer;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
        }

        .futuristic-card:hover {
            border-color: #00D4FF;
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0, 212, 255, 0.2);
        }

        .futuristic-card-header {
            background: rgba(0, 212, 255, 0.1);
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid rgba(0, 212, 255, 0.2);
        }

        .futuristic-card-title {
            font-family: 'Orbitron', sans-serif;
            font-size: 1.5rem;
            color: #00D4FF;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .futuristic-card-body {
            padding: 20px;
            font-size: 1rem;
            color: #B0B7C3;
        }

        .json-path {
            background: rgba(26, 31, 44, 0.7);
            padding: 12px;
            border-radius: 10px;
            margin-top: 10px;
            font-family: monospace;
            word-break: break-all;
            border-left: 4px solid #00D4FF;
        }

        .json-content-container {
            background: rgba(10, 15, 28, 0.9);
            padding: 20px;
            border-radius: 12px;
            margin-top: 15px;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            color: #00FFAA;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid rgba(0, 212, 255, 0.2);
            text-align: left;
        }

        .pulse-dot {
            display: inline-block;
            width: 10px;
            height: 10px;
            background: #00FF00;
            border-radius: 50%;
            margin-right: 10px;
            animation: pulseDot 1.5s infinite;
        }

        .footer {
            text-align: center;
            margin-top: 60px;
            padding: 20px;
            color: #B0B7C3;
            font-size: 0.9rem;
            letter-spacing: 1px;
            border-top: 1px solid rgba(0, 212, 255, 0.1);
        }

        /* Animações */
        @keyframes textGlow {
            0% { text-shadow: 0 0 15px rgba(0, 212, 255, 0.5); }
            100% { text-shadow: 0 0 25px rgba(0, 212, 255, 0.8), 0 0 35px rgba(0, 212, 255, 0.6); }
        }

        @keyframes pulse {
            0% { transform: scale(1); box-shadow: 0 5px 20px rgba(0, 0, 0, 0.5); }
            100% { transform: scale(1.02); box-shadow: 0 8px 25px rgba(0, 212, 255, 0.3); }
        }

        @keyframes pulseDot {
            0% { opacity: 0.5; transform: scale(1); }
            50% { opacity: 1; transform: scale(1.2); }
            100% { opacity: 0.5; transform: scale(1); }
        }

        /* Responsividade */
        @media (max-width: 768px) {
            .futuristic-title {
                font-size: 2.5rem;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .futuristic-qr-image {
                width: 200px;
                height: 200px;
            }
            
            .futuristic-form, .futuristic-qr-preview, .futuristic-card {
                padding: 20px;
            }
        }

        @media (max-width: 480px) {
            .futuristic-title {
                font-size: 2rem;
            }
            
            .futuristic-container {
                padding: 0 15px;
            }
            
            .input-field {
                padding: 14px 16px;
            }
        }
    </style>
</head>
<body>
    <div class="cyber-grid"></div>
    <div class="neon-glow glow-1"></div>
    <div class="neon-glow glow-2"></div>
    
    <div class="futuristic-container">
        <div class="header">
            <h1 class="futuristic-title">Gerador de QR Code</h1>
            <p class="subtitle">Crie QR codes personalizados COM A CARA DO ULISSES</p>
        </div>

        <form method="post" class="futuristic-form">
            <div class="input-group">
                <label class="input-label" for="texto_superior"><i class="fas fa-text-height"></i> TEXTO SUPERIOR</label>
                <input type="text" id="texto_superior" name="texto_superior" placeholder="Digite o texto que aparecerá acima do QR Code" class="input-field" value="<?= htmlspecialchars($topText) ?>">
                <div class="input-icon"><i class="fas fa-arrow-up"></i></div>
            </div>
            
            <div class="input-group">
                <label class="input-label" for="texto_inferior"><i class="fas fa-text-height"></i> TEXTO INFERIOR</label>
                <input type="text" id="texto_inferior" name="texto_inferior" placeholder="Digite o texto que aparecerá abaixo do QR Code" class="input-field" value="<?= htmlspecialchars($bottomText) ?>">
                <div class="input-icon"><i class="fas fa-arrow-down"></i></div>
            </div>
            
            <div class="input-group">
                <label class="input-label" for="link"><i class="fas fa-link"></i> LINK DO PAGAMENTO</label>
                <input type="url" id="link" name="link" placeholder="https://exemplo.com/pagamento" class="input-field" value="<?= htmlspecialchars($link) ?>" required>
                <div class="input-icon"><i class="fas fa-external-link-alt"></i></div>
            </div>
            
            <div class="button-group">
                <button type="submit" class="futuristic-btn futuristic-btn-primary">
                    <i class="fas fa-qrcode"></i> GERAR QR CODE
                </button>
                <button type="submit" name="limpar" class="futuristic-btn futuristic-btn-danger">
                    <i class="fas fa-eraser"></i> LIMPAR TUDO
                </button>
            </div>
        </form>

        <?php if ($link): ?>
        <div class="qr-section">
            <h2 class="section-title">PRÉVIA DO QR CODE</h2>
            <div class="futuristic-qr-preview">
                <?php if($topText): ?>
                    <div class="qr-text qr-text-top"><?= htmlspecialchars($topText) ?></div>
                <?php endif; ?>
                
                <div class="qr-container">
                    <img src="<?= $qrFile ?>" alt="QR Code" class="futuristic-qr-image">
                </div>
                
                <?php if($bottomText): ?>
                    <div class="qr-text qr-text-bottom"><?= htmlspecialchars($bottomText) ?></div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($jsonMessage): ?>
        <div class="json-section">
            <h2 class="section-title">INFORMAÇÕES DO JSON</h2>
            
            <div class="futuristic-card" id="jsonCard">
                <div class="futuristic-card-header">
                    <h2 class="futuristic-card-title">
                        <i class="fas fa-file-code"></i> JSON ATIVO
                        <span class="pulse-dot"></span>
                        <span style="color: #00FF00; font-size: 1rem;">ONLINE</span>
                    </h2>
                    <i class="fas fa-chevron-down" id="jsonToggleIcon"></i>
                </div>
                <div class="futuristic-card-body">
                    <p>Local do arquivo JSON:</p>
                    <div class="json-path"><?= $jsonFile ?></div>
                </div>
            </div>

            <div class="json-content-container" id="jsonContentContainer" style="display:none;">
                <?= htmlspecialchars($jsonContent) ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="footer">
            <p><i class="fas fa-code"></i> Desenvolvido Por eonbry 💻| <?= date('Y') ?></p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const jsonCard = document.getElementById('jsonCard');
            const jsonContainer = document.getElementById('jsonContentContainer');
            const jsonToggleIcon = document.getElementById('jsonToggleIcon');
            
            if(jsonCard) {
                jsonCard.addEventListener('click', function() {
                    if(jsonContainer.style.display === 'none') {
                        jsonContainer.style.display = 'block';
                        jsonToggleIcon.className = 'fas fa-chevron-up';
                        jsonContainer.scrollIntoView({ behavior: 'smooth' });
                    } else {
                        jsonContainer.style.display = 'none';
                        jsonToggleIcon.className = 'fas fa-chevron-down';
                    }
                });
            }
            
            // Efeito de digitação nos campos
            const inputs = document.querySelectorAll('.input-field');
            inputs.forEach(input => {
                input.addEventListener('focus', function() {
                    this.parentElement.style.transform = 'translateY(-5px)';
                });
                
                input.addEventListener('blur', function() {
                    this.parentElement.style.transform = 'translateY(0)';
                });
            });
            
            // Efeito de foco nos botões
            const buttons = document.querySelectorAll('.futuristic-btn');
            buttons.forEach(button => {
                button.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-3px)';
                });
                
                button.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0)';
                });
            });
            
            // Animação de partículas no fundo
            createParticles();
        });
        
        function createParticles() {
            const container = document.querySelector('.cyber-grid');
            for(let i = 0; i < 15; i++) {
                const particle = document.createElement('div');
                particle.style.position = 'fixed';
                particle.style.width = Math.random() * 4 + 1 + 'px';
                particle.style.height = particle.style.width;
                particle.style.background = `rgba(0, 212, 255, ${Math.random() * 0.5 + 0.1})`;
                particle.style.borderRadius = '50%';
                particle.style.top = Math.random() * 100 + 'vh';
                particle.style.left = Math.random() * 100 + 'vw';
                particle.style.zIndex = '-1';
                particle.style.boxShadow = '0 0 10px rgba(0, 212, 255, 0.8)';
                
                // Animação
                const duration = Math.random() * 20 + 10;
                const delay = Math.random() * 5;
                particle.style.animation = `moveParticle ${duration}s linear ${delay}s infinite`;
                
                // Adicionar keyframes dinamicamente
                if (!document.getElementById('particleKeyframes')) {
                    const style = document.createElement('style');
                    style.id = 'particleKeyframes';
                    style.innerHTML = `
                        @keyframes moveParticle {
                            0% { transform: translateY(0) translateX(0); opacity: 0; }
                            10% { opacity: 1; }
                            90% { opacity: 1; }
                            100% { transform: translateY(${Math.random() * -100 - 50}vh) translateX(${Math.random() * 100 - 50}vw); opacity: 0; }
                        }
                    `;
                    document.head.appendChild(style);
                }
                
                document.body.appendChild(particle);
            }
        }
    </script>
</body>
</html>