<?php
ob_start(); // Inicia buffer de saída
require_once __DIR__ . '/includes/header.php';

$user = current_user();
$user_id = $user['id'] ?? 0;
$theme_config = get_user_theme($user_id);
$current_theme = $theme_config['mode'];
$custom_css = $theme_config['custom_css'];

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

// Processar alteração de tema
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['theme_mode'])) {
        $new_theme = str_in($_POST['theme_mode']);
        $available = array_keys(get_available_themes());
        
        if (in_array($new_theme, $available)) {
            if (save_user_theme($user_id, $new_theme, '')) {
                ob_end_clean(); // Limpa buffer antes do redirect
                header('Location: theme.php?success=1');
                exit;
            } else {
                $message = 'Erro ao salvar tema.';
                $message_type = 'error';
            }
        }
    } elseif (isset($_POST['custom_css'])) {
        $custom = trim($_POST['custom_css']);
        if (save_user_theme($user_id, 'custom', $custom)) {
            ob_end_clean(); // Limpa buffer antes do redirect
            header('Location: theme.php?success=2');
            exit;
        } else {
            $message = 'Erro ao salvar CSS.';
            $message_type = 'error';
        }
    }
}

if (isset($_GET['success'])) {
    if ($_GET['success'] == 1) {
        $message = 'Tema alterado com sucesso!';
    } else {
        $message = 'CSS personalizado salvo com sucesso!';
    }
    $message_type = 'success';
    // Atualizar dados após redirect
    $theme_config = get_user_theme($user_id);
    $current_theme = $theme_config['mode'];
    $custom_css = $theme_config['custom_css'];
}

$available_themes = get_available_themes();
?>

