<?php
/*
desenvolvedor: luciano donizeti
mania de script: www.maniadescript.com.br
whatsapp 43998240911
*/

session_start();
require_once 'db/configdb.php';
require_once 'tema_helper.php';

if (!isset($_SESSION['usuario']) || !isset($_SESSION['user_id']) || !isset($_SESSION['nivel'])) {
    header('Location: login.php?error=session_invalid');
    exit();
}

$mensagem = '';
$temas = painelTemasDisponiveis();

try {
    $pdo = conectarTemaPainelPDO();
    ensureTemaPainelColumn($pdo);
    $temaAtual = obterTemaPainelUsuario($pdo, $_SESSION['user_id']);

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $temaEscolhido = normalizarTemaPainel($_POST['tema_painel'] ?? '');

        if (!isset($temas[$temaEscolhido])) {
            $mensagem = '<div class="alert alert-danger"><i class="fas fa-triangle-exclamation"></i> Tema inválido.</div>';
        } else {
            salvarTemaPainelUsuario($pdo, $_SESSION['user_id'], $temaEscolhido);
            $_SESSION['tema_painel'] = $temaEscolhido;
            $temaAtual = $temaEscolhido;
            $mensagem = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> Tema aplicado com sucesso. Esta alteração vale somente para o seu usuário.</div>';
        }
    }
} catch (Throwable $e) {
    error_log(date('Y-m-d H:i:s') . " - Erro em temas.php: " . $e->getMessage() . "\n", 3, 'session_debug.log');
    $temaAtual = temaPainelPadrao();
    $mensagem = '<div class="alert alert-danger"><i class="fas fa-triangle-exclamation"></i> Não foi possível carregar/salvar o tema agora. Verifique a conexão com o banco.</div>';
}

$pageTitle = 'Tema do Painel';
include 'includes/header.php';
?>

<style>
    .theme-page {
        max-width: 1240px;
        margin: 0 auto;
    }

    .theme-intro {
        display: grid;
        grid-template-columns: 1fr auto;
        gap: 20px;
        align-items: center;
        margin-bottom: 24px;
    }

    .theme-current-badge {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 10px 14px;
        border: 1px solid var(--theme-border-color);
        border-radius: 999px;
        background: rgba(0, 0, 0, 0.18);
        color: var(--text-color);
        font-weight: 700;
        white-space: nowrap;
    }

    .theme-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 18px;
    }

    .theme-card {
        position: relative;
        overflow: hidden;
        border-radius: 18px;
        border: 1px solid var(--theme-border-color);
        min-height: 225px;
        box-shadow: var(--box-shadow);
        transition: transform .2s ease, border-color .2s ease, box-shadow .2s ease;
    }

    .theme-card:hover {
        transform: translateY(-4px);
        border-color: var(--accent-color);
    }

    .theme-card.is-active {
        outline: 3px solid var(--accent-color);
        outline-offset: 2px;
    }

    .theme-preview {
        padding: 16px;
        min-height: 130px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.14);
    }

    .preview-layout {
        display: grid;
        grid-template-columns: 54px 1fr;
        gap: 12px;
        height: 100px;
    }

    .preview-sidebar,
    .preview-card {
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.14);
    }

    .preview-sidebar {
        display: flex;
        flex-direction: column;
        gap: 8px;
        padding: 10px;
    }

    .preview-dot,
    .preview-line,
    .preview-button {
        border-radius: 999px;
    }

    .preview-dot {
        width: 22px;
        height: 22px;
    }

    .preview-line {
        width: 100%;
        height: 7px;
        opacity: .75;
    }

    .preview-card {
        padding: 14px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .preview-button {
        height: 26px;
        width: 70%;
    }

    .theme-info {
        padding: 16px;
        background: rgba(0, 0, 0, 0.14);
    }

    .theme-info h3 {
        margin: 0 0 6px;
        font-size: 1.05rem;
        color: inherit;
    }

    .theme-info p {
        margin: 0 0 14px;
        min-height: 42px;
        font-size: .92rem;
        color: inherit;
        opacity: .82;
    }

    .theme-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
    }

    .theme-apply-btn {
        border: none;
        border-radius: 10px;
        padding: 10px 14px;
        font-weight: 800;
        color: white;
        cursor: pointer;
        width: 100%;
        transition: filter .2s ease, transform .2s ease;
    }

    .theme-apply-btn:hover {
        filter: brightness(1.08);
        transform: translateY(-1px);
    }

    .theme-active-label {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 7px;
        width: 100%;
        padding: 10px 14px;
        border-radius: 10px;
        font-weight: 800;
        background: rgba(34, 197, 94, .18);
        color: var(--success-color);
        border: 1px solid rgba(34, 197, 94, .32);
    }

    .alert {
        padding: 15px 18px;
        margin-bottom: 20px;
        border-radius: 12px;
        font-weight: 700;
        display: flex;
        gap: 10px;
        align-items: center;
    }

    .alert-success {
        background: rgba(34, 197, 94, .16);
        border: 1px solid rgba(34, 197, 94, .34);
        color: var(--success-color);
    }

    .alert-danger {
        background: rgba(239, 68, 68, .16);
        border: 1px solid rgba(239, 68, 68, .34);
        color: var(--danger-color);
    }

    @media (max-width: 720px) {
        .theme-intro {
            grid-template-columns: 1fr;
        }
    }
