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

// Configuración de la base de datos SQLite
$db_path = 'api/ads.db';

// Definición de funciones auxiliares
function sanitizeString($str) {
    return htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
}

function sanitizeAndValidateUrl($url) {
    $url = filter_var($url, FILTER_SANITIZE_URL);
    if (filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    return $url;
}

function isImage($url) {
    $ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
    return in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
}

// Inicializar variables
$res = false;
$error = null;
$success = null;
$editingAd = null;

try {
    // Crear o conectar a la base de datos SQLite
    $db = new SQLite3($db_path);

    // Verificar si la tabla existe y tiene la estructura correcta
    $tableCheck = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='ads'");
    if (!$tableCheck->fetchArray()) {
        // La tabla no existe, la creamos
        $db->exec('CREATE TABLE ads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT,
            url TEXT,
            created_on TEXT
        )');
    }

    // Manejar la eliminación de anuncios
    if (isset($_GET['delete'])) {
        $id = filter_var($_GET['delete'], FILTER_SANITIZE_NUMBER_INT);
        $stmt = $db->prepare('DELETE FROM ads WHERE id = :id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        if ($stmt->execute()) {
            $success = "Anuncio eliminado correctamente.";
        } else {
            $error = "Error al eliminar el anuncio.";
        }
    }

    // Manejar la edición de anuncios
    if (isset($_GET['edit'])) {
        $id = filter_var($_GET['edit'], FILTER_SANITIZE_NUMBER_INT);
        $stmt = $db->prepare('SELECT * FROM ads WHERE id = :id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $editingAd = $result->fetchArray(SQLITE3_ASSOC);
    }

    // Manejar actualización de anuncios existentes
    if(isset($_POST['submit']) && isset($_POST['id'])){
        $title = sanitizeString($_POST['title']);
        $url = sanitizeAndValidateUrl($_POST['url']);
        
        if ($url === false) {
            $error = "URL inválida. Por favor, introduce una URL válida.";
        } else {
            $id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
            $stmt = $db->prepare('UPDATE ads SET title = :title, url = :url WHERE id = :id');
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':url', $url, SQLITE3_TEXT);
            
            if ($stmt->execute()) {
                $success = "Anuncio actualizado correctamente.";
                $editingAd = null;
            } else {
                $error = "Error al actualizar el anuncio: " . $db->lastErrorMsg();
            }
        }
    }

    // Obtener todos los anuncios
    $res = $db->query('SELECT * FROM ads ORDER BY created_on DESC');
    if ($res === false) {
        throw new Exception($db->lastErrorMsg());
    }

} catch (Exception $e) {
    $error = "Error de base de datos: " . $e->getMessage();
    $res = false;
}
?>
<!-- Modal para Editar Anuncio -->
<div class="modal fade" id="editAdModal" tabindex="-1" role="dialog" aria-labelledby="editAdModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content bg-dark text-white"> <!-- fondo oscuro y texto blanco -->
            <div class="modal-header bg-warning text-dark"> <!-- para que el header destaque y el texto sea legible -->
                <h5 class="modal-title" id="editAdModalLabel"><i class="fas fa-edit"></i> Editar Anuncio</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"> <!-- cerrar con texto blanco -->
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="id" id="editAdId">
                    <div class="form-group">
                        <label for="editAdTitle" class="text-white">Título del Anuncio</label>
                        <input class="form-control bg-secondary text-white border-0" name="title" id="editAdTitle" type="text" required>
                    </div>
                    <div class="form-group">
                        <label for="editAdUrl" class="text-white">URL del Anuncio</label>
                        <input class="form-control bg-secondary text-white border-0" name="url" id="editAdUrl" type="url" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" name="submit" class="btn btn-primary">Guardar Cambios</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!--Contenido Principal-->
<div class="container-fluid">
    <div class="mx-auto" style="max-width: 900px;">
        <div class="card bg-dark border-left-primary shadow h-100 card shadow mb-4 text-white"> <!-- fondo oscuro y texto blanco -->
            <div class="card-header py-3 bg-secondary text-white">
                <h6 class="m-0 font-weight-bold"><i class="fas fa-user"></i> Aquí puedes editar o eliminar los Anuncios Manuales</h6>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?= $error ?>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Cerrar">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <?php endif; ?>

                <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?= $success ?>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Cerrar">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <?php endif; ?>
                <div class="table-responsive">
                    <table class="table table-hover table-dark"> <!-- tabla oscura -->
                        <thead>
                            <tr>
                                <th>Título</th>
                                <th>Imagen</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($res && $res->fetchArray(SQLITE3_ASSOC)): ?>
                                <?php $res->reset(); ?>
                                <?php while ($ad = $res->fetchArray(SQLITE3_ASSOC)): ?>
                                    <tr>
                                        <td class="align-middle"><?= htmlspecialchars($ad['title']) ?></td>
                                        <td class="align-middle">
                                            <?php if (isImage($ad['url'])): ?>
                                                <img src="<?= htmlspecialchars($ad['url']) ?>" 
                                                     class="img-thumbnail" 
                                                     style="max-width: 150px; max-height: 100px;"
                                                     alt="<?= htmlspecialchars($ad['title']) ?>">
                                            <?php else: ?>
                                                <a href="<?= htmlspecialchars($ad['url']) ?>" 
                                                   target="_blank" 
                                                   class="btn btn-sm btn-info">
                                                   <i class="fas fa-external-link-alt"></i> Ver enlace
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                        <td class="align-middle text-nowrap">
                                            <button class="btn btn-sm btn-primary mr-2 edit-btn"
                                                    data-id="<?= $ad['id'] ?>"
                                                    data-title="<?= htmlspecialchars($ad['title']) ?>"
                                                    data-url="<?= htmlspecialchars($ad['url']) ?>">
                                                <i class="fas fa-edit"></i> Editar
                                            </button>
                                            <a href="?delete=<?= $ad['id'] ?>" 
                                               class="btn btn-sm btn-danger"
                                               onclick="return confirm('¿Estás seguro de eliminar este anuncio?')">
                                               <i class="fas fa-trash"></i> Eliminar
                                            </a>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3" class="text-center py-4 text-white">No hay anuncios para mostrar</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Asegurar que jQuery y Bootstrap JS estén cargados -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Script para manejar la edición en modal
$(document).ready(function() {
    $('.edit-btn').on('click', function() {
        var id = $(this).data('id');
        var title = $(this).data('title');
        var url = $(this).data('url');
        
        $('#editAdId').val(id);
        $('#editAdTitle').val(title);
        $('#editAdUrl').val(url);
        
        $('#editAdModal').modal('show');
    });
});
</script>
<script>
setTimeout(function() {
    $(".alert").alert('close');
}, 4000); // 4 segundos
</script>
<?php include ('includes/footer.php'); ?>