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

// Nome da tabela
$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);

/**
 * Anti-lock (recomendado) - se $adb for SQLite3
 * (Se $adb não for SQLite3, isso não quebra; só ignora caso dê warning)
 */
if (isset($adb) && $adb instanceof SQLite3) {
    $adb->busyTimeout(15000);
    $adb->exec("PRAGMA journal_mode = WAL;");
    $adb->exec("PRAGMA synchronous = NORMAL;");
    $adb->exec("PRAGMA busy_timeout = 15000;");
}

// Criação da tabela caso não exista
$adb->exec("CREATE TABLE IF NOT EXISTS {$table_name}(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    title VARCHAR(100), 
    url TEXT, 
    owner VARCHAR(100)
)");

// ✅ Lógica de Deletar (coloquei antes, para processar rápido)
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];

    $ok = $adb->exec("DELETE FROM {$table_name} WHERE id={$id}");

    if (!$ok) {
        // Se der erro, você vai ver na tela (ajuda muito a diagnosticar)
        die("Erro ao deletar: " . $adb->lastErrorMsg());
    }

    echo "<script>window.location.href='{$base_file}';</script>";
    exit;
}

// Chamada da tabela
$res = $adb->query("SELECT * FROM {$table_name}");

// Chamada para atualização
$rowU = null;
if (isset($_GET['update'])) {
    $idU = (int)$_GET['update'];
    $resU = $adb->query("SELECT * FROM {$table_name} WHERE id='{$idU}'");
    $rowU = $resU ? $resU->fetchArray(SQLITE3_ASSOC) : null;
}

// Função para validar mídia
function isMediaUrl($url) {
    $extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'webm', 'ogg'];
    $path = parse_url($url, PHP_URL_PATH);
    $path_info = pathinfo($path ?? '');
    return isset($path_info['extension']) && in_array(strtolower($path_info['extension']), $extensions);
}

// Lógica de Atualizar
if (isset($_POST['submitU'])) {
    if (isMediaUrl($_POST['url'])) {
        $id = (int)($_POST['id'] ?? 0);
        $title = SQLite3::escapeString($_POST['title']);
        $url = SQLite3::escapeString($_POST['url']);

        $adb->exec("UPDATE {$table_name} SET title='{$title}', url='{$url}' WHERE id='{$id}'");
        echo "<script>window.location.href='{$base_file}';</script>";
        exit;
    } else {
        echo "<script>alert('Insira um link de mídia válido!');</script>";
    }
}

// Lógica de Inserir
if (isset($_POST['submit'])) {
    if (isMediaUrl($_POST['url'])) {
        $admin_name = $_SESSION['name'] ?? 'ADM';
        $title = SQLite3::escapeString($_POST['title']);
        $url = SQLite3::escapeString($_POST['url']);
        $owner = SQLite3::escapeString($admin_name);

        $adb->exec("INSERT INTO {$table_name}(title, url, owner) VALUES('{$title}', '{$url}', '{$owner}')");
        echo "<script>window.location.href='{$base_file}';</script>";
        exit;
    } else {
        echo "<script>alert('Insira um link de mídia válido!');</script>";
    }
}
?>

<style>
    :root {
        --neon-blue: #00d4ff;
        --dark-bg: #06090c;
        --card-glass: rgba(13, 18, 24, 0.95);
        --border-glass: rgba(0, 212, 255, 0.2);
    }

    html, body, 
    #wrapper, 
    #content-wrapper, 
    #content, 
    .container-fluid,
    .bg-white,
    .bg-light {
        background-color: var(--dark-bg) !important;
        color: #f8f9fc !important;
    }

    body { font-family: 'Poppins', sans-serif; }

    .card-futuristic {
        background: var(--card-glass) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--border-glass) !important;
        border-radius: 15px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    }

    .card-header-futuristic {
        background: rgba(0, 212, 255, 0.03) !important;
        border-bottom: 1px solid var(--border-glass) !important;
        padding: 1.5rem !important;
    }

    .card-header-futuristic h2, .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-blue) !important;
        text-shadow: 0 0 10px var(--neon-blue);
        margin: 0;
        text-transform: uppercase;
    }

    .table-modern {
        color: #e0e0e0 !important;
        border-collapse: separate;
        border-spacing: 0 10px;
        width: 100%;
    }

    .table-modern thead th {
        border: none !important;
        color: var(--neon-blue) !important;
        text-transform: uppercase;
        font-size: 0.75rem;
    }

    .table-modern tbody tr {
        background: rgba(255, 255, 255, 0.02);
        transition: 0.3s;
    }

    .table-modern td {
        border: none !important;
        padding: 15px !important;
        vertical-align: middle !important;
    }

    .url-link {
        color: #888;
        text-decoration: none;
        max-width: 180px;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 0.8rem;
        transition: 0.3s;
    }

    .url-link:hover {
        color: var(--neon-blue);
        text-shadow: 0 0 8px var(--neon-blue);
        text-decoration: none;
    }

    .preview-media {
        border: 1px solid var(--neon-blue);
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0, 212, 255, 0.2);
        max-width: 100px;
    }

    .form-control-futuristic {
        background: rgba(0, 0, 0, 0.5) !important;
        border: 1px solid var(--border-glass) !important;
        color: #fff !important;
        padding: 12px;
        border-radius: 8px;
    }

    .btn-neon {
        background: transparent;
        border: 1px solid var(--neon-blue);
        color: var(--neon-blue) !important;
        font-family: 'Orbitron', sans-serif;
        padding: 10px 20px;
        border-radius: 8px;
        transition: 0.4s;
    }

    .btn-neon:hover {
        background: var(--neon-blue);
        color: #000 !important;
        box-shadow: 0 0 20px var(--neon-blue);
    }
