<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

$page_title = 'Productos';
$db = db();

$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$por_pagina = 12;
$offset = ($pagina - 1) * $por_pagina;

$where = ['p.activo = 1'];
$params = [];

if (!empty($_GET['buscar'])) {
    $buscar = '%' . sanitize($_GET['buscar']) . '%';
    $where[] = '(p.nombre LIKE ? OR p.descripcion_corta LIKE ?)';
    $params[] = $buscar;
    $params[] = $buscar;
    $page_title = 'Busqueda: ' . e($_GET['buscar']);
}
$cat_slug = sanitize($_GET['categoria'] ?? '');
if (!empty($cat_slug)) {
    $where[] = 'c.slug = ?';
    $params[] = $cat_slug;
}
if (!empty($_GET['marca'])) {
    $where[] = 'm.slug = ?';
    $params[] = sanitize($_GET['marca']);
}
if (!empty($_GET['min'])) {
    $where[] = 'COALESCE(p.precio_oferta, p.precio) >= ?';
    $params[] = (float)$_GET['min'];
}
if (!empty($_GET['max'])) {
    $where[] = 'COALESCE(p.precio_oferta, p.precio) <= ?';
    $params[] = (float)$_GET['max'];
}
if (!empty($_GET['en_oferta'])) {
    $where[] = 'p.en_oferta = 1';
}

$orden = $_GET['orden'] ?? 'destacado';
$order_clause = match($orden) {
    'precio_asc' => 'COALESCE(p.precio_oferta, p.precio) ASC',
    'precio_desc' => 'COALESCE(p.precio_oferta, p.precio) DESC',
    'nombre' => 'p.nombre ASC',
    'nuevos' => 'p.fecha_creacion DESC',
    'rating' => 'p.calificacion DESC',
    default => 'p.destacado DESC, p.fecha_creacion DESC'
};

$where_sql = implode(' AND ', $where);
$sql_base = "FROM productos p JOIN categorias c ON p.categoria_id = c.id JOIN marcas m ON p.marca_id = m.id WHERE {$where_sql}";

$stmt = $db->prepare("SELECT COUNT(*) {$sql_base}");
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();
$total_paginas = ceil($total / $por_pagina);

$stmt = $db->prepare("SELECT p.*, c.nombre AS categoria_nombre, c.slug AS categoria_slug, m.nombre AS marca_nombre, m.slug AS marca_slug {$sql_base} ORDER BY {$order_clause} LIMIT {$por_pagina} OFFSET {$offset}");
$stmt->execute($params);
$productos = $stmt->fetchAll();

$cats = $db->query('SELECT * FROM categorias WHERE activo = 1 ORDER BY orden')->fetchAll();
$marcas = $db->query('SELECT * FROM marcas WHERE activo = 1 ORDER BY nombre')->fetchAll();

require_once __DIR__ . '/../includes/header.php';
?>

<section class="page-header">
    <div class="container">
        <h1><?= $page_title ?></h1>
        <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0"><li class="breadcrumb-item"><a href="<?= url('') ?>">Inicio</a></li><li class="breadcrumb-item active">Productos</li></ol></nav>
    </div>
</section>