</style>

<div class="theme-page">
    <div class="page-header theme-intro">
        <div>
            <h1><i class="fas fa-palette" style="color: var(--accent-color);"></i> Tema do Painel</h1>
            <p style="color: var(--text-muted);">Escolha as cores do seu painel. O tema fica salvo apenas para o seu usuário, sem alterar o painel dos outros revendedores.</p>
        </div>
        <div class="theme-current-badge">
            <i class="fas fa-circle-half-stroke"></i>
            Atual: <?php echo htmlspecialchars($temas[$temaAtual]['nome'] ?? 'Azul Noite', ENT_QUOTES, 'UTF-8'); ?>
        </div>
    </div>

    <?php if ($mensagem) echo $mensagem; ?>

    <div class="theme-grid">
        <?php foreach ($temas as $slug => $tema): ?>
            <?php $ativo = ($slug === $temaAtual); ?>
            <div class="theme-card <?php echo $ativo ? 'is-active' : ''; ?>" style="background: <?php echo htmlspecialchars($tema['gradient'], ENT_QUOTES, 'UTF-8'); ?>; color: <?php echo htmlspecialchars($tema['text_color'], ENT_QUOTES, 'UTF-8'); ?>;">
                <div class="theme-preview">
                    <div class="preview-layout">
                        <div class="preview-sidebar" style="background: <?php echo htmlspecialchars($tema['sidebar_bg'], ENT_QUOTES, 'UTF-8'); ?>;">
                            <span class="preview-dot" style="background: <?php echo htmlspecialchars($tema['accent_color'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                            <span class="preview-line" style="background: <?php echo htmlspecialchars($tema['text_muted'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                            <span class="preview-line" style="background: <?php echo htmlspecialchars($tema['text_muted'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                            <span class="preview-line" style="background: <?php echo htmlspecialchars($tema['accent_color'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                        </div>
                        <div class="preview-card" style="background: <?php echo htmlspecialchars($tema['card_bg'], ENT_QUOTES, 'UTF-8'); ?>;">
                            <span class="preview-line" style="width: 80%; background: <?php echo htmlspecialchars($tema['text_color'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                            <span class="preview-line" style="width: 56%; background: <?php echo htmlspecialchars($tema['text_muted'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                            <span class="preview-button" style="background: <?php echo htmlspecialchars($tema['accent_color'], ENT_QUOTES, 'UTF-8'); ?>;"></span>
                        </div>
                    </div>
                </div>

                <div class="theme-info">
                    <h3><?php echo htmlspecialchars($tema['nome'], ENT_QUOTES, 'UTF-8'); ?></h3>
                    <p><?php echo htmlspecialchars($tema['descricao'], ENT_QUOTES, 'UTF-8'); ?></p>
                    <div class="theme-actions">
                        <?php if ($ativo): ?>
                            <span class="theme-active-label"><i class="fas fa-check"></i> Em uso</span>
                        <?php else: ?>
                            <form method="POST" action="temas.php" style="width: 100%; margin: 0;">
                                <input type="hidden" name="tema_painel" value="<?php echo htmlspecialchars($slug, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="theme-apply-btn" style="background: <?php echo htmlspecialchars($tema['accent_color'], ENT_QUOTES, 'UTF-8'); ?>;">
                                    Aplicar tema
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

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