<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


include 'includes/header.php';

$file_path = 'a/qrcode.json';

// INICIALIZAR variáveis primeiro
$texto_inferior = '';
$texto_superior = '';
$imagem = '';

// PRIMEIRO: Processar o POST (se existir)
if (isset($_POST['texto_superior'])) {
    $new_data = [
        'texto_inferior' => $_POST['texto_inferior'], 
        'texto_superior' => $_POST['texto_superior'], 
        'imagem' => $_POST['imagem']
    ];
    
    // Carregar dados existentes
    if (file_exists($file_path)) {
        $file_content = file_get_contents($file_path);
        $data_array = json_decode($file_content, true);
    } else {
        $data_array = [];
    }
    
    // Mesclar e salvar
    $merged_data = array_replace_recursive($data_array, $new_data);
    $updated_content = json_encode($merged_data, JSON_UNESCAPED_UNICODE);
    file_put_contents($file_path, $updated_content);
    
    // USAR OS NOVOS DADOS SALVOS no formulário
    $texto_inferior = $_POST['texto_inferior'];
    $texto_superior = $_POST['texto_superior'];
    $imagem = $_POST['imagem'];
    
    echo "<script>
        Swal.fire({
            icon: 'success',
            title: 'Sucesso!',
            text: 'QR Code e textos atualizados com sucesso!',
            timer: 2000,
            showConfirmButton: false
        });
        // Recarregar a página após 2 segundos
        setTimeout(function() {
            window.location.reload();
        }, 2000);
    </script>";
} 
// SEGUNDO: Se não houve POST, carregar do JSON
else {
    if (file_exists($file_path)) {
        $file_content = file_get_contents($file_path);
        $data_array = json_decode($file_content, true);
        
        $texto_inferior = $data_array['texto_inferior'] ?? '';
        $texto_superior = $data_array['texto_superior'] ?? '';
        $imagem = $data_array['imagem'] ?? '';
    }
}
?>
<style>
/* Estilos futuristas para QR Code */
:root {
    --primary: #00D4FF;
    --primary-dark: #0099CC;
    --secondary: #FF6B9D;
    --accent: #00FF88;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(0, 212, 255, 0.3);
    --glow-accent: 0 0 20px rgba(0, 255, 136, 0.3);
    --error: #FF4757;
    --success: #00D084;
}

.futuristic-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.futuristic-title {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 10px;
    text-align: center;
    text-shadow: 0 0 10px rgba(0, 212, 255, 0.3);
    letter-spacing: 1px;
}

.futuristic-subtitle {
    color: var(--text-secondary);
    font-size: 16px;
    text-align: center;
    margin-bottom: 30px;
    font-weight: 400;
}

.futuristic-card {
    background: rgba(26, 31, 44, 0.9);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    border: 1px solid var(--border);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    margin-bottom: 30px;
    transition: all 0.3s ease;
}

.futuristic-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0, 212, 255, 0.2);
    border-color: var(--primary);
}

.futuristic-card-header {
    background: linear-gradient(135deg, rgba(26, 31, 44, 0.9), rgba(42, 47, 60, 0.9));
    padding: 25px 30px;
    border-bottom: 1px solid var(--border);
    position: relative;
    overflow: hidden;
}

.futuristic-card-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, var(--primary), transparent);
}

.futuristic-card-title {
    color: var(--text-primary);
    font-size: 20px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 15px;
}

.futuristic-card-title i {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 24px;
}

.futuristic-card-body {
    padding: 30px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 40px;
}

@media (max-width: 992px) {
    .futuristic-card-body {
        grid-template-columns: 1fr;
        gap: 30px;
    }
}

/* Formulário Futurista */
.futuristic-form {
    max-width: 100%;
}

.futuristic-form-group {
    margin-bottom: 25px;
    animation: slideInUp 0.5s ease forwards;
    animation-delay: calc(var(--item-index, 0) * 0.1s);
    opacity: 0;
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.futuristic-label {
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--text-primary);
    font-weight: 500;
    margin-bottom: 10px;
    font-size: 14px;
    letter-spacing: 0.5px;
}

.futuristic-label i {
    color: var(--primary);
    font-size: 16px;
    width: 20px;
    text-align: center;
}

.futuristic-label span {
    font-weight: 600;
    color: var(--accent);
}