</style>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content card-futuristic">
            <div class="modal-header border-0">
                <h2 style="color:var(--neon-blue); font-family: 'Orbitron';">Confirmar</h2>
            </div>
            <div class="modal-body">Deseja realmente excluir este anúncio?</div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary" data-dismiss="modal" data-bs-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok" href="#">Deletar</a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid pt-4 px-5">

<?php if (isset($_GET['create']) || isset($_GET['update'])): 
    $isUpdate = isset($_GET['update']);
?>
    <div class="col-md-7 mx-auto">
        <div class="card card-futuristic shadow">
            <div class="card-header-futuristic text-center">
                <h2>
                    <i class="fas <?php echo $isUpdate ? 'fa-edit' : 'fa-plus-circle'; ?> mr-2"></i>
                    <?php echo $isUpdate ? 'Editar Anúncio' : 'Novo Anúncio'; ?>
                </h2>
            </div>
            <div class="card-body p-4">
                <form method="post">
                    <?php if($isUpdate): ?>
                        <input type="hidden" name="id" value="<?= (int)$_GET['update'] ?>">
                    <?php endif; ?>

                    <div class="form-group mb-4">
                        <label class="small text-uppercase" style="color:var(--neon-blue)">Título</label>
                        <input type="text" class="form-control form-control-futuristic" name="title"
                               value="<?php echo $isUpdate && $rowU ? htmlspecialchars($rowU['title']) : ''; ?>" required>
                    </div>

                    <div class="form-group mb-4">
                        <label class="small text-uppercase" style="color:var(--neon-blue)">URL da Mídia</label>
                        <input type="text" class="form-control form-control-futuristic" name="url"
                               value="<?php echo $isUpdate && $rowU ? htmlspecialchars($rowU['url']) : ''; ?>" required>
                    </div>

                    <div class="text-center">
                        <button type="submit" name="<?php echo $isUpdate ? 'submitU' : 'submit'; ?>" class="btn btn-neon btn-block">SALVAR</button>
                        <a href="<?php echo $base_file; ?>" class="btn btn-link text-white-50 mt-2">Voltar</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

<?php else: ?>
    <div class="card card-futuristic shadow mb-4">
        <div class="card-header-futuristic d-flex justify-content-between align-items-center">
            <h6><i class="fas fa-broadcast-tower mr-2"></i> CENTRAL DE ANÚNCIOS</h6>
            <a href="?create" class="btn btn-neon btn-sm"><i class="fas fa-plus mr-1"></i> NOVO ANÚNCIO</a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-modern">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Titulo</th>
                            <th>Add Url</th>
                            <th>Registrado Por</th>
                            <th>Pre-Visualização</th>
                            <th class="text-center">Editar</th>
                            <th class="text-center">Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $res->fetchArray(SQLITE3_ASSOC)): ?>
                            <tr>
                                <td style="color:var(--neon-blue)">#<?= (int)$row['id'] ?></td>
                                <td class="font-weight-bold"><?= htmlspecialchars($row['title'] ?? '') ?></td>
                                <td>
                                    <a href="<?= htmlspecialchars($row['url'] ?? '') ?>" target="_blank" class="url-link"
                                       title="Clique para abrir: <?= htmlspecialchars($row['url'] ?? '') ?>">
                                        <?= htmlspecialchars($row['url'] ?? '') ?>
                                    </a>
                                </td>
                                <td>
                                    <span class="badge" style="border:1px solid rgba(255,255,255,0.1); color:#fff; background: transparent;">
                                        <?= htmlspecialchars($row['owner'] ?? '') ?>
                                    </span>
                                </td>
                                <td>
                                    <?php
                                        $url = $row['url'] ?? '';
                                        $isVideo = (stripos($url, '.mp4') !== false || stripos($url, '.webm') !== false);
                                    ?>
                                    <?php if ($isVideo): ?>
                                        <video class="preview-media" src="<?= htmlspecialchars($url) ?>" muted loop
                                               onmouseover="this.play()" onmouseout="this.pause()"></video>
                                    <?php else: ?>
                                        <img class="preview-media" src="<?= htmlspecialchars($url) ?>" onerror="this.src='img/logo.png'">
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <a href="?update=<?= (int)$row['id'] ?>" title="Editar">
                                        <i class="fas fa-edit" style="font-size:20px; color:var(--neon-blue); text-shadow: 0 0 10px var(--neon-blue);"></i>
                                    </a>
                                </td>
                                <td class="text-center">
                                    <a href="#"
                                       data-href="?delete=<?= (int)$row['id'] ?>"
                                       data-toggle="modal" data-target="#confirm-delete"
                                       data-bs-toggle="modal" data-bs-target="#confirm-delete"
                                       title="Deletar">
                                        <i class="fas fa-trash-alt" style="font-size:20px; color:#ff3e3e; text-shadow: 0 0 10px #ff3e3e;"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php endif; ?>
</div>

<script>
/**
 * ✅ Funciona com Bootstrap 4 e 5, com ou sem jQuery
 * Apenas coloca o link correto no botão "Deletar" do modal
 */
document.addEventListener('DOMContentLoaded', function () {
    var modal = document.getElementById('confirm-delete');
    var btnOk = modal ? modal.querySelector('.btn-ok') : null;

    function bindDeleteLinks() {
        var links = document.querySelectorAll('[data-href][data-target="#confirm-delete"], [data-href][data-bs-target="#confirm-delete"]');
        links.forEach(function (link) {
            link.addEventListener('click', function () {
                var href = link.getAttribute('data-href');
                if (btnOk && href) btnOk.setAttribute('href', href);
            });
        });
    }

    bindDeleteLinks();
});
</script>

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