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

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

$db_path = __DIR__ . '/api/db/db_ads3.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 = "ads3.php";

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 Vertical 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 Vertical 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 EVITAR QUEBRA DE LAYOUT */
    * { box-sizing: border-box; }

    :root {
        --bg-main: #020617;
        --bg-card: #0f172a;
        --accent: #d946ef;
        --text-dim: #94a3b8;
        --border: #1e293b;
    }

    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: var(--bg-main) !important; 
        color: #f8fafc !important;
        font-family: 'Inter', sans-serif;
    }

    .lua-icon, .fa-moon, .fa-sun, .navbar { display: none !important; }

    /* FORMULÁRIO CORRIGIDO */
    .form-lux {
        background: var(--bg-card);
        border-radius: 24px;
        padding: 25px;
        border: 1px solid var(--border);
        max-width: 500px;
        margin: 0 auto;
        width: 95%; /* Margem de segurança nas laterais */
    }

    .input-lux {
        width: 100%;
        background: #020617 !important;
        border: 1px solid var(--border) !important;
        color: #fff !important;
        padding: 15px;
        border-radius: 12px;
        margin-top: 5px;
    }

    /* BOTÃO SALVAR CENTRALIZADO E DENTRO DOS LIMITES */
    .btn-save-lux {
        width: 100%;
        background: linear-gradient(135deg, #d946ef 0%, #a855f7 100%);
        color: #fff;
        padding: 16px;
        border-radius: 12px;
        font-weight: 800;
        text-transform: uppercase;
        border: none;
        cursor: pointer;
        margin-top: 20px;
        display: block;
    }

    /* GRID DE CARDS */
    .ads-grid {
        display: flex;
        flex-direction: column;
        gap: 25px;
        max-width: 450px;
        margin: 0 auto;
        padding-bottom: 50px;
    }

    .banner-card {
        background: var(--bg-card);
        border: 1px solid var(--border);
        border-radius: 28px;
        overflow: hidden;
        width: 100%;
    }

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

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

    /* ÁREA DE AÇÕES CORRIGIDA (CENTRALIZADA) */
    .banner-actions {
        display: flex;
        padding: 15px 20px; /* Padding igual nas laterais */
        background: var(--bg-card);
        justify-content: space-between; /* Distribui o ID e os botões */
        align-items: center;
        border-top: 1px solid var(--border);
    }

    .action-buttons-group {
        display: flex;
        gap: 12px; /* Espaço entre editar e excluir */
    }

    .btn-action-premium {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        cursor: pointer;
        transition: 0.2s;
    }

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

    .top-nav {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 20px auto;
        max-width: 450px;
    }

    .btn-create-new {
        background: var(--accent);
        color: #fff !important;
        padding: 10px 20px;
        border-radius: 10px;
        font-weight: 700;
        text-decoration: none !important;
    }
</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">
            <a href="<?= $base_file ?>" style="color: var(--text-dim); font-weight: 700; text-decoration: none;">
                <i class="fas fa-chevron-left"></i> VOLTAR
            </a>
        </div>

        <div class="form-lux">
            <div style="text-align: center; margin-bottom: 25px;">
                <h2 style="font-weight: 900; color:#fff;"><?= isset($_GET['update']) ? 'Editar' : 'Novo' ?> Ads 3</h2>
            </div>

            <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; ?>

                <div style="margin-bottom: 15px;">
                    <label style="color:#fff; font-size: 0.75rem; font-weight: 700;">TÍTULO INTERNO</label>
                    <input type="text" name="title" class="input-lux" value="<?= $data['title'] ?? '' ?>" required>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="color:#fff; font-size: 0.75rem; font-weight: 700;">URL DA MÍDIA (VERTICAL)</label>
                    <input type="text" name="url" class="input-lux" value="<?= $data['url'] ?? '' ?>" required>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="color:#fff; font-size: 0.75rem; font-weight: 700;">TEXTO DE EXIBIÇÃO</label>
                    <input type="text" name="display_title" class="input-lux" value="<?= $data['display_title'] ?? '' ?>" required>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="color:#fff; font-size: 0.75rem; font-weight: 700;">COR DO TEXTO</label>
                    <input type="color" name="title_color" class="input-lux" style="height: 50px; padding: 5px;" value="<?= $data['title_color'] ?? '#ffffff' ?>">
                </div>

                <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.3rem;">Ads Vertical</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/1080x1920/0f172a/334155?text=ADS3+VERTICAL'">
                        <?php endif; ?>

                        <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 30px 20px; background: linear-gradient(to top, rgba(2, 6, 23, 1) 0%, transparent 100%);">
                            <span style="background: var(--accent); color: #fff; padding: 3px 8px; border-radius: 5px; font-size: 0.6rem; font-weight: 800;">VERTICAL</span>
                            <h3 style="font-size: 1.1rem; font-weight: 800; margin-top: 8px; color: #fff;"><?= htmlspecialchars($row['title']) ?></h3>
                            <p style="color: <?= $row['title_color'] ?>; font-weight: 500; font-size: 0.85rem;"><?= htmlspecialchars($row['display_title']) ?></p>
                        </div>
                    </div>

                    <div class="banner-actions">
                        <span style="font-size: 0.75rem; color: var(--text-dim); font-weight: 700;">#<?= $row['id'] ?></span>
                        <div class="action-buttons-group">
                            <a href="?update=<?= $row['id'] ?>" class="btn-action-premium btn-edit-lux">
                                <i class="fas fa-edit"></i>
                            </a>
                            <button onclick="confirmarExclusao(<?= $row['id'] ?>)" class="btn-action-premium btn-delete-lux">
                                <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_success'])): ?>
        Swal.fire({
            icon: 'success', title: 'Sucesso', text: '<?= $_SESSION['msg_success'] ?>',
            background: '#0f172a', color: '#fff', confirmButtonColor: '#d946ef'
        });
        <?php unset($_SESSION['msg_success']); ?>
    <?php endif; ?>

    function confirmarExclusao(id) {
        Swal.fire({
            title: 'Excluir?',
            text: "Remover este banner vertical agora?",
            icon: 'warning',
            showCancelButton: true,
            background: '#0f172a', color: '#fff',
            confirmButtonColor: '#ef4444', cancelButtonColor: '#1e293b',
            confirmButtonText: 'APAGAR', cancelButtonText: 'NÃO'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '<?= $base_file ?>?delete_confirmed=' + id;
            }
        });
    }
</script>

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