<section class="py-4">
    <div class="container">
        <div class="row">
            <div class="col-lg-3 mb-4">
                <div class="filter-section">
                    <h6><i class="bi bi-funnel me-2"></i>Filtros</h6>
                    <form method="GET" id="filterForm">
                        <input type="hidden" name="buscar" value="<?= e($_GET['buscar'] ?? '') ?>">

                        <div class="mb-3">
                            <label class="form-label fw-medium small">Categoria</label>
                            <select class="form-select form-select-sm" name="categoria" onchange="this.form.submit()">
                                <option value="">Todas</option>
                                <?php foreach ($cats as $cat): $sel = ($_GET['categoria'] ?? '') === $cat['slug'] ? 'selected' : ''; ?>
                                <option value="<?= $cat['slug'] ?>" <?= $sel ?>><?= e($cat['nombre']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-medium small">Marca</label>
                            <select class="form-select form-select-sm" name="marca" onchange="this.form.submit()">
                                <option value="">Todas</option>
                                <?php foreach ($marcas as $m): $sel = ($_GET['marca'] ?? '') === $m['slug'] ? 'selected' : ''; ?>
                                <option value="<?= $m['slug'] ?>" <?= $sel ?>><?= e($m['nombre']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-medium small">Precio</label>
                            <div class="row g-2">
                                <div class="col-6"><input type="number" class="form-control form-control-sm" name="min" placeholder="Min" value="<?= e($_GET['min'] ?? '') ?>"></div>
                                <div class="col-6"><input type="number" class="form-control form-control-sm" name="max" placeholder="Max" value="<?= e($_GET['max'] ?? '') ?>"></div>
                            </div>
                        </div>

                        <div class="mb-2"><div class="form-check"><input class="form-check-input" type="checkbox" name="en_oferta" value="1" <?= !empty($_GET['en_oferta']) ? 'checked' : '' ?> onchange="this.form.submit()"><label class="form-check-label small">Solo ofertas</label></div></div>

                        <button type="submit" class="btn btn-primary btn-sm w-100">Filtrar</button>
                        <a href="<?= url('pages/productos.php') ?>" class="btn btn-outline-secondary btn-sm w-100 mt-1">Limpiar</a>
                    </form>
                </div>
            </div>

            <div class="col-lg-9">
                <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                    <p class="text-muted small mb-0" id="products-count"><?= $total ?> producto(s) encontrado(s)</p>
                    <form method="GET" class="d-flex align-items-center gap-2">
                        <?php foreach (['buscar','categoria','marca','min','max','en_oferta'] as $k): if (!empty($_GET[$k])): ?>
                        <input type="hidden" name="<?= $k ?>" value="<?= e($_GET[$k]) ?>">
                        <?php endif; endforeach; ?>
                        <label class="form-label small mb-0">Ordenar:</label>
                        <select class="form-select form-select-sm" name="orden" onchange="this.form.submit()" style="width:auto;">
                            <option value="destacado" <?= $orden==='destacado'?'selected':'' ?>>Destacados</option>
                            <option value="nuevos" <?= $orden==='nuevos'?'selected':'' ?>>Mas nuevos</option>
                            <option value="precio_asc" <?= $orden==='precio_asc'?'selected':'' ?>>Menor precio</option>
                            <option value="precio_desc" <?= $orden==='precio_desc'?'selected':'' ?>>Mayor precio</option>
                            <option value="nombre" <?= $orden==='nombre'?'selected':'' ?>>Nombre A-Z</option>
                            <option value="rating" <?= $orden==='rating'?'selected':'' ?>>Mejor calificados</option>
                        </select>
                    </form>
                </div>

                <div id="products-grid-container" style="transition: opacity 0.3s ease;">
                <?php if (empty($productos)): ?>
                <div class="empty-state"><i class="bi bi-search"></i><h5>Sin resultados</h5><p class="text-muted">Intenta con otros filtros o terminos de busqueda.</p></div>
                <?php else: ?>
                <div class="row g-3">
                    <?php foreach ($productos as $p): ?>
                    <div class="col-6 col-md-4 col-lg-4"><?php include __DIR__ . '/../includes/product-card.php'; ?></div>
                    <?php endforeach; ?>
                </div>
                </div>

                <?php if ($total_paginas > 1): ?>
                <nav class="mt-4"><ul class="pagination justify-content-center">
                    <?php $url_base = '?'; foreach (['buscar','categoria','marca','min','max','en_oferta','orden'] as $k) { if (!empty($_GET[$k])) $url_base .= $k.'='.urlencode($_GET[$k]).'&'; } ?>
                    <?php for ($i = 1; $i <= $total_paginas; $i++): ?>
                    <li class="page-item <?= $i === $pagina ? 'active' : '' ?>"><a class="page-link" href="<?= $url_base ?>pagina=<?= $i ?>"><?= $i ?></a></li>
                    <?php endfor; ?>
                </ul></nav>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
