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

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

// Configuração do Banco de Dados (Padronizado)
$db_path = __DIR__ . '/api/db/db_ads.db';
if (!file_exists(__DIR__ . '/api/db')) { mkdir(__DIR__ . '/api/db', 0755, true); }

try {
    $pdo = new PDO("sqlite:" . $db_path);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("CREATE TABLE IF NOT EXISTS ads2 (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title VARCHAR(100),
        url TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
} catch(PDOException $e) { die("Erro: " . $e->getMessage()); }

$base_file = basename($_SERVER["SCRIPT_NAME"]);

if (isset($_POST['submit']) || isset($_POST['submitU'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php"); exit();
    }
    
    if (isset($_POST['submitU'])) {
        $stmt = $pdo->prepare("UPDATE ads2 SET title = ?, url = ? WHERE id = ?");
        $stmt->execute([$_POST['title'], $_POST['url'], $_POST['id']]);
        $_SESSION['msg'] = "Banner Secundário atualizado!";
    } else {
        $stmt = $pdo->prepare("INSERT INTO ads2 (title, url) VALUES (?, ?)");
        $stmt->execute([$_POST['title'], $_POST['url']]);
        $_SESSION['msg'] = "Novo Banner Secundário adicionado!";
    }
    header("Location: $base_file"); exit;
}

if (isset($_GET['delete_confirmed'])) {
    $stmt = $pdo->prepare("DELETE FROM ads2 WHERE id = ?");
    $stmt->execute([$_GET['delete_confirmed']]);
    $_SESSION['msg'] = "Banner removido!";
    header("Location: $base_file"); exit;
}

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

<style>
    /* RESET DE CAIXA PARA SEGURANÇA */
    * { box-sizing: border-box; }

    /* DESIGN SYSTEM ULTRA DARK ROYAL BLUE */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #f8fafc !important;
    }

    .navbar, .lua-icon, .fa-moon, .fa-sun { display: none !important; }
    .container-fluid { padding: 15px !important; }

    /* NAVEGAÇÃO SUPERIOR */
    .top-nav {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 25px;
    }

    .btn-create-lux {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        color: #fff !important;
        padding: 12px 20px;
        border-radius: 12px;
        font-weight: 800;
        font-size: 0.75rem;
        text-transform: uppercase;
        box-shadow: 0 10px 20px rgba(59, 130, 246, 0.2);
        text-decoration: none !important;
    }

    /* GRID DE CARDS */
    .ads-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 20px;
    }

    .banner-card-lux {
        background: #0f172a;
        border: 1px solid #1e293b;
        border-radius: 24px;
        overflow: hidden;
        width: 100%;
    }

    .banner-visual {
        width: 100%;
        aspect-ratio: 16 / 9;
        background: #000;
        position: relative;
    }

    .banner-visual img, .banner-visual video {
        width: 100%; height: 100%; object-fit: cover;
    }

    .banner-info-overlay {
        position: absolute;
        bottom: 0; left: 0; right: 0;
        padding: 20px;
        background: linear-gradient(to top, rgba(2, 6, 23, 1) 0%, rgba(2, 6, 23, 0.7) 60%, transparent 100%);
    }

    /* BARRA DE AÇÕES CORRIGIDA */
    .banner-actions-bar {
        padding: 15px 20px; /* Margem interna para os botões não tocarem a borda */
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #0f172a;
        border-top: 1px solid rgba(255,255,255,0.03);
    }

    .action-btn-lux {
        width: 44px;
        height: 44px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        cursor: pointer;
    }

    .btn-edit-royal { background: #1e293b; color: #60a5fa; }
    .btn-del-royal { background: #1e293b; color: #f87171; }

    /* FORMULÁRIO CORRIGIDO */
    .form-container-lux {
        background: #070e1b;
        border-radius: 28px;
        padding: 25px;
        border: 1px solid #1e293b;
        max-width: 600px;
        margin: 0 auto;
        width: 100%;
    }

    .input-premium {
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important;
        color: #fff !important; padding: 18px; border-radius: 16px; margin-bottom: 20px;
    }

    .btn-save-royal {
        width: 100%; background: #3b82f6; color: #fff; padding: 20px;
        border-radius: 18px; font-weight: 800; text-transform: uppercase; border: none;
        display: block;
    }

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

<div class="container-fluid">

<?php if (isset($_GET['create']) || isset($_GET['update'])): 
    if (isset($_GET['update'])) {
        $stmt = $pdo->prepare("SELECT * FROM ads2 WHERE id = ?");
        $stmt->execute([$_GET['update']]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
    }
?>
    <div class="top-nav">
        <a href="<?= $base_file ?>" style="color: #64748b; font-weight: 700; text-decoration: none;">
            <i class="fas fa-chevron-left"></i> VOLTAR
        </a>
    </div>

    <div class="form-container-lux">
        <h2 style="font-weight: 900; margin-bottom: 30px; color: #fff;">
            <?= isset($_GET['update']) ? 'Ajustar' : 'Cadastrar' ?> Ads 2
        </h2>
        
        <form method="post">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
            <?php if(isset($data)): ?><input type="hidden" name="id" value="<?= $data['id'] ?>"><?php endif; ?>

            <label style="color: #3b82f6; font-size: 0.65rem; font-weight: 900; margin-left: 5px;">TÍTULO DO BANNER</label>
            <input type="text" name="title" class="input-premium" value="<?= $data['title'] ?? '' ?>" required>

            <label style="color: #3b82f6; font-size: 0.65rem; font-weight: 900; margin-left: 5px;">URL DA MÍDIA</label>
            <input type="text" name="url" class="input-premium" value="<?= $data['url'] ?? '' ?>" required>

            <button type="submit" name="<?= isset($_GET['update']) ? 'submitU' : 'submit' ?>" class="btn-save-royal">
                Confirmar Alterações
            </button>
        </form>
    </div>

<?php else: ?>
    <div class="top-nav">
        <div>
            <h1 style="font-weight: 900; font-size: 1.5rem; margin: 0;">Ads 2</h1>
        </div>
        <a href="?create" class="btn-create-lux"><i class="fas fa-plus"></i> Novo</a>
    </div>

    <div class="ads-grid">
        <?php 
        $res = $pdo->query("SELECT * FROM ads2 ORDER BY id DESC");
        while ($row = $res->fetch(PDO::FETCH_ASSOC)): 
            $is_video = preg_match('/\.(mp4|webm|ogg)$/i', $row['url']);
        ?>
            <div class="banner-card-lux">
                <div class="banner-visual">
                    <?php if ($is_video): ?>
                        <video src="<?= htmlspecialchars($row['url']) ?>" autoplay muted loop></video>
                    <?php else: ?>
                        <img src="<?= htmlspecialchars($row['url']) ?>" onerror="this.src='https://placehold.co/800x450/0f172a/3b82f6?text=Ads+2'">
                    <?php endif; ?>

                    <div class="banner-info-overlay">
                        <span class="banner-lux-title"><?= htmlspecialchars($row['title']) ?></span>
                    </div>
                </div>

                <div class="banner-actions-bar">
                    <span style="font-size: 0.65rem; color: #334155; font-weight: 800;">ID: #<?= $row['id'] ?></span>
                    <div style="display: flex; gap: 10px;">
                        <a href="?update=<?= $row['id'] ?>" class="action-btn-lux btn-edit-royal">
                            <i class="fas fa-edit"></i>
                        </a>
                        <button onclick="confirmarExclusao(<?= $row['id'] ?>)" class="action-btn-lux btn-del-royal">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
    </div>
<?php endif; ?>

</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 (isset($_SESSION['msg'])): ?>
        Swal.fire({
            icon: 'success', title: 'Sucesso', text: '<?= $_SESSION['msg'] ?>',
            background: '#020617', color: '#fff', confirmButtonColor: '#3b82f6'
        });
        <?php unset($_SESSION['msg']); ?>
    <?php endif; ?>

    function confirmarExclusao(id) {
        Swal.fire({
            title: 'Excluir?',
            icon: 'warning',
            showCancelButton: true,
            background: '#020617', color: '#fff',
            confirmButtonColor: '#ef4444', cancelButtonColor: '#1e293b',
            confirmButtonText: 'REMOVER', cancelButtonText: 'VOLTAR'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '<?= $base_file ?>?delete_confirmed=' + id;
            }
        });
    }
</script>

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