
<?php
ob_start(); // Inicie o buffer de saída
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
include "includes/header.php";

// Processar upload via arquivo
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
    $fileType = $_FILES["image"]["type"];
    if ($fileType === "image/png") {
        $uploadPath = './api/qr/';
        $fileName = 'qr.png';
        
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $uploadPath . $fileName)) {
            $_SESSION['alert'] = ['type' => 'success', 'message' => 'QR Code enviado com sucesso!'];
        } else {
            $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Falha ao enviar o arquivo.'];
        }
    } else {
        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Apenas arquivos PNG são permitidos.'];
    }
    header("Location: qrcode.php");
    exit;
}

// Processar upload via URL
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["image_url"])) {
    $imageUrl = filter_var($_POST["image_url"], FILTER_VALIDATE_URL);
    
    if ($imageUrl && preg_match('/\.png$/i', $imageUrl)) {
        $uploadPath = './api/qr/qr.png';
        
        // Verificar se a URL é acessível
        $headers = @get_headers($imageUrl);
        if($headers && strpos($headers[0], '200')) {
            $imageData = file_get_contents($imageUrl);
            
            if ($imageData !== false && file_put_contents($uploadPath, $imageData)) {
                $_SESSION['alert'] = ['type' => 'success', 'message' => 'QR Code baixado com sucesso!'];
            } else {
                $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Falha ao baixar a imagem da URL.'];
            }
        } else {
            $_SESSION['alert'] = ['type' => 'danger', 'message' => 'URL inacessível ou inválida.'];
        }
    } else {
        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'URL inválida ou não é uma imagem PNG.'];
    }
    header("Location: qrcode.php");
    exit;
}
?>

<style>
/* Main Colors - Dark Blue Theme (totalmente alinhado com dns.php) */
:root {
    --primary-blue: #1a237e;
    --dark-blue: #0d1541;
    --accent-blue: #3d5afe;
    --light-blue: #e8eaf6;
    --danger-red: #dc3545;
    --success-green: #28a745;
    --warning-orange: #fd7e14;
    --white: #ffffff;
    --light-gray: #f8f9fa;
    --medium-gray: #e9ecef;
    --dark-gray: #6c757d;
    --black: #212529;
}

/* Card Styles - White with Blue Accents */
.card {
    border: none;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    margin-bottom: 25px;
    background-color: var(--white);
    border: 1px solid var(--light-blue);
}

.card-header {
    border-radius: 10px 10px 0 0 !important;
    padding: 18px 25px;
    font-weight: 600;
    color: var(--white);
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%) !important;
}

.card-body {
    padding: 30px;
    background-color: var(--white);
}

/* Form Styles */
.form-control {
    padding: 12px 15px;
    border-radius: 8px;
    border: 1px solid var(--medium-gray);
    transition: all 0.3s;
    background-color: var(--white);
}

.form-control:focus {
    border-color: var(--accent-blue);
    box-shadow: 0 0 0 3px rgba(61, 90, 254, 0.15);
}

.form-label {
    font-weight: 500;
    margin-bottom: 10px;
    color: var(--dark-blue);
    display: block;
}