.futuristic-input-group {
    position: relative;
}

.futuristic-input {
    width: 100%;
    padding: 16px 20px 16px 50px;
    background: rgba(10, 15, 28, 0.6);
    border: 1px solid var(--border);
    border-radius: 12px;
    color: var(--text-primary);
    font-size: 14px;
    transition: all 0.3s ease;
    outline: none;
}

.futuristic-input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 212, 255, 0.1);
    background: rgba(10, 15, 28, 0.8);
}

.futuristic-input::placeholder {
    color: var(--text-muted);
}

.futuristic-input-icon {
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-muted);
    font-size: 16px;
    z-index: 2;
    transition: color 0.3s ease;
}

.futuristic-input:focus + .futuristic-input-icon {
    color: var(--primary);
}

.futuristic-input-hint {
    display: block;
    color: var(--text-muted);
    font-size: 11px;
    margin-top: 6px;
    font-style: italic;
}

.futuristic-btn {
    padding: 16px 35px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 12px;
    text-decoration: none;
    border: none;
    min-width: 180px;
    justify-content: center;
}

.futuristic-btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    box-shadow: var(--glow);
}

.futuristic-btn-primary:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(0, 212, 255, 0.4);
    background: linear-gradient(135deg, var(--primary-dark), var(--primary));
}

.futuristic-btn-primary i {
    font-size: 18px;
}

/* Preview QR Code */
.futuristic-qr-preview {
    background: rgba(10, 15, 28, 0.4);
    border-radius: 20px;
    padding: 30px;
    border: 1px solid var(--border);
    text-align: center;
    position: relative;
    overflow: hidden;
}

.futuristic-qr-preview::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, var(--accent), transparent);
}

.futuristic-qr-badge {
    position: absolute;
    top: 15px;
    right: 15px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    box-shadow: var(--glow);
    z-index: 2;
}