<style>
    .theme-header {
        margin-bottom: 30px;
    }
    
    .theme-header h1 {
        font-size: 28px;
        margin-bottom: 8px;
        background: var(--primary-bg);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .theme-header p {
        color: #999;
        font-size: 14px;
    }
    
    .alert {
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        font-size: 14px;
        animation: slideIn 0.3s ease;
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .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;
    }
    
    .tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 30px;
        border-bottom: 2px solid rgba(255, 255, 255, 0.1);
    }
    
    .tab {
        padding: 12px 24px;
        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;
    }
    
    .current-theme-info {
        background: #1a1a1a;
        padding: 20px;
        border-radius: 10px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        margin-bottom: 30px;
    }
    
    .current-theme-info h2 {
        font-size: 16px;
        margin-bottom: 10px;
        color: #fff;
    }
    
    .current-theme-info p {
        color: #999;
        font-size: 14px;
    }
    
    .theme-container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }
    
    .theme-card {
        background: #1a1a1a;
        border-radius: 12px;
        overflow: hidden;
        border: 2px solid rgba(255, 255, 255, 0.1);
        transition: all 0.3s ease;
        cursor: pointer;
        position: relative;
    }
    
    .theme-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
    }
    
    .theme-card.active {
        border-color: #2ecc71;
        box-shadow: 0 0 20px rgba(46, 204, 113, 0.3);
    }
    
    .theme-card.active::before {
        content: "✓ Ativo";
        position: absolute;
        top: 15px;
        right: 15px;
        background: #2ecc71;
        color: #fff;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: bold;
        z-index: 10;
    }
    
    .theme-preview {
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 48px;
        position: relative;
    }
    
    .theme-info {
        padding: 20px;
    }
    
    .theme-info h3 {
        font-size: 18px;
        margin-bottom: 8px;
        color: #fff;
    }
    
    .theme-info p {
        color: #999;
        font-size: 13px;
        margin-bottom: 15px;
    }
    
    .select-btn {
        width: 100%;
        padding: 10px;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .select-btn:not(.active-btn) {
        background: rgba(255, 255, 255, 0.1);
        color: #fff;
    }
    
    .select-btn:not(.active-btn):hover {
        background: rgba(255, 255, 255, 0.2);
    }
    
    .select-btn.active-btn {
        background: #2ecc71;
        color: #fff;
        cursor: default;
    }
    
    .css-editor-container {
        background: #1a1a1a;
        padding: 25px;
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .css-editor-container h2 {
        font-size: 18px;
        margin-bottom: 15px;
        color: #fff;
    }
    
    .css-editor-container p {
        color: #999;
        font-size: 14px;
        margin-bottom: 20px;
    }
    
    .css-editor {
        width: 100%;
        min-height: 400px;
        padding: 15px;
        background: #0a0a0a;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        color: #f8f8f2;
        font-family: 'Courier New', monospace;
        font-size: 13px;
        resize: vertical;
    }
    
    .css-editor:focus {
        outline: none;
        border-color: var(--primary-bg);
        box-shadow: 0 0 0 3px rgba(192, 57, 43, 0.1);
    }
    
    .css-template {
        background: #0a0a0a;
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 20px;
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .css-template h3 {
        font-size: 14px;
        color: #fff;
        margin-bottom: 10px;
    }
    
    .css-template code {
        display: block;
        color: #2ecc71;
        font-size: 12px;
        line-height: 1.6;
    }
    
    .save-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;
        margin-top: 15px;
    }
    
    .save-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
    
    @media (max-width: 768px) {
        .theme-container {
            grid-template-columns: 1fr;
        }
        
        .tabs {
            overflow-x: auto;
        }
        
        .tab {
            white-space: nowrap;
        }
    }
</style>

<div class="theme-header">
    <h1>🎨 Gerenciador de Temas</h1>
    <p>Personalize a aparência do seu painel</p>
</div>

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

<div class="current-theme-info">
    <h2>Tema Atual</h2>
    <p>
        Você está usando: 
        <strong>
            <?php 
            if ($current_theme === 'custom') {
                echo '🎨 CSS Personalizado';
            } else {
                echo $available_themes[$current_theme]['icon'] . ' ' . $available_themes[$current_theme]['name'];
            }
            ?>
        </strong>
    </p>
</div>

<div class="tabs">
    <button class="tab active" onclick="switchTab('predefined')">🎨 Temas Pré-definidos</button>
    <button class="tab" onclick="switchTab('custom')">✏️ CSS Personalizado</button>
</div>

<!-- Tab: Temas Pré-definidos -->
<div id="predefined-tab" class="tab-content active">
    <form method="POST" id="themeForm">
        <div class="theme-container">
            <?php foreach ($available_themes as $key => $theme): ?>
                <div class="theme-card <?php echo $current_theme === $key && $current_theme !== 'custom' ? 'active' : ''; ?>" 
                     onclick="selectTheme('<?php echo $key; ?>')">
                    <div class="theme-preview" style="background: <?php echo $theme['preview_color']; ?>">
                        <?php echo $theme['icon']; ?>
                    </div>
                    <div class="theme-info">
                        <h3><?php echo $theme['name']; ?></h3>
                        <p><?php echo $theme['description']; ?></p>
                        <button type="submit" 
                                name="theme_mode" 
                                value="<?php echo $key; ?>" 
                                class="select-btn <?php echo $current_theme === $key && $current_theme !== 'custom' ? 'active-btn' : ''; ?>">
                            <?php echo $current_theme === $key && $current_theme !== 'custom' ? '✓ Tema Ativo' : 'Selecionar Tema'; ?>
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </form>
</div>

<!-- Tab: CSS Personalizado -->
<div id="custom-tab" class="tab-content">
    <div class="css-editor-container">
        <h2>✏️ Editor de CSS Personalizado</h2>
        <p>Crie seu próprio tema editando as variáveis CSS abaixo. Use o template como base:</p>
        
        <div class="css-template">
            <h3>📝 Template de Variáveis CSS:</h3>
            <code>
                :root {<br>
                &nbsp;&nbsp;--primary-bg: #c0392b;<br>
                &nbsp;&nbsp;--sidebar-bg: #222;<br>
                &nbsp;&nbsp;--hover-bg: #555;<br>
                &nbsp;&nbsp;--link-bg: #444;<br>
                &nbsp;&nbsp;--link-hover: #555;<br>
                &nbsp;&nbsp;--logout-bg: #c0392b;<br>
                &nbsp;&nbsp;--logout-hover: #e74c3c;<br>
                }
            </code>
        </div>
        
        <form method="POST">
            <textarea name="custom_css" class="css-editor" placeholder="Cole ou edite seu CSS aqui..."><?php echo htmlspecialchars($custom_css); ?></textarea>
            <button type="submit" class="save-btn">💾 Salvar CSS Personalizado</button>
        </form>
    </div>
</div>

<script>
    function switchTab(tabName) {
        // Remove active de todas as tabs
        document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        
        // Ativa a tab clicada
        event.target.classList.add('active');
        document.getElementById(tabName + '-tab').classList.add('active');
    }
    
    function selectTheme(theme) {
        const buttons = document.querySelectorAll('.select-btn:not(.active-btn)');
        buttons.forEach(btn => {
            if (btn.value === theme) {
                btn.click();
            }
        });
    }
</script>

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