<?php 
include 'conexion.php'; 
session_start(); 

// 1. GESTIÓN DE BÚSQUEDA SEGURA
$busqueda = isset($_GET['q']) ? $_GET['q'] : '';
$filtro_nivel = isset($_GET['nivel']) ? $_GET['nivel'] : '';

$sql = "SELECT * FROM materiales WHERE 1=1";
$params = [];
$types = "";

if (!empty($busqueda)) {
    $sql .= " AND (titulo LIKE ? OR descripcion LIKE ? OR area LIKE ?)";
    $term = "%$busqueda%";
    $params[] = $term; $params[] = $term; $params[] = $term;
    $types .= "sss";
}

if (!empty($filtro_nivel)) {
    $sql .= " AND nivel = ?";
    $params[] = $filtro_nivel;
    $types .= "s";
}

$sql .= " ORDER BY id DESC";

$stmt = $conexion->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$resultado = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edujoam — Recursos Educativos</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --blue-dark: #0f172a; --blue-main: #2563eb; --blue-soft: #eef2ff;
            --text-main: #1e293b; --text-muted: #64748b; --bg-body: #f8fafc;
        }
        body { background: var(--bg-body); font-family: 'Outfit', sans-serif; color: var(--text-main); }
        .hero-premium { background: linear-gradient(135deg, #0f172a, #1e40af); padding: 40px 0 60px; text-align: center; color: #fff; }
        .search-container { max-width: 950px; margin: -35px auto 50px; padding: 15px; background: #fff; border-radius: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.1); border: 1px solid #eee; }
        .card-pro { background: #fff; border-radius: 22px; border: 1px solid #e2e8f0; padding: 25px; height: 100%; display: flex; flex-direction: column; transition: 0.3s; position: relative; overflow: hidden; }
        .card-pro::before { content: ""; position: absolute; top: 0; left: 0; height: 5px; width: 100%; background: var(--blue-main); }
        .card-pro:hover { transform: translateY(-5px); box-shadow: 0 20px 40px rgba(0,0,0,0.08); }
        .tag-nivel { background: var(--blue-soft); color: var(--blue-main); padding: 5px 12px; border-radius: 10px; font-size: 0.75rem; font-weight: 700; }
        .price-wrapper { margin-top: auto; background: var(--blue-main); border-radius: 15px; padding: 15px; display: flex; justify-content: space-between; align-items: center; }
        .price-value { font-size: 1.4rem; font-weight: 800; color: #fff; }
        .btn-buy-pro { margin-top: 15px; width: 100%; padding: 12px; border-radius: 12px; font-weight: 700; color: #fff; background: var(--blue-dark); text-decoration: none; text-align: center; border: none; transition: 0.3s; }
        .btn-buy-pro:hover { background: #000; transform: scale(1.02); color: #fff; }
        .btn-login-card { margin-top: 15px; width: 100%; padding: 12px; border-radius: 12px; font-weight: 700; color: var(--blue-dark); background: transparent; border: 2px solid var(--blue-dark); text-decoration: none; text-align: center; transition: 0.3s; }
        .btn-login-card:hover { background: var(--blue-dark); color: #fff; }
    </style>
</head>
<body>

<?php if(file_exists('navbar.php')) include 'navbar.php'; ?>

<header class="hero-premium">
    <div class="container"><h1>Materiales pedagógicos</h1></div>
</header>

<div class="container">
    <div class="search-container">
        <form method="GET" class="row g-2">
            <div class="col-md-5"><input type="text" name="q" value="<?= htmlspecialchars($busqueda) ?>" class="form-control" placeholder="Buscar por tema o curso"></div>
            <div class="col-md-4">
                <select name="nivel" class="form-select">
                    <option value="">Todos los niveles</option>
                    <option value="Inicial" <?= $filtro_nivel=='Inicial'?'selected':'' ?>>Inicial</option>
                    <option value="Primaria" <?= $filtro_nivel=='Primaria'?'selected':'' ?>>Primaria</option>
                    <option value="Secundaria" <?= $filtro_nivel=='Secundaria'?'selected':'' ?>>Secundaria</option>
                </select>
            </div>
            <div class="col-md-3"><button class="btn btn-primary w-100 fw-bold">Filtrar</button></div>
        </form>
    </div>

    <div class="row g-4 pb-5">
    <?php while($row = $resultado->fetch_assoc()): 
        $ext = pathinfo($row['archivo_url'], PATHINFO_EXTENSION); ?>
        <div class="col-md-6 col-lg-4">
            <div class="card-pro">
                <div class="d-flex justify-content-between">
                    <span class="tag-nivel"><?= $row['nivel'] ?></span>
                    <span class="text-muted small fw-bold"><?= strtoupper($ext) ?></span>
                </div>
                <h2 class="h5 fw-bold mt-3 mb-2"><?= htmlspecialchars($row['titulo']) ?></h2>
                <p class="text-muted small mb-4"><?= mb_strimwidth($row['descripcion'], 0, 90, "...") ?></p>
                
                <div class="price-wrapper">
                    <div>
                        <small class="text-white-50 d-block" style="font-size: 0.65rem;">PRECIO</small>
                        <div class="price-value">S/ <?= number_format($row['precio'], 2) ?></div>
                    </div>
                    <span class="badge bg-white text-dark rounded-pill px-3 py-2 small fw-bold"><?= $row['area'] ?></span>
                </div>

                <?php if(isset($_SESSION['user_id'])): ?>
                    <a href="reportar_pago.php?id=<?= $row['id'] ?>" class="btn-buy-pro">
                        <i class="fas fa-shopping-cart me-2"></i>Obtener material
                    </a>
                <?php else: ?>
                    <a href="login.php" class="btn-login-card">Iniciar sesión</a>
                <?php endif; ?>
            </div>
        </div>
    <?php endwhile; ?>
    </div>
</div>

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



