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

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

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

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

$branding = get_branding();
$current_bg = $branding['background_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: 60px 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: 20px;
        background: #0a0a0a;
        border-radius: 8px;
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .preview-section h3 {
        font-size: 16px;
        margin-bottom: 15px;
        color: #fff;
    }
    
    .preview-image {
        width: 100%;
        max-height: 400px;
        object-fit: cover;
        border-radius: 8px;
        border: 2px solid rgba(255, 255, 255, 0.1);
    }
    
    .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 Background</h1>
    <p>Altere a imagem de fundo do aplicativo</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="background_file" 
                           name="background_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 | Recomendado: 1920x1080px ou superior
                </div>
            </div>
        </div>
        
        <!-- Tab: URL -->
        <div id="url-tab" class="tab-content">
            <div class="form-group">
                <label for="background_url">🔗 URL do Background</label>
                <input type="url" 
                       id="background_url" 
                       name="background_url" 
                       value="<?php echo htmlspecialchars($current_bg); ?>"
                       placeholder="https://exemplo.com/background.jpg">
            </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 Background</button>
    </form>
    
    <?php if (!empty($current_bg)): ?>
        <div class="preview-section">
            <h3>👁️ Background Atual</h3>
            <img src="<?php echo htmlspecialchars($current_bg); ?>" 
                 alt="Background" 
                 class="preview-image"
                 onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
            <p style="display:none; color: #e74c3c; text-align: center; padding: 40px;">Erro ao carregar imagem</p>
            <p style="margin-top: 15px; font-size: 12px; color: #999; word-break: break-all;">
                URL: <?php echo htmlspecialchars($current_bg); ?>
            </p>
        </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>
