<?php
ob_start();
require_once __DIR__ . '/includes/header.php';

$message = '';
$message_type = '';

// Processar upload/atualização
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $logo_url = str_in($_POST['logo_url'] ?? '');
    $file = $_FILES['logo_file'] ?? null;
    
    $result = save_logo($logo_url, $file);
    
    if ($result['ok']) {
        ob_end_clean();
        header('Location: logo.php?success=1');
        exit;
    } else {
        $message = $result['message'];
        $message_type = 'error';
    }
}

if (isset($_GET['success'])) {
    $message = 'Logo atualizado com sucesso!';
    $message_type = 'success';
}

$branding = get_branding();
$current_logo = $branding['logo_url'] ?? '';
?>

<style>
    .page-header {
        margin-bottom: 30px;
    }
    
    .page-header h1 {
        font-size: 28px;
        margin-bottom: 8px;
        background: var(--primary-bg);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .page-header p {
        color: #999;
        font-size: 14px;
    }
    
    .alert {
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        animation: slideIn 0.3s ease;
    }
    
    .alert-success {
        background: rgba(46, 204, 113, 0.2);
        border: 1px solid #2ecc71;
        color: #2ecc71;
    }
    
    .alert-error {
        background: rgba(231, 76, 60, 0.2);
        border: 1px solid #e74c3c;
        color: #e74c3c;
    }
    
    .form-container {
        background: #1a1a1a;
        padding: 30px;
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        max-width: 800px;
    }
    
    .tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 25px;
        border-bottom: 2px solid rgba(255, 255, 255, 0.1);
    }
    
    .tab {
        padding: 10px 20px;
        background: transparent;
        border: none;
        color: #999;
        cursor: pointer;
        font-size: 14px;
        font-weight: 600;
        border-bottom: 3px solid transparent;
        transition: all 0.2s ease;
    }
    
    .tab:hover {
        color: #fff;
    }
    
    .tab.active {
        color: #fff;
        border-bottom-color: var(--primary-bg);
    }
    
    .tab-content {
        display: none;
    }
    
    .tab-content.active {
        display: block;
    }
    
    .form-group {
        margin-bottom: 25px;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 8px;
        color: #fff;
        font-weight: 500;
        font-size: 14px;
    }
    
    .form-group input[type="url"],
    .form-group input[type="text"] {
        width: 100%;
        padding: 12px 15px;
        background: #111;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        transition: all 0.2s ease;
    }
    
    .form-group input:focus {
        outline: none;
        border-color: var(--primary-bg);
        box-shadow: 0 0 0 3px rgba(192, 57, 43, 0.1);
    }
    
    .file-upload {
        position: relative;
        display: inline-block;
        width: 100%;
    }
    
    .file-upload input[type="file"] {
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
    
    .file-upload-label {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 40px 20px;
        background: #111;
        border: 2px dashed rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        color: #999;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .file-upload-label:hover {
        border-color: var(--primary-bg);
        background: rgba(255, 255, 255, 0.02);
    }
    
    .file-upload-label.has-file {
        border-color: #2ecc71;
        background: rgba(46, 204, 113, 0.1);
        color: #2ecc71;
    }
    
    .file-info {
        margin-top: 10px;
        font-size: 13px;
        color: #999;
    }
    
    .submit-btn {
        background: var(--primary-bg);
        color: #fff;
        padding: 12px 30px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        width: 100%;
    }
    
    .submit-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
    
    .preview-section {
        margin-top: 30px;
        padding: 24px;
        background: linear-gradient(135deg, rgba(34, 6, 83, 0.92), rgba(13, 2, 31, 0.96));
        border-radius: 18px;
        border: 1px solid rgba(181, 126, 255, 0.28);
        text-align: center;
        box-shadow: inset 0 0 35px rgba(138, 55, 255, 0.10);
    }
    
    .preview-section h3 {
        font-size: 16px;
        margin-bottom: 15px;
        color: #fff;
    }

    .preview-stage {
        width: 100%;
        min-height: 160px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 26px;
        border-radius: 18px;
        background:
            radial-gradient(circle at center, rgba(165, 75, 255, 0.30), rgba(29, 3, 70, 0.92) 55%, rgba(7, 1, 18, 0.96) 100%),
            linear-gradient(135deg, rgba(112, 35, 255, 0.30), rgba(20, 3, 45, 0.95));
        border: 1px dashed rgba(196, 155, 255, 0.32);
    }
    
    .preview-logo {
        max-width: 260px;
        max-height: 135px;
        object-fit: contain;
        background: transparent;
        padding: 0;
        border-radius: 0;
        filter: drop-shadow(0 10px 22px rgba(0, 0, 0, 0.55));
    }

    .preview-note {
        margin-top: 12px;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.65);
    }
    
    .info-box {
        background: rgba(52, 152, 219, 0.1);
        border: 1px solid #3498db;
        color: #3498db;
        padding: 15px;
        border-radius: 8px;
        margin-top: 20px;
        font-size: 13px;
    }
    
    @media (max-width: 768px) {
        .tabs {
            overflow-x: auto;
        }
    }