/* Button Styles */
.btn {
    padding: 12px 24px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.btn-primary {
    background-color: var(--primary-blue);
    border-color: var(--primary-blue);
    color: var(--white);
}

.btn-primary:hover {
    background-color: var(--dark-blue);
    border-color: var(--dark-blue);
}

.btn-success {
    background-color: var(--success-green);
    border-color: var(--success-green);
    color: var(--white);
}

.btn-success:hover {
    background-color: #218838;
    border-color: #1e7e34;
}

/* QR Code Preview Section */
.qr-current-section {
    background-color: var(--light-blue);
    border-radius: 10px;
    padding: 25px;
    margin-bottom: 30px;
    text-align: center;
    border: 1px solid var(--accent-blue);
}

.qr-preview {
    max-width: 250px;
    max-height: 250px;
    border-radius: 10px;
    border: 1px solid var(--medium-gray);
    margin: 0 auto 20px;
    display: block;
    box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.qr-section {
    margin-bottom: 35px;
    padding-bottom: 35px;
    border-bottom: 1px solid var(--medium-gray);
}

.qr-section:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.section-title {
    color: var(--primary-blue);
    margin-bottom: 25px;
    font-size: 1.2rem;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.section-title i {
    margin-right: 12px;
    font-size: 1.3rem;
    color: var(--accent-blue);
}

.upload-method {
    display: flex;
    gap: 20px;
    margin-bottom: 25px;
}

.upload-method-btn {
    flex: 1;
    padding: 15px;
    border-radius: 8px;
    background: var(--light-gray);
    border: 1px solid var(--medium-gray);
    cursor: pointer;
    transition: all 0.3s;
    text-align: center;
}

.upload-method-btn.active {
    border-color: var(--accent-blue);
    background-color: rgba(61, 90, 254, 0.1);
}

.upload-method-btn i {
    font-size: 1.5rem;
    margin-bottom: 10px;
    color: var(--accent-blue);
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .card-body {
        padding: 20px;
    }
    
    .upload-method {
        flex-direction: column;
    }
    
    .qr-preview {
        max-width: 200px;
    }
}
</style>

<div class="container-fluid py-4">
    <?php if (isset($_SESSION['alert'])): ?>
        <div class="alert alert-<?= $_SESSION['alert']['type'] ?> alert-dismissible fade show" role="alert">
            <i class="fas <?= $_SESSION['alert']['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?> me-2"></i>
            <?= $_SESSION['alert']['message'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="card shadow-sm">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-qrcode me-2"></i>Gerenciador de QR Code</h4>
                    </div>
                </div>
                <div class="card-body">
                    <!-- Seção do QR Code Atual -->
                    <div class="qr-current-section">
                        <h5 class="section-title">
                            <i class="fas fa-eye"></i>QR Code Atual
                        </h5>
                        <img src="api/qr/qr.png?<?= time() ?>" class="qr-preview" 
                             onerror="this.src='https://via.placeholder.com/250?text=QR+Code+Não+Configurado'">
                        <p class="text-muted">Visualização do QR Code atualmente em uso</p>
                    </div>

                    <!-- Seção de Upload -->
                    <div class="qr-section">
                        <h5 class="section-title">
                            <i class="fas fa-cloud-upload-alt"></i>Configurar Novo QR Code
                        </h5>
                        
                        <div class="upload-method">
                            <div class="upload-method-btn active" onclick="showUploadMethod('file')">
                                <i class="fas fa-file-upload"></i>
                                <div>Upload de Arquivo</div>
                            </div>
                            <div class="upload-method-btn" onclick="showUploadMethod('url')">
                                <i class="fas fa-link"></i>
                                <div>Importar por URL</div>
                            </div>
                        </div>
                        
                        <!-- Método: Upload de Arquivo -->
                        <div id="file-upload-method">
                            <form method="post" enctype="multipart/form-data">
                                <div class="mb-4">
                                    <label for="image" class="form-label">Selecione um arquivo PNG</label>
                                    <input type="file" class="form-control" name="image" id="image" 
                                           accept="image/png" required>
                                    <small class="text-muted">Apenas arquivos .png são aceitos (Tamanho recomendado: 250x250px)</small>
                                </div>
                                <div class="text-center">
                                    <button type="submit" class="btn btn-primary px-5">
                                        <i class="fas fa-upload me-2"></i>Enviar Arquivo
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Método: Importar por URL -->
                        <div id="url-upload-method" style="display: none;">
                            <form method="post">
                                <div class="mb-4">
                                    <label for="image_url" class="form-label">URL da Imagem PNG</label>
                                    <input type="url" class="form-control" name="image_url" id="image_url" 
                                           placeholder="https://exemplo.com/qrcode.png" required>
                                    <small class="text-muted">Informe uma URL direta para uma imagem PNG</small>
                                </div>
                                <div class="text-center">
                                    <button type="submit" class="btn btn-success px-5">
                                        <i class="fas fa-download me-2"></i>Importar da URL
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Mostrar método de upload selecionado
function showUploadMethod(method) {
    document.querySelectorAll('.upload-method-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    if (method === 'file') {
        document.getElementById('file-upload-method').style.display = 'block';
        document.getElementById('url-upload-method').style.display = 'none';
        document.querySelector('.upload-method-btn:nth-child(1)').classList.add('active');
    } else {
        document.getElementById('file-upload-method').style.display = 'none';
        document.getElementById('url-upload-method').style.display = 'block';
        document.querySelector('.upload-method-btn:nth-child(2)').classList.add('active');
    }
}

// Fechar alertas automaticamente após 5 segundos
setTimeout(function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        var bsAlert = new bootstrap.Alert(alert);
        bsAlert.close();
    });
}, 5000);
</script>

<?php
ob_end_flush(); // Envie a saída do buffer
include "includes/footer.php";
?>
