<?php
/*
 * 🎬 @ Gerenciador de Anúncios 
 * 🚀 @ Versão: 1.0.2
 * 📅 @ Atualizado: 17/06/2024
 */

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

include "includes/header.php";
$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);
$adb->exec("CREATE TABLE IF NOT EXISTS " . $table_name . "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), url TEXT)");
$res = $adb->query("SELECT * FROM " . $table_name);
$resU = @$adb->query("SELECT * FROM " . $table_name . " WHERE id='" . $_GET["update"] . "'");
$rowU = @$resU->fetchArray();

if (isset($_POST["submitU"])) {
    $adb->exec("UPDATE " . $table_name . " SET title='" . $_POST["title"] . "',url='" . $_POST["url"] . "' WHERE id='" . $_POST["id"] . "'");
    $adb->close();
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}

if (isset($_POST["submit"])) {
    $adb->exec("INSERT INTO " . $table_name . "(title, url) VALUES('" . $_POST["title"] . "', '" . $_POST["url"] . "')");
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}

if (isset($_GET["delete"])) {
    $adb->exec("DELETE FROM " . $table_name . " WHERE id=" . $_GET["delete"]);
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}

echo '<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content bg-dark text-white">
            <div class="modal-header bg-danger">
                <h2 class="modal-title">⚠️ Confirmar Exclusão</h2>
            </div>
            <div class="modal-body">
                <p class="lead">🗑️ Você realmente deseja excluir este anúncio?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">❌ Cancelar</button>
                <a class="btn btn-danger btn-ok">✅ Confirmar</a>
            </div>
        </div>
    </div>
</div>';

if (isset($_GET["create"])) {
    echo '<div class="col-md-8 mx-auto">
            <div class="card bg-primary text-white">
                <div class="card-header bg-info">
                    <center>
                        <h2><i class="fa fa-bullhorn"></i> 🆕 Adicionar Anúncio</h2>
                    </center>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="form-group">
                            <label class="form-label">📛 Título do Anúncio</label>
                            <input class="form-control" type="text" name="title" placeholder="Digite o título" required>
                        </div>
                        <div class="form-group mt-3">
                            <label class="form-label">🌐 URL da Imagem/Vídeo</label>
                            <input class="form-control" type="text" name="url" placeholder="https://exemplo.com/anuncio.jpg" required>
                            <small class="form-text text-muted">Formatos suportados: GIF, PNG, JPG, SVG, MP4, WEBM</small>
                        </div>  
                        <div class="col-12 text-center mt-4">
                            <button type="submit" name="submit" class="btn btn-success btn-lg">
                                <i class="fa fa-paper-plane"></i> 📤 Publicar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>';
} elseif (isset($_GET["update"])) {
    echo '<div class="col-md-8 mx-auto">
            <div class="card bg-primary text-white">
                <div class="card-header bg-warning">
                    <center>
                        <h2><i class="fa fa-edit"></i> ✏️ Editar Anúncio</h2>
                    </center>
                </div>
                <div class="card-body">
                    <form method="post">
                        <input type="hidden" class="form-control" name="id" value="' . $_GET["update"] . '">
                        <div class="form-group">
                            <label class="form-label">📛 Título do Anúncio</label>
                            <input type="text" name="title" class="form-control" value="' . $rowU["title"] . '" required>
                        </div>
                        <div class="form-group mt-3">
                            <label class="form-label">🌐 URL da Imagem/Vídeo</label>
                            <input type="text" class="form-control" name="url" value="' . $rowU["url"] . '" required>
                            <small class="form-text text-muted">Formatos suportados: GIF, PNG, JPG, SVG, MP4, WEBM</small>
                        </div>  
                        <div class="col-12 text-center mt-4">
                            <button type="submit" name="submitU" class="btn btn-warning btn-lg">
                                <i class="fa fa-save"></i> 💾 Salvar Alterações
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>';
} else {
    echo '<div class="col-md-12 mx-auto">
            <div class="card bg-primary text-white">
                <div class="card-header bg-info">
                    <center>
                        <h2><i class="fa fa-ad"></i> 📢 Gerenciador de Anúncios</h2>
                        <a id="button" href="./' . $base_file . '?create" class="btn btn-success mt-2">
                            <i class="fa fa-plus"></i> 🆕 Adicionar Anúncio
                        </a>
                    </center>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-dark table-hover table-striped">
                            <thead class="bg-secondary">
                                <tr>
                                    <th>#️⃣ ID</th>
                                    <th>📛 Título</th>
                                    <th>🔗 URL</th>
                                    <th>👁️ Pré-visualização</th>
                                    <th>⚙️ Ações</th>
                                </tr>
                            </thead>
                            <tbody>';

    while ($row = $res->fetchArray()) {
        $mediaType = '';
        if (strpos($row["url"], ".mp4") !== false || strpos($row["url"], ".webm") !== false || strpos($row["url"], ".ogg") !== false) {
            $mediaType = 'video';
            $rowClass = 'class="table-danger"';
        } elseif (strpos($row["url"], ".gif") !== false) {
            $mediaType = 'gif';
            $rowClass = 'class="table-warning"';
        } else {
            $mediaType = 'image';
            $rowClass = '';
        }

        echo '<tr ' . $rowClass . '>
                <td>' . $row["id"] . '</td>
                <td>' . $row["title"] . '</td>
                <td><a href="' . $row["url"] . '" target="_blank">🔗 Ver URL</a></td>
                <td>';

        if ($mediaType === 'video') {
            echo '<video src="' . $row["url"] . '" width="150" controls muted loop></video>';
        } elseif ($mediaType === 'gif') {
            echo '<img src="' . $row["url"] . '" width="150" class="img-thumbnail">';
        } else {
            echo '<img src="' . $row["url"] . '" width="150" class="img-thumbnail">';
        }

        echo '</td>
                <td>
                    <a class="btn btn-info btn-sm" href="' . $base_file . '?update=' . $row["id"] . '">
                        <i class="fa fa-edit"></i> ✏️
                    </a>
                    <a class="btn btn-danger btn-sm" href="#" data-href="' . $base_file . '?delete=' . $row["id"] . '" data-toggle="modal" data-target="#confirm-delete">
                        <i class="fa fa-trash"></i> 🗑️
                    </a>
                </td>
            </tr>';
    }

    echo '</tbody>
                    </table>
                </div>
            </div>
        </div>';
}

include "includes/footer.php";
echo '<script type="text/javascript">
    // Update alert
    $("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
        $("#success-alert").alert("close");
    });

    // Delete modal
    $("#confirm-delete").on("show.bs.modal", function(e) {
        $(this).find(".btn-ok").attr("href", $(e.relatedTarget).data("href"));
    });
</script>
</body>
</html>';