<?php
// admin_bloque_publicitario.php

// ===== DEBUG PROVISORIO (después lo podés borrar) =====
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

@session_start();

// 🔐 Si existe restringir.php en esta carpeta, lo usamos. Si no, seguimos igual.
if (file_exists(__DIR__ . '/restringir.php')) {
    require_once __DIR__ . '/restringir.php';
}

require_once __DIR__ . '/db.php';

// Intentar obtener PDO
try {
    $pdo = pdo();
} catch (Exception $e) {
    echo "<h2>Error al obtener conexión PDO</h2>";
    echo "<pre>" . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</pre>";
    exit;
}

/* ==========================
   CREAR TABLA SI NO EXISTE
   ========================== */
try {
    $sqlCreate = "
        CREATE TABLE IF NOT EXISTS bloque_publicitario (
            id INT AUTO_INCREMENT PRIMARY KEY,
            titulo VARCHAR(255) DEFAULT NULL,
            imagen_url VARCHAR(500) NOT NULL,
            enlace VARCHAR(500) DEFAULT NULL,
            orden INT DEFAULT 0,
            estado VARCHAR(20) DEFAULT 'activo',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ";
    $pdo->exec($sqlCreate);
} catch (Exception $e) {
    echo "<h2>Error al crear/chequear la tabla bloque_publicitario</h2>";
    echo "<pre>" . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</pre>";
    exit;
}

/* ==========================
   HELPER SUBIDA DE IMAGEN
   ========================== */
function bp_subir_imagen($campo) {
    if (empty($_FILES[$campo]['name']) || $_FILES[$campo]['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    $dir = __DIR__ . '/img/bloque_publicitario/';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }

    $ext = pathinfo($_FILES[$campo]['name'], PATHINFO_EXTENSION);
    $ext = strtolower($ext ? $ext : 'jpg');

    $nombre = 'bp_' . date('Ymd_His') . '_' . mt_rand(1000, 9999) . '.' . $ext;
    $destinoAbs = $dir . $nombre;

    if (!move_uploaded_file($_FILES[$campo]['tmp_name'], $destinoAbs)) {
        return null;
    }

    // URL relativa para usar en el <img>
    return 'img/bloque_publicitario/' . $nombre;
}

/* ==========================
   ACCIONES (POST)
   ========================== */
$mensaje = null;
$error   = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $accion = isset($_POST['accion']) ? $_POST['accion'] : '';

    if ($accion === 'crear') {
        $titulo = trim(isset($_POST['titulo']) ? $_POST['titulo'] : '');
        $enlace = trim(isset($_POST['enlace']) ? $_POST['enlace'] : '');
        $orden  = (int)(isset($_POST['orden']) ? $_POST['orden'] : 0);
        $estado = (isset($_POST['estado']) && $_POST['estado'] === 'inactivo') ? 'inactivo' : 'activo';

        $imgUrl = bp_subir_imagen('imagen');
        if (!$imgUrl) {
            $error = "Debés seleccionar una imagen válida para el bloque publicitario.";
        } else {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO bloque_publicitario (titulo, imagen_url, enlace, orden, estado)
                    VALUES (?, ?, ?, ?, ?)
                ");
                if ($stmt->execute(array($titulo, $imgUrl, $enlace, $orden, $estado))) {
                    $mensaje = "Bloque publicitario creado correctamente.";
                } else {
                    $error = "Error al guardar el bloque publicitario.";
                }
            } catch (Exception $e) {
                $error = "Error SQL al crear: " . $e->getMessage();
            }
        }

    } elseif ($accion === 'actualizar') {
        $id     = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $titulo = trim(isset($_POST['titulo']) ? $_POST['titulo'] : '');
        $enlace = trim(isset($_POST['enlace']) ? $_POST['enlace'] : '');
        $orden  = (int)(isset($_POST['orden']) ? $_POST['orden'] : 0);
        $estado = (isset($_POST['estado']) && $_POST['estado'] === 'inactivo') ? 'inactivo' : 'activo';

        $nuevaImg = bp_subir_imagen('imagen');

        try {
            if ($nuevaImg) {
                $stmt = $pdo->prepare("
                    UPDATE bloque_publicitario
                    SET titulo = ?, enlace = ?, orden = ?, estado = ?, imagen_url = ?
                    WHERE id = ?
                ");
                $ok = $stmt->execute(array($titulo, $enlace, $orden, $estado, $nuevaImg, $id));
            } else {
                $stmt = $pdo->prepare("
                    UPDATE bloque_publicitario
                    SET titulo = ?, enlace = ?, orden = ?, estado = ?
                    WHERE id = ?
                ");
                $ok = $stmt->execute(array($titulo, $enlace, $orden, $estado, $id));
            }

            if ($ok) {
                $mensaje = "Bloque publicitario actualizado.";
            } else {
                $error = "No se pudo actualizar el bloque publicitario.";
            }
        } catch (Exception $e) {
            $error = "Error SQL al actualizar: " . $e->getMessage();
        }

    } elseif ($accion === 'eliminar') {
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        try {
            $stmt = $pdo->prepare("DELETE FROM bloque_publicitario WHERE id = ?");
            if ($stmt->execute(array($id))) {
                $mensaje = "Bloque publicitario eliminado.";
            } else {
                $error = "No se pudo eliminar el bloque publicitario.";
            }
        } catch (Exception $e) {
            $error = "Error SQL al eliminar: " . $e->getMessage();
        }
    }
}

/* ==========================
   LISTADO
   ========================== */
try {
    $stmt = $pdo->query("
        SELECT id, titulo, imagen_url, enlace, orden, estado, created_at
        FROM bloque_publicitario
        ORDER BY orden ASC, id DESC
    ");
    $bloques = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();
} catch (Exception $e) {
    echo "<h2>Error al listar bloque_publicitario</h2>";
    echo "<pre>" . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</pre>";
    $bloques = array();
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administrador de Bloques Publicitarios</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a56d4;
            --secondary: #7209b7;
            --success: #4cc9f0;
            --light: #f8f9fa;
            --dark: #212529;
            --gradient: linear-gradient(135deg, #4361ee 0%, #7209b7 100%);
            --card-shadow: 0 10px 20px rgba(0,0,0,0.1);
            --hover-shadow: 0 15px 30px rgba(0,0,0,0.15);
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .admin-container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .glass-card {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            box-shadow: var(--card-shadow);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
        }
        
        .glass-card:hover {
            box-shadow: var(--hover-shadow);
            transform: translateY(-5px);
        }
        
        .header-gradient {
            background: var(--gradient);
            color: white;
            border-radius: 16px 16px 0 0;
            padding: 1.5rem;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            padding: 0.75rem 1rem;
            border: 1px solid #e1e5eb;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
            border-color: var(--primary);
        }
        
        .btn-primary {
            background: var(--primary);
            border: none;
            border-radius: 10px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 7px 14px rgba(67, 97, 238, 0.3);
        }
        
        .btn-success {
            background: #06d6a0;
            border: none;
            border-radius: 10px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-success:hover {
            background: #05b386;
            transform: translateY(-2px);
            box-shadow: 0 7px 14px rgba(6, 214, 160, 0.3);
        }
        
        .btn-outline-danger {
            border-radius: 10px;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
        }
        
        .btn-outline-danger:hover {
            transform: translateY(-2px);
        }
        
        .banner-card {
            border-radius: 12px;
            overflow: hidden;
            transition: all 0.3s ease;
            height: 100%;
        }
        
        .banner-card:hover {
            transform: translateY(-5px);
        }
        
        .banner-img-container {
            height: 180px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            overflow: hidden;
        }
        
        .banner-img {
            max-height: 100%;
            max-width: 100%;
            object-fit: contain;
        }
        
        .status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-active {
            background: rgba(76, 201, 240, 0.2);
            color: #06aed5;
            border: 1px solid rgba(76, 201, 240, 0.3);
        }
        
        .status-inactive {
            background: rgba(239, 71, 111, 0.2);
            color: #ef476f;
            border: 1px solid rgba(239, 71, 111, 0.3);
        }
        
        .alert-custom {
            border-radius: 12px;
            border: none;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        .alert-success {
            background: rgba(6, 214, 160, 0.1);
            color: #05b386;
            border-left: 4px solid #06d6a0;
        }
        
        .alert-danger {
            background: rgba(239, 71, 111, 0.1);
            color: #ef476f;
            border-left: 4px solid #ef476f;
        }
        
        .section-title {
            color: var(--primary);
            font-weight: 700;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid rgba(67, 97, 238, 0.1);
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: #dee2e6;
        }
        
        .form-label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.5rem;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        @media (max-width: 768px) {
            .banner-img-container {
                height: 150px;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container py-4">
        <div class="row justify-content-center">
            <div class="col-12">
                <div class="glass-card mb-5">
                    <div class="header-gradient">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-ad fa-2x me-3"></i>
                            <div>
                                <h1 class="h3 mb-0">Administrador de Bloques Publicitarios</h1>
                                <p class="mb-0 opacity-75">Gestiona todos tus banners publicitarios en un solo lugar</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card-body">
                        <?php if ($mensaje): ?>
                            <div class="alert alert-success alert-custom alert-dismissible fade show d-flex align-items-center" role="alert">
                                <i class="fas fa-check-circle me-2"></i>
                                <div><?php echo htmlspecialchars($mensaje, ENT_QUOTES, 'UTF-8'); ?></div>
                                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($error): ?>
                            <div class="alert alert-danger alert-custom alert-dismissible fade show d-flex align-items-center" role="alert">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <div><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div>
                                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                            </div>
                        <?php endif; ?>

                        <h3 class="section-title">
                            <i class="fas fa-plus-circle me-2"></i>Agregar nuevo banner
                        </h3>
                        
                        <form method="post" enctype="multipart/form-data" class="row g-4">
                            <input type="hidden" name="accion" value="crear">

                            <div class="col-md-4">
                                <label class="form-label">Título (opcional)</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-heading"></i></span>
                                    <input type="text" name="titulo" class="form-control" placeholder="Ej: Sponsor principal">
                                </div>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Enlace (opcional)</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-link"></i></span>
                                    <input type="url" name="enlace" class="form-control" placeholder="https://">
                                </div>
                            </div>

                            <div class="col-md-2">
                                <label class="form-label">Orden</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-sort"></i></span>
                                    <input type="number" name="orden" class="form-control" value="0">
                                </div>
                            </div>

                            <div class="col-md-2">
                                <label class="form-label">Estado</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-toggle-on"></i></span>
                                    <select name="estado" class="form-select">
                                        <option value="activo">Activo</option>
                                        <option value="inactivo">Inactivo</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Imagen (requerida)</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-image"></i></span>
                                    <input type="file" name="imagen" class="form-control" accept="image/*" required>
                                </div>
                                <small class="text-muted mt-1 d-block">
                                    <i class="fas fa-info-circle me-1"></i>Se guarda en <code>img/bloque_publicitario/</code>
                                </small>
                            </div>

                            <div class="col-12 mt-2">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save me-2"></i>Guardar bloque publicitario
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="glass-card">
                    <div class="card-header bg-light py-3">
                        <h3 class="section-title mb-0">
                            <i class="fas fa-images me-2"></i>Bloques cargados
                        </h3>
                    </div>
                    
                    <div class="card-body">
                        <?php if (empty($bloques)): ?>
                            <div class="empty-state">
                                <i class="fas fa-ad"></i>
                                <h4 class="h5">No hay banners cargados</h4>
                                <p class="mb-0">Comienza agregando tu primer bloque publicitario usando el formulario superior.</p>
                            </div>
                        <?php else: ?>
                            <div class="row g-4">
                                <?php foreach ($bloques as $b): ?>
                                    <div class="col-12 col-md-6 col-lg-4">
                                        <div class="banner-card glass-card position-relative">
                                            <div class="banner-img-container">
                                                <img src="<?php echo htmlspecialchars($b['imagen_url'], ENT_QUOTES, 'UTF-8'); ?>"
                                                     alt="<?php echo htmlspecialchars($b['titulo'] ? $b['titulo'] : 'Banner', ENT_QUOTES, 'UTF-8'); ?>"
                                                     class="banner-img">
                                            </div>
                                            
                                            <span class="status-badge <?php echo $b['estado'] === 'activo' ? 'status-active' : 'status-inactive'; ?>">
                                                <i class="fas fa-circle me-1" style="font-size: 0.5rem;"></i>
                                                <?php echo $b['estado'] === 'activo' ? 'Activo' : 'Inactivo'; ?>
                                            </span>
                                            
                                            <div class="card-body">
                                                <form method="post" enctype="multipart/form-data">
                                                    <input type="hidden" name="accion" value="actualizar">
                                                    <input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>">

                                                    <div class="mb-3">
                                                        <label class="form-label mb-1">Título</label>
                                                        <div class="input-group input-group-sm">
                                                            <span class="input-group-text"><i class="fas fa-heading"></i></span>
                                                            <input type="text" name="titulo" class="form-control"
                                                                   value="<?php echo htmlspecialchars($b['titulo'], ENT_QUOTES, 'UTF-8'); ?>">
                                                        </div>
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label mb-1">Enlace</label>
                                                        <div class="input-group input-group-sm">
                                                            <span class="input-group-text"><i class="fas fa-link"></i></span>
                                                            <input type="url" name="enlace" class="form-control"
                                                                   value="<?php echo htmlspecialchars($b['enlace'], ENT_QUOTES, 'UTF-8'); ?>">
                                                        </div>
                                                    </div>

                                                    <div class="row g-2 mb-3">
                                                        <div class="col-6">
                                                            <label class="form-label mb-1">Orden</label>
                                                            <div class="input-group input-group-sm">
                                                                <span class="input-group-text"><i class="fas fa-sort"></i></span>
                                                                <input type="number" name="orden" class="form-control"
                                                                       value="<?php echo (int)$b['orden']; ?>">
                                                            </div>
                                                        </div>
                                                        <div class="col-6">
                                                            <label class="form-label mb-1">Estado</label>
                                                            <div class="input-group input-group-sm">
                                                                <span class="input-group-text"><i class="fas fa-toggle-on"></i></span>
                                                                <select name="estado" class="form-select">
                                                                    <option value="activo" <?php echo ($b['estado'] === 'activo' ? 'selected' : ''); ?>>Activo</option>
                                                                    <option value="inactivo" <?php echo ($b['estado'] === 'inactivo' ? 'selected' : ''); ?>>Inactivo</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label mb-1">Reemplazar imagen (opcional)</label>
                                                        <div class="input-group input-group-sm">
                                                            <span class="input-group-text"><i class="fas fa-image"></i></span>
                                                            <input type="file" name="imagen" class="form-control" accept="image/*">
                                                        </div>
                                                    </div>

                                                    <div class="d-flex justify-content-between mt-4">
                                                        <button type="submit" class="btn btn-primary btn-sm">
                                                            <i class="fas fa-save me-1"></i>Guardar
                                                        </button>
                                                </form>
                                                        <form method="post" onsubmit="return confirm('¿Eliminar este bloque publicitario?');">
                                                            <input type="hidden" name="accion" value="eliminar">
                                                            <input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>">
                                                            <button type="submit" class="btn btn-outline-danger btn-sm">
                                                                <i class="fas fa-trash me-1"></i>Eliminar
                                                            </button>
                                                        </form>
                                                    </div>

                                                    <small class="text-muted d-block mt-3">
                                                        <i class="fas fa-fingerprint me-1"></i>ID #<?php echo (int)$b['id']; ?> 
                                                        · <i class="fas fa-calendar me-1"></i><?php echo htmlspecialchars($b['created_at'], ENT_QUOTES, 'UTF-8'); ?>
                                                    </small>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>