.futuristic-qr-title {
    color: var(--accent);
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.futuristic-qr-display {
    margin: 20px 0;
    padding: 20px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 15px;
    border: 2px dashed var(--border);
    min-height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.futuristic-qr-display:hover {
    border-color: var(--primary);
    background: rgba(0, 212, 255, 0.05);
}

.futuristic-qr-image {
    max-width: 200px;
    max-height: 200px;
    border-radius: 10px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
    transition: all 0.3s ease;
}

.futuristic-qr-image:hover {
    transform: scale(1.05);
    box-shadow: 0 10px 30px rgba(0, 212, 255, 0.3);
}

.futuristic-qr-text {
    margin-top: 25px;
    padding: 20px;
    background: rgba(26, 31, 44, 0.6);
    border-radius: 12px;
    border-left: 3px solid var(--primary);
}

.futuristic-qr-text-top {
    color: var(--text-primary);
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    text-align: center;
}

.futuristic-qr-text-bottom {
    color: var(--text-secondary);
    font-size: 14px;
    text-align: center;
    line-height: 1.5;
}

.futuristic-qr-empty {
    color: var(--text-muted);
    font-size: 14px;
    text-align: center;
    padding: 40px 20px;
}

.futuristic-qr-empty i {
    font-size: 48px;
    margin-bottom: 15px;
    display: block;
    opacity: 0.5;
}

/* URL Preview */
.futuristic-url-preview {
    background: rgba(10, 15, 28, 0.6);
    border-radius: 12px;
    padding: 15px;
    margin-top: 20px;
    border: 1px solid var(--border);
    word-break: break-all;
}

.futuristic-url-label {
    color: var(--text-secondary);
    font-size: 11px;
    font-weight: 600;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.futuristic-url-value {
    color: var(--primary);
    font-size: 12px;
    font-family: 'Courier New', monospace;
}

/* Responsividade */
@media (max-width: 768px) {
    .futuristic-container {
        padding: 15px;
    }
    
    .futuristic-title {
        font-size: 28px;
    }
    
    .futuristic-subtitle {
        font-size: 14px;
    }
    
    .futuristic-card-body {
        padding: 20px;
        gap: 25px;
    }
    
    .futuristic-card-header {
        padding: 20px;
    }
    
    .futuristic-card-title {
        font-size: 18px;
    }
    
    .futuristic-input {
        padding: 14px 18px 14px 48px;
        font-size: 13px;
    }
    
    .futuristic-btn {
        width: 100%;
        padding: 14px 25px;
    }
    
    .futuristic-qr-preview {
        padding: 20px;
    }
    
    .futuristic-qr-image {
        max-width: 150px;
        max-height: 150px;
    }
}

@media (max-width: 480px) {
    .futuristic-container {
        padding: 10px;
    }
    
    .futuristic-title {
        font-size: 24px;
    }
    
    .futuristic-card-body {
        padding: 15px;
        gap: 20px;
    }
    
    .futuristic-card-header {
        padding: 15px;
    }
    
    .futuristic-input {
        padding: 12px 16px 12px 46px;
        font-size: 12px;
    }
    
    .futuristic-btn {
        padding: 12px 20px;
        font-size: 14px;
    }
    
    .futuristic-qr-preview {
        padding: 15px;
    }
}

/* Character Counter */
.futuristic-char-counter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 5px;
    font-size: 11px;
    color: var(--text-muted);
}

.futuristic-char-count {
    font-weight: 600;
}

.futuristic-char-count.warning {
    color: var(--secondary);
}

.futuristic-char-count.danger {
    color: var(--error);
}

/* QR Code Animation */
@keyframes qrPulse {
    0%, 100% { 
        box-shadow: 0 0 0 0 rgba(0, 212, 255, 0.4);
    }
    70% { 
        box-shadow: 0 0 0 10px rgba(0, 212, 255, 0);
    }
}

.futuristic-qr-animated {
    animation: qrPulse 2s infinite;
    border-radius: 15px;
    padding: 10px;
}

/* URL Validation */
.futuristic-url-valid {
    color: var(--accent);
}

.futuristic-url-invalid {
    color: var(--error);
}

/* Preview Loading */
.futuristic-qr-loading {
    display: inline-block;
    width: 50px;
    height: 50px;
    border: 3px solid rgba(0, 212, 255, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary);
    animation: spin 1s ease-in-out infinite;
    margin: 20px auto;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<div class="futuristic-container">
    <h1 class="futuristic-title">QR Code e Texto</h1>
    <p class="futuristic-subtitle">Configure o QR Code e textos exibidos para os usuários</p>
    
    <div class="futuristic-card">
        <div class="futuristic-card-header">
            <h2 class="futuristic-card-title">
                <i class="fas fa-qrcode"></i>
                Configuração de QR Code
            </h2>
        </div>
        
        <div class="futuristic-card-body">
            <!-- Formulário -->
            <div class="futuristic-form-container">
                <form method="post" id="qrcodeForm" class="futuristic-form">
                    <div class="futuristic-form-group" style="--item-index: 0">
                        <label class="futuristic-label">
                            <i class="fas fa-arrow-up"></i>
                            <span>Texto Superior</span>
                        </label>
                        <div class="futuristic-input-group">
                            <i class="fas fa-heading futuristic-input-icon"></i>
                            <input type="text" class="futuristic-input" id="texto_superior" name="texto_superior" 
                                   placeholder="Digite o texto que aparecerá acima do QR Code" 
                                   value="<?php echo htmlspecialchars($texto_superior); ?>" 
                                   maxlength="200">
                        </div>
                        <div class="futuristic-char-counter">
                            <span>Máximo: 200 caracteres</span>
                            <span class="futuristic-char-count" id="superiorCounter">
                                <?php echo strlen($texto_superior); ?>/200
                            </span>
                        </div>
                    </div>
                    
                    <div class="futuristic-form-group" style="--item-index: 1">
                        <label class="futuristic-label">
                            <i class="fas fa-arrow-down"></i>
                            <span>Texto Inferior</span>
                        </label>
                        <div class="futuristic-input-group">
                            <i class="fas fa-align-center futuristic-input-icon"></i>
                            <input type="text" class="futuristic-input" id="texto_inferior" name="texto_inferior" 
                                   placeholder="Digite o texto que aparecerá abaixo do QR Code" 
                                   value="<?php echo htmlspecialchars($texto_inferior); ?>" 
                                   maxlength="200">
                        </div>
                        <div class="futuristic-char-counter">
                            <span>Máximo: 200 caracteres</span>
                            <span class="futuristic-char-count" id="inferiorCounter">
                                <?php echo strlen($texto_inferior); ?>/200
                            </span>
                        </div>
                    </div>
                    
                    <div class="futuristic-form-group" style="--item-index: 2">
                        <label class="futuristic-label">
                            <i class="fas fa-link"></i>
                            <span>URL da Imagem (QR Code)</span>
                        </label>
                        <div class="futuristic-input-group">
                            <i class="fas fa-image futuristic-input-icon"></i>
                            <input type="text" class="futuristic-input" id="imagem" name="imagem" 
                                   placeholder="Cole aqui a URL da imagem do QR Code" 
                                   value="<?php echo htmlspecialchars($imagem); ?>">
                        </div>
                        <span class="futuristic-input-hint">
                            <i class="fas fa-info-circle"></i> URL da imagem (PNG, JPG, GIF, SVG)
                        </span>
                    </div>
                    
                    <div class="futuristic-url-preview" id="urlPreview" style="display: <?php echo !empty($imagem) ? 'block' : 'none'; ?>;">
                        <div class="futuristic-url-label">
                            <i class="fas fa-external-link-alt"></i>
                            URL Atual:
                        </div>
                        <div class="futuristic-url-value" id="currentUrl">
                            <?php echo htmlspecialchars($imagem); ?>
                        </div>
                    </div>
                    
                    <div style="margin-top: 30px;">
                        <button type="submit" name="text" class="futuristic-btn futuristic-btn-primary" id="submitBtn">
                            <i class="fas fa-sync-alt"></i>
                            <span>Atualizar QR Code</span>
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Preview -->
            <div class="futuristic-qr-preview">
                <span class="futuristic-qr-badge">PREVIEW</span>
                <div class="futuristic-qr-title">
                    <i class="fas fa-eye"></i>
                    Visualização
                </div>
                
                <div class="futuristic-qr-display" id="qrDisplay">
                    <?php if (!empty($imagem)): ?>
                        <img src="<?php echo htmlspecialchars($imagem); ?>" 
                             alt="QR Code" 
                             class="futuristic-qr-image futuristic-qr-animated"
                             onerror="this.onerror=null; this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iIzBBMEYxQyIvPjx0ZXh0IHg9IjEwMCIgeT0iMTAwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTQiIGZpbGw9IiM3MThBQzIiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5RUiBDb2RlPC90ZXh0Pjx0ZXh0IHg9IjEwMCIgeT0iMTIwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTIiIGZpbGw9IiM2QjcyODAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5VUkwgSW52w6FsaWRhPC90ZXh0Pjwvc3ZnPg=='">
                    <?php else: ?>
                        <div class="futuristic-qr-empty">
                            <i class="fas fa-qrcode"></i>
                            <p>Nenhuma imagem configurada</p>
                            <p style="font-size: 12px; margin-top: 10px;">
                                Insira uma URL de imagem acima para visualizar
                            </p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($texto_superior) || !empty($texto_inferior)): ?>
                    <div class="futuristic-qr-text">
                        <?php if (!empty($texto_superior)): ?>
                            <div class="futuristic-qr-text-top" id="previewSuperior">
                                <?php echo htmlspecialchars($texto_superior); ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($texto_inferior)): ?>
                            <div class="futuristic-qr-text-bottom" id="previewInferior">
                                <?php echo htmlspecialchars($texto_inferior); ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Cards de Informações -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-top: 30px;">
        <div class="futuristic-card" style="margin: 0;">
            <div class="futuristic-card-header">
                <h2 class="futuristic-card-title" style="font-size: 16px;">
                    <i class="fas fa-info-circle"></i>
                    Dicas de Uso
                </h2>
            </div>
            <div style="padding: 20px; color: var(--text-secondary); font-size: 13px; line-height: 1.5;">
                <p><strong>Texto Superior:</strong> Use para títulos ou instruções importantes.</p>
                <p><strong>Texto Inferior:</strong> Use para descrições ou chamadas para ação.</p>
                <p><strong>URL da Imagem:</strong> Certifique-se de que a URL esteja acessível publicamente.</p>
                <p><strong>Formato:</strong> PNG, JPG ou SVG recomendados.</p>
            </div>
        </div>
        
        <div class="futuristic-card" style="margin: 0;">
            <div class="futuristic-card-header">
                <h2 class="futuristic-card-title" style="font-size: 16px;">
                    <i class="fas fa-database"></i>
                    Status do JSON
                </h2>
            </div>
            <div style="padding: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <span style="color: var(--text-secondary); font-size: 13px;">Última Atualização:</span>
                    <span style="color: var(--primary); font-size: 13px; font-weight: 600;">
                        <?php 
                            if (file_exists($file_path)) {
                                echo date('d/m H:i', filemtime($file_path));
                            } else {
                                echo 'Nunca';
                            }
                        ?>
                    </span>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: var(--text-secondary); font-size: 13px;">Status do Arquivo:</span>
                    <span id="jsonStatus" style="color: <?php echo (json_last_error() === JSON_ERROR_NONE) ? 'var(--accent)' : 'var(--error)'; ?>; 
                          font-size: 13px; font-weight: 600;">
                        <?php echo (json_last_error() === JSON_ERROR_NONE) ? '✓ Válido' : '✗ Inválido'; ?>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Elementos
    const form = document.getElementById('qrcodeForm');
    const superiorInput = document.getElementById('texto_superior');
    const inferiorInput = document.getElementById('texto_inferior');
    const imagemInput = document.getElementById('imagem');
    const superiorCounter = document.getElementById('superiorCounter');
    const inferiorCounter = document.getElementById('inferiorCounter');
    const submitBtn = document.getElementById('submitBtn');
    const urlPreview = document.getElementById('urlPreview');
    const currentUrl = document.getElementById('currentUrl');
    const previewSuperior = document.getElementById('previewSuperior');
    const previewInferior = document.getElementById('previewInferior');
    const qrDisplay = document.getElementById('qrDisplay');
    
    // Atualizar contadores de caracteres
    function updateCharCounters() {
        const superiorLength = superiorInput.value.length;
        const inferiorLength = inferiorInput.value.length;
        
        // Atualizar contadores
        superiorCounter.textContent = `${superiorLength}/200`;
        inferiorCounter.textContent = `${inferiorLength}/200`;
        
        // Estilizar baseado no limite
        superiorCounter.className = 'futuristic-char-count';
        inferiorCounter.className = 'futuristic-char-count';
        
        if (superiorLength > 180) {
            superiorCounter.classList.add('warning');
        }
        if (superiorLength > 195) {
            superiorCounter.classList.add('danger');
        }
        
        if (inferiorLength > 180) {
            inferiorCounter.classList.add('warning');
        }
        if (inferiorLength > 195) {
            inferiorCounter.classList.add('danger');
        }
        
        // Atualizar preview de textos
        if (previewSuperior) {
            previewSuperior.textContent = superiorInput.value || '';
            previewSuperior.style.display = superiorInput.value ? 'block' : 'none';
        }
        
        if (previewInferior) {
            previewInferior.textContent = inferiorInput.value || '';
            previewInferior.style.display = inferiorInput.value ? 'block' : 'none';
        }
    }
    
    // Atualizar preview da imagem
    function updateImagePreview() {
        const url = imagemInput.value.trim();
        
        // Mostrar/ocultar preview da URL
        if (url) {
            urlPreview.style.display = 'block';
            currentUrl.textContent = url;
            
            // Atualizar imagem do QR Code
            const qrImage = qrDisplay.querySelector('img');
            if (qrImage) {
                qrImage.src = url;
            } else {
                // Criar nova imagem
                const newImg = document.createElement('img');
                newImg.src = url;
                newImg.alt = 'QR Code';
                newImg.className = 'futuristic-qr-image futuristic-qr-animated';
                newImg.onerror = function() {
                    this.onerror = null;
                    this.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iIzBBMEYxQyIvPjx0ZXh0IHg9IjEwMCIgeT0iMTAwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTQiIGZpbGw9IiM3MThBQzIiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5RUiBDb2RlPC90ZXh0Pjx0ZXh0IHg9IjEwMCIgeT0iMTIwIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTIiIGZpbGw9IiM2QjcyODAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5VUkwgSW52w6FsaWRhPC90ZXh0Pjwvc3ZnPg==';
                };
                
                qrDisplay.innerHTML = '';
                qrDisplay.appendChild(newImg);
            }
        } else {
            urlPreview.style.display = 'none';
            currentUrl.textContent = '';
            
            // Mostrar estado vazio
            qrDisplay.innerHTML = `
                <div class="futuristic-qr-empty">
                    <i class="fas fa-qrcode"></i>
                    <p>Nenhuma imagem configurada</p>
                    <p style="font-size: 12px; margin-top: 10px;">
                        Insira uma URL de imagem acima para visualizar
                    </p>
                </div>
            `;
        }
    }
    
    // Validar URL
    function isValidUrl(string) {
        try {
            new URL(string);
            return true;
        } catch (_) {
            return false;
        }
    }
    
    // Validar formulário
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const superior = superiorInput.value.trim();
        const inferior = inferiorInput.value.trim();
        const imagem = imagemInput.value.trim();
        
        let isValid = true;
        const errors = [];
        
        // Validar textos (opcionais, mas com limite)
        if (superior.length > 200) {
            errors.push('Texto superior não pode ter mais de 200 caracteres');
            isValid = false;
        }
        
        if (inferior.length > 200) {
            errors.push('Texto inferior não pode ter mais de 200 caracteres');
            isValid = false;
        }
        
        // Validar URL (opcional, mas se fornecida, deve ser válida)
        if (imagem && !isValidUrl(imagem)) {
            errors.push('URL da imagem inválida');
            isValid = false;
        }
        
        if (!isValid) {
            Swal.fire({
                icon: 'error',
                title: 'Erro de Validação',
                html: '<div style="text-align: left;">' + 
                      errors.map(error => `<p>• ${error}</p>`).join('') + 
                      '</div>',
                confirmButtonColor: '#00D4FF'
            });
            return;
        }
        
        // Mostrar loading
        const originalContent = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Atualizando...';
        submitBtn.disabled = true;
        
        // Simular delay para efeito visual
        setTimeout(() => {
            // Se tudo estiver OK, enviar formulário
            form.submit();
        }, 1000);
    });
    
    // Inicializar contadores
    updateCharCounters();
    updateImagePreview();
    
    // Atualizar em tempo real
    superiorInput.addEventListener('input', updateCharCounters);
    inferiorInput.addEventListener('input', updateCharCounters);
    imagemInput.addEventListener('input', updateImagePreview);
    
    // Efeitos visuais nos inputs
    const inputs = [superiorInput, inferiorInput, imagemInput];
    inputs.forEach(input => {
        // Efeito de foco
        input.addEventListener('focus', function() {
            this.style.borderColor = 'var(--primary)';
            this.style.boxShadow = '0 0 0 2px rgba(0, 212, 255, 0.1)';
        });
        
        input.addEventListener('blur', function() {
            this.style.borderColor = '';
            this.style.boxShadow = '';
        });
        
        // Verificar URL em tempo real
        if (input === imagemInput) {
            input.addEventListener('input', function() {
                const url = this.value.trim();
                if (url && isValidUrl(url)) {
                    this.style.borderColor = 'var(--accent)';
                } else if (url) {
                    this.style.borderColor = 'var(--error)';
                } else {
                    this.style.borderColor = '';
                }
            });
        }
    });
    
    // Auto-focus no primeiro campo
    setTimeout(() => {
        superiorInput.focus();
    }, 300);
    
    // Configurar SweetAlert2
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'QR Code',
            text: 'Configure o QR Code e textos para exibição.',
            icon: 'info',
            timer: 3000,
            showConfirmButton: false,
            toast: true,
            position: 'top-end'
        });
    }
    
    // Verificar status do JSON
    function checkJsonStatus() {
        // Simulação - em produção, poderia fazer uma requisição AJAX
        const currentData = {
            texto_superior: superiorInput.value,
            texto_inferior: inferiorInput.value,
            imagem: imagemInput.value
        };
        
        try {
            const jsonStr = JSON.stringify(currentData);
            JSON.parse(jsonStr);
            document.getElementById('jsonStatus').textContent = '✓ Válido';
            document.getElementById('jsonStatus').style.color = 'var(--accent)';
        } catch (error) {
            document.getElementById('jsonStatus').textContent = '✗ Inválido';
            document.getElementById('jsonStatus').style.color = 'var(--error)';
        }
    }
    
    // Verificar JSON em tempo real
    superiorInput.addEventListener('input', checkJsonStatus);
    inferiorInput.addEventListener('input', checkJsonStatus);
    imagemInput.addEventListener('input', checkJsonStatus);
    
    // Inicializar verificação
    checkJsonStatus();
});
</script>

<?php 
include 'includes/footer.php';
?>
</html>