<?php
/*
 * @ https://hospedagem.matrixch.store 
 * @ PHP 7.4
 * @ Decoder version: 1.0.2
 * @ Release: 17/06/2024
*/

header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

include "includes/header.php";
$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Initialize database table
$adb->exec("CREATE TABLE IF NOT EXISTS " . $table_name . "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), url TEXT)");

// Handle form submissions
if (isset($_POST["submitU"])) {
    $adb->exec("UPDATE " . $table_name . " SET title='" . $_POST["title"] . "',url='" . $_POST["url"] . "' WHERE id='" . $_POST["id"] . "'");
    echo "<script>window.location.href='ads.php?status=5';</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?status=5';</script>";
    exit;
}

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

// Processar exclusão de todos os registros
if (isset($_GET["deleteall"])) {
    $adb->exec("DELETE FROM " . $table_name);
    echo "<script>window.location.href='ads.php?status=7';</script>";
    exit;
}

// Verificar se existem anúncios
$countQuery = $adb->query("SELECT COUNT(*) as total FROM " . $table_name);
$countRow = $countQuery->fetchArray();
$hasAds = ($countRow['total'] > 0);
?>

<div class="container-fluid py-4">
    <?php if (isset($_GET['status'])): ?>
        <?php if ($_GET['status'] == 5): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Operação realizada com sucesso!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php elseif ($_GET['status'] == 6): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Anúncio excluído com sucesso!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php elseif ($_GET['status'] == 7): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Todos os anúncios foram excluídos com sucesso!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
    <?php endif; ?>

    <?php if (isset($_GET["create"])): ?>
        <!-- Create New Ad Form -->
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-plus-circle me-2"></i>Adicionar anúncio</h4>
                            <a href="<?= $base_file ?>" class="btn btn-sm btn-light">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <div class="mb-3">
                                <label for="title" class="form-label">Título</label>
                                <input type="text" class="form-control" name="title" required>
                            </div>
                            <div class="mb-3">
                                <label for="url" class="form-label">Image/Video URL</label>
                                <input type="text" class="form-control" name="url" placeholder="URL for GIF, PNG, JPG, SVG, MP4, WEBM" required>
                                <small class="text-muted">Formatos suportados: Images (GIF, PNG, JPG, SVG) and Videos (MP4, WEBM)</small>
                            </div>
                            <div class="text-center mt-4">
                                <button type="submit" name="submit" class="btn btn-primary px-4">
                                    <i class="fas fa-save me-2"></i>Salvar anúncio
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    <?php elseif (isset($_GET["update"])): 
        $resU = $adb->query("SELECT * FROM " . $table_name . " WHERE id='" . $_GET["update"] . "'");
        $rowU = $resU->fetchArray();
        ?>
        <!-- Edit Ad Form -->
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-edit me-2"></i>Editar anúncio</h4>
                            <a href="<?= $base_file ?>" class="btn btn-sm btn-light">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="id" value="<?= $_GET['update'] ?>">
                            <div class="mb-3">
                                <label for="title" class="form-label">Título</label>
                                <input type="text" class="form-control" name="title" value="<?= htmlspecialchars($rowU['title']) ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="url" class="form-label">Image/Video URL</label>
                                <input type="text" class="form-control" name="url" value="<?= htmlspecialchars($rowU['url']) ?>" required>
                            </div>
                            <div class="text-center mt-4">
                                <button type="submit" name="submitU" class="btn btn-primary px-4">
                                    <i class="fas fa-save me-2"></i>Atualizar anúncio
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    <?php else: ?>
        <!-- Main Ad Listing -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-ad me-2"></i>Gestão de Publicidade</h4>
                            <div>
                                <?php if ($hasAds): ?>
                                <a href="<?= $base_file ?>?deleteall" class="btn btn-sm btn-danger me-2" onclick="return confirm('Are you sure you want to delete ALL advertisements? This action cannot be undone.');">
                                    <i class="fas fa-trash-alt me-1"></i> Remover tudo
                                </a>
                                <?php endif; ?>
                                <a href="<?= $base_file ?>?create" class="btn btn-sm btn-light">
                                    <i class="fas fa-plus me-1"></i> Adicionar novo
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if ($hasAds): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th width="5%">ID</th>
                                        <th width="20%">Título</th>
                                        <th width="30%">URL</th>
                                        <th width="25%">Visualização</th>
                                        <th width="20%" class="text-center">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $res = $adb->query("SELECT * FROM " . $table_name);
                                    while ($row = $res->fetchArray()): 
                                        $isVideo = strpos($row["url"], ".mp4") !== false || 
                                                  strpos($row["url"], ".webm") !== false || 
                                                  strpos($row["url"], ".ogg") !== false;
                                    ?>
                                    <tr>
                                        <td><?= $row["id"] ?></td>
                                        <td class="<?= $isVideo ? 'text-danger' : '' ?>"><?= htmlspecialchars($row["title"]) ?></td>
                                        <td><code><?= htmlspecialchars($row["url"]) ?></code></td>
                                        <td>
                                            <?php if ($isVideo): ?>
                                                <video src="<?= htmlspecialchars($row['url']) ?>" width="150" controls muted loop></video>
                                            <?php elseif (strpos($row["url"], ".jpg") !== false || 
                                                        strpos($row["url"], ".jpeg") !== false || 
                                                        strpos($row["url"], ".png") !== false || 
                                                        strpos($row["url"], ".gif") !== false): ?>
                                                <img src="<?= htmlspecialchars($row['url']) ?>" width="150" class="img-thumbnail">
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <a href="<?= $base_file ?>?update=<?= $row['id'] ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="<?= $base_file ?>?delete=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this advertisement? This action cannot be undone.');">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div class="text-center py-4">
                            <i class="fas fa-ad fa-3x text-muted mb-3"></i>
                            <p class="text-muted">Nenhum anúncio encontrado. Clique em "Adicionar novo" para criar um.</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
// Fechar alertas automaticamente
setTimeout(function() {
    document.querySelectorAll('.alert').forEach(function(alert) {
        var closeButton = alert.querySelector('.btn-close');
        if (closeButton) {
            closeButton.click();
        }
    });
}, 3000);
</script>

<?php 
include "includes/footer.php";
?>