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

$jsonFile = './api/setting.json';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['theme'])) {
    $selectedTheme = $_POST['theme'];
    $jsonData = file_get_contents($jsonFile);
    $data = json_decode($jsonData, true);

    if (!empty($data)) {
        $data[0]['PanalData'] = $selectedTheme;
        file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT));
    }

    try {
        $db = new SQLite3('./a/.eggziedb.db');
        $db->exec("CREATE TABLE IF NOT EXISTS theme (id INTEGER PRIMARY KEY, name VARCHAR(100), url VARCHAR(100))");
        $db->exec("DELETE FROM theme");
        $stmt = $db->prepare("INSERT INTO theme (name, url) VALUES (:name, :url)");
        $stmt->bindValue(':name', $selectedTheme, SQLITE3_TEXT);
        $stmt->bindValue(':url', './themes/' . $selectedTheme, SQLITE3_TEXT);
        $stmt->execute();
        $db->close();
    } catch (Exception $e) {}

    header("Location: layouts.php?r=atualizado");
    exit;
}

$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);
$currentTheme = !empty($data) ? $data[0]['PanalData'] : 'theme_d';

$themes = [
    'theme_d' => ['label' => 'Standard Classic', 'img' => './assets/images/standard.jpg'],
    'theme_1' => ['label' => 'Premium Blue', 'img' => './assets/images/tema1.jpg'],
    'theme_2' => ['label' => 'Metallic Silver', 'img' => './assets/images/tema2.jpg'],
    'theme_3' => ['label' => 'Neon Cyber', 'img' => './assets/images/tema3.jpg'],
    'theme_4' => ['label' => 'Dark Horizon', 'img' => './assets/images/tema4.jpg'],
    'theme_5' => ['label' => 'Royal Gold', 'img' => './assets/images/tema5.jpg'],
    'theme_6' => ['label' => 'Emerald City', 'img' => './assets/images/tema6.jpg']
];

include './includes/header.php';
?>

<style>
    :root {
        --primary: #00BFFF; /* Azul Celeste */
        --primary-dark: #4682B4; /* Azul Metálico */
        --bg-dark: #0a192f;
        --card-bg: rgba(17, 34, 64, 0.7);
        --text-main: #e6f1ff;
        --text-muted: #8892b0;
        --glow: 0 0 15px rgba(0, 191, 255, 0.4);
    }

    .themes-container {
        padding: 1.5rem;
        animation: fadeIn 0.5s ease-in-out;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .page-header {
        margin-bottom: 2.5rem;
        background: linear-gradient(135deg, rgba(17, 34, 64, 0.8), rgba(10, 25, 47, 0.8));
        padding: 2rem;
        border-radius: 24px;
        border: 1px solid rgba(0, 191, 255, 0.2);
        box-shadow: var(--glow);
    }

    .page-header h1 {
        font-size: 2.2rem;
        font-weight: 800;
        background: linear-gradient(90deg, var(--primary), var(--primary-dark));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 0.5rem;
    }

    .themes-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 2rem;
    }

    .theme-card {
        background: var(--card-bg);
        border-radius: 24px;
        overflow: hidden;
        border: 2px solid transparent;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
    }

    .theme-card:hover {
        transform: translateY(-10px);
        border-color: var(--primary);
        box-shadow: var(--glow);
    }

    .theme-card.active {
        border-color: var(--primary);
        box-shadow: 0 0 25px rgba(0, 191, 255, 0.6);
    }

    .theme-card.active::before {
        content: 'ATIVO';
        position: absolute;
        top: 15px;
        right: 15px;
        background: var(--primary);
        color: #000;
        padding: 5px 15px;
        border-radius: 50px;
        font-size: 0.7rem;
        font-weight: 900;
        z-index: 10;
        box-shadow: 0 0 10px var(--primary);
    }

    .theme-preview {
        width: 100%;
        height: 180px;
        object-fit: cover;
        transition: transform 0.5s ease;
    }

    .theme-card:hover .theme-preview {
        transform: scale(1.1);
    }

    .theme-details {
        padding: 1.5rem;
        background: linear-gradient(to top, rgba(10, 25, 47, 0.9), transparent);
    }

    .theme-details h3 {
        color: var(--text-main);
        font-size: 1.1rem;
        margin-bottom: 1rem;
        font-weight: 700;
    }

    .apply-btn {
        width: 100%;
        padding: 0.8rem;
        background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        border: none;
        border-radius: 12px;
        color: #fff;
        font-weight: 700;
        font-size: 0.9rem;
        cursor: pointer;
        transition: all 0.3s ease;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .apply-btn:hover {
        filter: brightness(1.2);
        box-shadow: 0 0 15px var(--primary);
    }

    .apply-btn:disabled {
        background: #333;
        cursor: not-allowed;
    }

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

<div class="themes-container">
    <div class="page-header">
        <h1>Personalização de Temas</h1>
        <p class="text-muted">Escolha um visual incrível para o seu aplicativo IBO Player.</p>
    </div>

    <div class="themes-grid">
        <?php foreach ($themes as $id => $info): ?>
            <div class="theme-card <?php echo ($currentTheme == $id) ? 'active' : ''; ?>" onclick="submitTheme('<?php echo $id; ?>')">
                <img src="<?php echo $info['img']; ?>" class="theme-preview" alt="<?php echo $info['label']; ?>" onerror="this.src='./assets/images/standard.jpg'">
                <div class="theme-details">
                    <h3><?php echo $info['label']; ?></h3>
                    <form method="post" id="form-<?php echo $id; ?>">
                        <input type="hidden" name="theme" value="<?php echo $id; ?>">
                        <button type="submit" class="apply-btn" <?php echo ($currentTheme == $id) ? 'disabled' : ''; ?>>
                            <?php echo ($currentTheme == $id) ? 'Já Aplicado' : 'Aplicar Tema'; ?>
                        </button>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
function submitTheme(id) {
    const form = document.getElementById('form-' + id);
    if (form) form.submit();
}

<?php if (isset($_GET['r']) && $_GET['r'] == 'atualizado'): ?>
    Swal.fire({
        icon: 'success',
        title: 'Tema Atualizado!',
        text: 'O novo visual foi aplicado com sucesso.',
        background: '#0a192f',
        color: '#e6f1ff',
        confirmButtonColor: '#00BFFF'
    });
<?php endif; ?>
</script>

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