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

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

$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 ads (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title VARCHAR(100),
        url TEXT,
        display_title VARCHAR(200),
        title_color VARCHAR(7) DEFAULT '#ffffff',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
} catch(PDOException $e) {
    die("Erro crítico de conexão.");
}

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

// Lógica de Salvamento
if (isset($_POST['submit']) || isset($_POST['submitU'])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php"); exit();
    }
    
    $title_color = $_POST['title_color'] ?? '#ffffff';
    
    if (isset($_POST['submitU'])) {
        $stmt = $pdo->prepare("UPDATE ads SET title = ?, url = ?, display_title = ?, title_color = ? WHERE id = ?");
        $stmt->execute([$_POST['title'], $_POST['url'], $_POST['display_title'], $title_color, $_POST['id']]);
        $_SESSION['msg_success'] = "Banner atualizado!";
    } else {
        $stmt = $pdo->prepare("INSERT INTO ads (title, url, display_title, title_color) VALUES (?, ?, ?, ?)");
        $stmt->execute([$_POST['title'], $_POST['url'], $_POST['display_title'], $title_color]);
        $_SESSION['msg_success'] = "Banner adicionado!";
    }
    header("Location: $base_file"); exit;
}

if (isset($_GET['delete_confirmed'])) {
    $stmt = $pdo->prepare("DELETE FROM ads WHERE id = ?");
    $stmt->execute([$_GET['delete_confirmed']]);
    $_SESSION['msg_success'] = "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 */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #f8fafc !important;
    }

    .lua-icon, .fa-moon, .fa-sun, .navbar { 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-new {
        background: linear-gradient(135deg, #d946ef 0%, #a855f7 100%);
        color: #fff !important;
        padding: 12px 20px;
        border-radius: 12px;
        font-weight: 800;
        font-size: 0.8rem;
        text-transform: uppercase;
        box-shadow: 0 10px 20px rgba(217, 70, 239, 0.2);
        text-decoration: none !important;
    }

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

    .banner-card {
        background: #0f172a;
        border: 1px solid #1e293b;
        border-radius: 24px;
        overflow: hidden;
        position: relative;
        transition: transform 0.3s ease;
        width: 100%; /* Garante que o card não estoure */
    }

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

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

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

    .banner-tag {
        background: rgba(217, 70, 239, 0.2);
        color: #d946ef;
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 0.65rem;
        font-weight: 900;
        text-transform: uppercase;
        margin-bottom: 8px;
        display: inline-block;
    }

    .banner-title {
        font-size: 1.1rem;
        font-weight: 800;
        color: #fff;
        margin-bottom: 5px;
        display: block;
    }

    .banner-display-text {
        font-size: 0.85rem;
        font-weight: 500;
        opacity: 0.9;
    }

    /* AÇÕES DO CARD CENTRALIZADAS E PROTEGIDAS */
    .banner-actions {
        display: flex;
        padding: 15px 20px; /* Padding interno para não tocar as bordas */
        background: #0f172a;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid rgba(255,255,255,0.03);
    }

    .btn-action-premium {
        width: 45px;
        height: 45px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1rem;
        border: none;
        cursor: pointer;
        transition: 0.2s;
    }

    .btn-edit-lux { background: #1e293b; color: #3b82f6; }
    .btn-delete-lux { background: #1e293b; color: #ef4444; }

    /* FORMULÁRIO DE EDIÇÃO CENTRALIZADO */
    .form-lux {
        background: #070e1b;
        border-radius: 28px;
        padding: 25px;
        border: 1px solid #1e293b;
        max-width: 600px;
        margin: 0 auto; /* Centraliza no Desktop */
        width: 100%;
    }

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

    .btn-save-lux {
        width: 100%; background: #d946ef; color: #fff; padding: 20px;
        border-radius: 18px; font-weight: 800; text-transform: uppercase; border: none;
        box-shadow: 0 10px 20px rgba(217, 70, 239, 0.2);
        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 ads WHERE id = ?");
            $stmt->execute([$_GET['update']]);
            $data = $stmt->fetch(PDO::FETCH_ASSOC);
        }
    ?>
        <div class="top-nav" style="max-width: 600px; margin: 0 auto 25px auto;">
            <a href="<?= $base_file ?>" style="color: #64748b; font-weight: 700; text-decoration: none;">
                <i class="fas fa-arrow-left"></i> VOLTAR
            </a>
        </div>

        <div class="form-lux">
            <h2 style="font-weight: 800; margin-bottom: 25px;"><?= isset($_GET['update']) ? 'Editar' : 'Novo' ?> Banner</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: #d946ef; font-size: 0.7rem; font-weight: 800; margin-left: 5px;">IDENTIFICAÇÃO INTERNA</label>
                <input type="text" name="title" class="input-lux" value="<?= $data['title'] ?? '' ?>" required>

                <label style="color: #d946ef; font-size: 0.7rem; font-weight: 800; margin-left: 5px;">URL DA IMAGEM/VÍDEO</label>
                <input type="text" name="url" class="input-lux" value="<?= $data['url'] ?? '' ?>" required>

                <label style="color: #d946ef; font-size: 0.7rem; font-weight: 800; margin-left: 5px;">TEXTO DE EXIBIÇÃO (FRONT-END)</label>
                <input type="text" name="display_title" class="input-lux" value="<?= $data['display_title'] ?? '' ?>" required>

                <label style="color: #d946ef; font-size: 0.7rem; font-weight: 800; margin-left: 5px;">COR DO TEXTO</label>
                <input type="color" name="title_color" class="input-lux" style="height: 60px; padding: 5px;" value="<?= $data['title_color'] ?? '#ffffff' ?>">

                <button type="submit" name="<?= isset($_GET['update']) ? 'submitU' : 'submit' ?>" class="btn-save-lux">
                    Confirmar e Salvar
                </button>
            </form>
        </div>

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

        <div class="ads-grid">
            <?php 
            $res = $pdo->query("SELECT * FROM ads 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">
                    <div class="banner-preview-container">
                        <?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/600x337/0f172a/334155?text=Preview+Indisponível'">
                        <?php endif; ?>

                        <div class="banner-overlay">
                            <span class="banner-tag">Ativo</span>
                            <span class="banner-title"><?= htmlspecialchars($row['title']) ?></span>
                            <span class="banner-display-text" style="color: <?= $row['title_color'] ?>;">
                                <?= htmlspecialchars($row['display_title']) ?>
                            </span>
                        </div>
                    </div>

                    <div class="banner-actions">
                        <span style="font-size: 0.65rem; color: #475569; font-weight: 700;">ID: #<?= $row['id'] ?></span>
                        <div style="display: flex; gap: 10px;">
                            <a href="?update=<?= $row['id'] ?>" class="btn-action-premium btn-edit-lux">
                                <i class="fas fa-pen-nib"></i>
                            </a>
                            <button onclick="confirmarExclusao(<?= $row['id'] ?>)" class="btn-action-premium btn-delete-lux">
                                <i class="fas fa-trash-alt"></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_success'])): ?>
        Swal.fire({
            icon: 'success', title: 'Sucesso', text: '<?= $_SESSION['msg_success'] ?>',
            background: '#020617', color: '#fff', confirmButtonColor: '#d946ef'
        });
        <?php unset($_SESSION['msg_success']); ?>
    <?php endif; ?>

    function confirmarExclusao(id) {
        Swal.fire({
            title: 'Excluir este banner?',
            text: "A imagem sairá imediatamente do aplicativo.",
            icon: 'warning',
            showCancelButton: true,
            background: '#020617', color: '#fff',
            confirmButtonColor: '#ef4444', cancelButtonColor: '#1e293b',
            confirmButtonText: 'SIM, APAGAR', cancelButtonText: 'CANCELAR'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '<?= $base_file ?>?delete_confirmed=' + id;
            }
        });
    }
</script>

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