<?php
session_start();
include 'auth.php';

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

// ===== CONFIGURAÇÃO DO BANCO DE DATOS =====
$db_path = __DIR__ . '/api/db/db_ads.db';

if (!file_exists(__DIR__ . '/api/db')) {
    mkdir(__DIR__ . '/api/db', 0755, true);
}

try {
    $db = new SQLite3($db_path);
    $db->exec("CREATE TABLE IF NOT EXISTS adsstatus (id INTEGER PRIMARY KEY, adstype TEXT)");
} catch (Exception $e) {
    die("Erro ao conectar ao banco de dados: " . $e->getMessage());
}

$status_message = '';
$status_type = '';

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

    $ad_item = $_POST["ad_item"];
    $check_count = $db->querySingle("SELECT COUNT(*) FROM adsstatus");

    if ($check_count === 0) {
        $stmt = $db->prepare("INSERT INTO adsstatus (adstype) VALUES (:ad_item)");
    } else {
        $stmt = $db->prepare("UPDATE adsstatus SET adstype = :ad_item WHERE id = 1");
    }

    $stmt->bindValue(':ad_item', $ad_item, SQLITE3_TEXT);

    if ($stmt->execute()) {
        $source = "./" . $ad_item . "/allads.php";
        $destination = "./api/allads.php";
        
        if (file_exists($source)) {
            if (copy($source, $destination)) {
                $status_message = "MODO " . strtoupper($ad_item) . " ATIVADO!";
                $status_type = "success";
            } else {
                $status_message = "ERRO AO COPIAR ARQUIVO API.";
                $status_type = "error";
            }
        } else {
            $status_message = "AVISO: MODO SALVO, MAS ARQUIVO NÃO ENCONTRADO.";
            $status_type = "warning";
        }
    }
}

$current_mode = $db->querySingle("SELECT adstype FROM adsstatus WHERE id = 1") ?: 'Autoads';

include "includes/header.php";
?>

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

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

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

    /* BOTÃO VOLTAR NAVEGAÇÃO */
    .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 CYAN */
    .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: 20px;
        text-align: center;
    }
    .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .card-header-premium p { color: #06b6d4; font-size: 0.8rem; margin-top: 4px; font-weight: 600; text-transform: uppercase; }

    /* ESTILO DO SELETOR (SELECT) */
    label { 
        display: block; color: #06b6d4; font-size: 0.7rem; font-weight: 800; 
        margin-bottom: 10px; text-transform: uppercase; letter-spacing: 1px;
        text-align: center;
    }

    .form-select-premium {
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; 
        color: #fff !important; padding: 18px; border-radius: 15px; font-size: 1rem; 
        margin-bottom: 25px; appearance: none; cursor: pointer; transition: 0.3s;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%2306b6d4' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
        background-repeat: no-repeat; background-position: right 1.2rem center; background-size: 1.2em;
    }
    .form-select-premium:focus { border-color: #06b6d4; box-shadow: 0 0 15px rgba(6, 182, 212, 0.1); }

    /* BOTÕES */
    .row-buttons { display: grid; grid-template-columns: 1fr; gap: 12px; }
    
    .btn-premium-cyan {
        background: #06b6d4 !important; color: #fff !important;
        padding: 18px; border-radius: 15px; 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(6, 182, 212, 0.2); transition: 0.3s;
    }
    
    .btn-premium-dark {
        background: #1e293b !important; color: #94a3b8 !important;
        padding: 18px; border-radius: 15px; font-weight: 800; text-transform: uppercase;
        text-align: center; text-decoration: none !important;
    }

    .btn-premium-cyan:active { transform: scale(0.98); }

    /* INFO BOX */
    .info-box-mode {
        background: rgba(6, 182, 212, 0.05);
        border-radius: 12px;
        padding: 15px;
        margin-top: 25px;
        border: 1px solid rgba(6, 182, 212, 0.1);
        font-size: 0.8rem;
        color: #94a3b8;
        line-height: 1.5;
    }

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

<div class="container-fluid">
    <a href="index.php" class="btn-back-nav">
        <i class="fas fa-chevron-left"></i> Painel de Controle
    </a>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Modo de Exibição</h1>
            <p><i class="fas fa-bullhorn mr-1"></i> Controle de Banners & ADS</p>
        </div>

        <form method="POST">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>">
            
            <label for="ad_item">Método de Processamento</label>
            <select name="ad_item" id="ad_item" class="form-select-premium">
                <option value="Autoads" <?= ($current_mode == 'Autoads' ? 'selected' : '') ?>>🚀 Modo Automático</option>
                <option value="Manualads" <?= ($current_mode == 'Manualads' ? 'selected' : '') ?>>⚙️ Modo Manual</option>
            </select>

            <div class="row-buttons">
                <button type="submit" name="submit" class="btn-premium-cyan">
                    <i class="fas fa-save"></i> Aplicar Alteração
                </button>
                <a href="index.php" class="btn-premium-dark">Sair</a>
            </div>
        </form>

        <div class="info-box-mode">
            <i class="fas fa-info-circle mr-1" style="color: #06b6d4;"></i> 
            <strong>Automático:</strong> O sistema gerencia os arquivos dinamicamente.<br>
            <strong>Manual:</strong> Você define manualmente as regras em <code>allads.php</code>.
        </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>

<script>
    <?php if ($status_message): ?>
        Swal.fire({
            icon: '<?= $status_type ?>',
            title: '<?= ($status_type == "success" ? "Sucesso!" : "Atenção") ?>',
            text: '<?= $status_message ?>',
            background: '#070e1b',
            color: '#fff',
            confirmButtonColor: '#06b6d4'
        });
    <?php endif; ?>
</script>

<?php 
$db->close();
include('includes/footer.php'); 
?>