<?php
session_start();
if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

include "includes/header.php"; 

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$jsonData = file_get_contents('./api/theme_change/Setting.json');
$data = json_decode($jsonData, true);

$tema_atual = "";
foreach ($data as $item) {
    if (isset($item["RTXSetting"]) && $item["RTXSetting"] === "mLayout") {
        $tema_atual = $item["PanalData"];
        break;
    }
}

$temas = [
    "theme_d" => "Layout 0",
    "theme_1" => "Layout 1",
    "theme_2" => "Layout 2",
];

$tema_atual_escolhido = isset($temas[$tema_atual]) ? $temas[$tema_atual] : "Padrão";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php");
        exit();
    }

    $selectedOption = $_POST['options'];
    if (array_key_exists($selectedOption, $temas)) {
        $data[0]["RTXSetting"] = "mLayout";
        $data[0]["PanalData"] = $selectedOption;
        file_put_contents('./api/theme_change/Setting.json', json_encode($data, JSON_PRETTY_PRINT));
        
        $tema_atual_escolhido = $temas[$selectedOption];
        $tema_atual = $selectedOption;
        $success = true;
    }
}
?>

<style>
    /* RESET E FUNDO TOTAL DARK */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
    }

    /* OCULTAR ELEMENTOS DO HEADER */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* BOTÃO VOLTAR */
    .btn-back-nav {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        text-decoration: none !important;
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 20px;
    }

    /* CARD PREMIUM */
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 20px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
    }

    .card-header-premium { 
        margin-bottom: 25px; 
        border-bottom: 1px solid rgba(255,255,255,0.05); 
        padding-bottom: 15px; 
    }
    .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .card-header-premium p { color: #8b5cf6; font-size: 0.8rem; margin-top: 4px; font-weight: 600; }

    /* ESTILO FORMULÁRIO */
    label { 
        display: block; color: #8b5cf6; font-size: 0.7rem; font-weight: 800; 
        margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;
    }

    .form-input { 
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; 
        color: #fff !important; padding: 15px; border-radius: 12px; font-size: 0.95rem; margin-bottom: 20px; 
        appearance: none; -webkit-appearance: none;
    }

    /* BOTÕES */
    .row-buttons { display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 5px; }
    
    .btn-premium-save {
        background: #8b5cf6 !important; color: #fff !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px;
        box-shadow: 0 4px 15px rgba(139, 92, 246, 0.2);
    }
    
    .btn-premium-back {
        background: #1e293b !important; color: #94a3b8 !important;
        padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase;
        text-align: center; text-decoration: none !important;
    }

    /* GRID DE VISUALIZAÇÃO */
    .theme-preview-list {
        display: flex;
        flex-direction: column;
        gap: 25px;
        margin-top: 30px;
    }

    .theme-item {
        background: #0f172a;
        border: 1px solid #1e293b;
        border-radius: 16px;
        padding: 12px;
        transition: 0.3s;
        position: relative;
    }

    .theme-item img {
        width: 100%;
        border-radius: 12px;
        display: block;
        filter: grayscale(0.4);
        transition: 0.3s;
    }

    .theme-item p {
        margin: 12px 0 5px 5px;
        font-weight: 800;
        font-size: 0.85rem;
        color: #64748b;
        text-transform: uppercase;
    }

    /* ESTILO ATIVO */
    .theme-item.active {
        border-color: #8b5cf6;
        background: rgba(139, 92, 246, 0.05);
        box-shadow: 0 0 20px rgba(139, 92, 246, 0.15);
    }

    .theme-item.active img { filter: grayscale(0); }
    .theme-item.active p { color: #8b5cf6; }

    .active-badge {
        position: absolute;
        top: 20px;
        right: 20px;
        background: #8b5cf6;
        color: #fff;
        font-size: 0.65rem;
        font-weight: 900;
        padding: 5px 12px;
        border-radius: 20px;
        text-transform: uppercase;
        box-shadow: 0 4px 10px rgba(0,0,0,0.5);
    }

    @media (min-width: 768px) {
        .row-buttons { grid-template-columns: 2fr 1fr; }
        .theme-preview-list { display: grid; grid-template-columns: 1fr 1fr; }
    }
</style>

<div class="container-fluid">
    <a href="index.php" class="btn-back-nav">
        <i class="fas fa-chevron-left"></i> Voltar ao Início
    </a>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Layout do Painel</h1>
            <p><i class="fas fa-magic mr-1"></i> Personalize a aparência do seu sistema</p>
        </div>
        
        <form method="post">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>"> 
            
            <label>Selecione o Modelo</label>
            <select name="options" class="form-input">
                <?php
                foreach ($temas as $key => $label) {
                    $selected = ($key === $tema_atual) ? 'selected' : '';
                    echo "<option value='$key' $selected>$label</option>";
                }
                ?>
            </select>

            <div class="row-buttons">
                <button type="submit" class="btn-premium-save">
                    <i class="fas fa-sync-alt"></i> Aplicar Layout
                </button>
                <a href="index.php" class="btn-premium-back">Cancelar</a>
            </div>
        </form>

        <div style="margin-top: 40px; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 20px;">
            <label style="text-align: center; margin-bottom: 20px;">Catálogo de Visualização</label>

            <div class="theme-preview-list">
                <?php
                foreach ($temas as $key => $label) {
                    $isActive = ($key === $tema_atual);
                    $imgNum = str_replace('theme_', '', $key);
                    // Caso o tema clássico use 'd', ajustar aqui se necessário para d.png
                    $imgPath = "./rtx/layout/{$imgNum}.png"; 
                ?>
                    <div class="theme-item <?= $isActive ? 'active' : '' ?>">
                        <?php if($isActive): ?>
                            <div class="active-badge">Em uso</div>
                        <?php endif; ?>
                        <p><?= $label ?></p>
                        <img src="<?= $imgPath ?>" alt="<?= $label ?>" onerror="this.src='./assets/img/no-preview.png'">
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php if(isset($success)): ?>
<script>
    Swal.fire({
        icon: 'success',
        title: 'Layout Atualizado!',
        text: 'O tema <?= $tema_atual_escolhido ?> já está ativo.',
        background: '#070e1b',
        color: '#fff',
        confirmButtonColor: '#8b5cf6'
    });
</script>
<?php endif; ?>

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