</style>

<div class="page-header">
    <h1>🏷️ Gerenciar Logo</h1>
    <p>Altere o logotipo do aplicativo e do painel</p>
</div>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="form-container">
    <div class="tabs">
        <button class="tab active" onclick="switchTab('upload')">📤 Upload de Imagem</button>
        <button class="tab" onclick="switchTab('url')">🔗 URL Externa</button>
    </div>
    
    <form method="POST" enctype="multipart/form-data">
        <!-- Tab: Upload -->
        <div id="upload-tab" class="tab-content active">
            <div class="form-group">
                <label>📷 Selecione uma imagem do seu computador</label>
                <div class="file-upload">
                    <input type="file" 
                           id="logo_file" 
                           name="logo_file" 
                           accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                           onchange="handleFileSelect(this)">
                    <div class="file-upload-label" id="fileLabel">
                        <span>📁</span>
                        <span>Clique para selecionar ou arraste a imagem aqui</span>
                    </div>
                </div>
                <div class="file-info">
                    Formatos aceitos: JPG, PNG, GIF, WEBP | Tamanho máximo: 5MB
                </div>
            </div>
        </div>
        
        <!-- Tab: URL -->
        <div id="url-tab" class="tab-content">
            <div class="form-group">
                <label for="logo_url">🔗 URL do Logo</label>
                <input type="url" 
                       id="logo_url" 
                       name="logo_url" 
                       value="<?php echo htmlspecialchars($current_logo); ?>"
                       placeholder="https://exemplo.com/logo.png">
            </div>
            
            <div class="info-box">
                💡 <strong>Dica:</strong> Você pode usar URLs externas (https://...) ou fazer upload de uma imagem local na aba "Upload de Imagem"
            </div>
        </div>
        
        <button type="submit" class="submit-btn">💾 Salvar Logo</button>
    </form>
    
    <?php if (!empty($current_logo)): ?>
        <div class="preview-section">
            <h3>👁️ Logo Atual</h3>
            <div class="preview-stage">
                <img src="<?php echo htmlspecialchars($current_logo); ?>" 
                     alt="Logo" 
                     class="preview-logo"
                     onerror="this.style.display='none'; document.getElementById('logoError').style.display='block';">
                <p id="logoError" style="display:none; color: #ff6b6b; margin: 0;">Erro ao carregar imagem</p>
            </div>
            <div class="preview-note">Prévia em fundo escuro para visualizar logos brancas ou transparentes.</div>
        </div>
    <?php endif; ?>
</div>

<script>
    function switchTab(tabName) {
        document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        
        event.target.classList.add('active');
        document.getElementById(tabName + '-tab').classList.add('active');
    }
    
    function handleFileSelect(input) {
        const label = document.getElementById('fileLabel');
        
        if (input.files && input.files[0]) {
            const file = input.files[0];
            const fileName = file.name;
            const fileSize = (file.size / 1024 / 1024).toFixed(2); // MB
            
            label.classList.add('has-file');
            label.innerHTML = `
                <span>✓</span>
                <div>
                    <div style="font-weight: 600;">${fileName}</div>
                    <div style="font-size: 12px; margin-top: 5px;">${fileSize} MB</div>
                </div>
            `;
        } else {
            label.classList.remove('has-file');
            label.innerHTML = `
                <span>📁</span>
                <span>Clique para selecionar ou arraste a imagem aqui</span>
            `;
        }
    }
</script>

</main>
</body>
</html>
