<?php
session_start();
if(!isset($_SESSION['rev_logado'])){ header("Location: index_rev.php"); exit(); }
include('../api/conexao_rev.php');

$id_rev = $_SESSION['rev_logado'];
$base_file = basename($_SERVER["SCRIPT_NAME"]);

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

// Caminho do arquivo individual conforme solicitado em ../api/db/
$jsonFile = "../api/db/panaci_theme_rev_" . $id_rev . ".json";

// Se não existir, define o layout padrão (Layout 0)
if (!file_exists($jsonFile)) {
    $defaultData = [["RTXSetting" => "mLayout", "PanalData" => "theme_d"]];
    file_put_contents($jsonFile, json_encode($defaultData, JSON_PRETTY_PRINT));
}

$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);

$tema_atual = "theme_d";
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'])) {
        exit('Erro de Token');
    }

    $selectedOption = $_POST['options'];
    if (array_key_exists($selectedOption, $temas)) {
        $data[0]["RTXSetting"] = "mLayout";
        $data[0]["PanalData"] = $selectedOption;
        
        file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT));
        
        $tema_atual_escolhido = $temas[$selectedOption];
        $tema_atual = $selectedOption;
        $success = true;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personalizar Layout</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        html, body { background-color: #020617 !important; color: #e2e8f0 !important; font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; }
        .container-fluid { padding: 20px; max-width: 800px; margin: 0 auto; }
        
        .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; }

        .premium-card { background: #070e1b !important; border: 1px solid #1e293b !important; border-radius: 20px; padding: 25px; 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; }

        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; outline: none; }

        .row-buttons { display: grid; grid-template-columns: 1fr; gap: 12px; }
        @media (min-width: 600px) { .row-buttons { grid-template-columns: 2fr 1fr; } }
        
        .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; }
        .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; }

        .theme-preview-list { display: grid; grid-template-columns: 1fr; gap: 20px; margin-top: 30px; }
        @media (min-width: 600px) { .theme-preview-list { grid-template-columns: 1fr 1fr; } }

        .theme-item { background: #0f172a; border: 1px solid #1e293b; border-radius: 16px; padding: 12px; position: relative; transition: 0.3s; }
        .theme-item img { width: 100%; border-radius: 12px; filter: grayscale(0.5); }
        .theme-item p { margin: 10px 0 0; font-weight: 800; font-size: 0.8rem; color: #64748b; text-transform: uppercase; }

        .theme-item.active { border-color: #8b5cf6; background: rgba(139, 92, 246, 0.05); }
        .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.6rem; font-weight: 900; padding: 4px 10px; border-radius: 20px; text-transform: uppercase; }
    </style>
</head>
<body>

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

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Layout do Aplicativo</h1>
            <p><i class="fas fa-magic mr-1"></i> Selecione o tema exclusivo para seus clientes</p>
        </div>
        
        <form method="post">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>"> 
            
            <label>Modelo Visual</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-check-circle"></i> Salvar Layout
                </button>
                <a href="dashboard_rev.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;">Visualização dos Layouts</label>
            <div class="theme-preview-list">
                <?php
                foreach ($temas as $key => $label) {
                    $isActive = ($key === $tema_atual);
                    
                    if ($key === 'theme_d') {
                        $imgNum = "0"; 
                    } else {
                        $imgNum = str_replace('theme_', '', $key);
                    }
                    
                    // CAMINHO PARA A NOVA PASTA: 2026/layout_rev/
                    $imgPath = "../layout_rev/{$imgNum}.png"; 
                ?>
                    <div class="theme-item <?= $isActive ? 'active' : '' ?>">
                        <?php if($isActive): ?>
                            <div class="active-badge">Ativo</div>
                        <?php endif; ?>
                        <p><?= $label ?></p>
                        <img src="<?= $imgPath ?>" onerror="this.src='https://placehold.co/400x250/0f172a/334155?text=Carregando...'">
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<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_atual_escolhido ?> foi aplicado com sucesso.',
        background: '#070e1b',
        color: '#fff',
        confirmButtonColor: '#8b5cf6'
    });
</script>
<?php endif; ?>
</body>
</html>
