<?php



require_once __DIR__ . '/../../config.php';

// GET /admin/productos/list.php
// Query params: search, page, limit

requireAdmin();

$db = getDB();
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(100, max(1, (int)($_GET['limit'] ?? 20)));
$offset = ($page - 1) * $limit;
$search = $_GET['search'] ?? '';

$where = '';
$params = [];

if (!empty($search)) {
    $where = 'WHERE p.nombre LIKE ? OR p.descripcion LIKE ?';
    $searchTerm = '%' . $search . '%';
    $params = [$searchTerm, $searchTerm];
}

$countSql = "SELECT COUNT(*) as total FROM productos p $where";
$stmt = $db->prepare($countSql);
$stmt->execute($params);
$total = $stmt->fetch()['total'] ?? 0;

$sql = "
    SELECT p.id_prod, p.nombre, p.descripcion, p.precio, p.pv, p.puntaje,
           p.fotografia, p.status, p.peso
    FROM productos p
    $where
    ORDER BY p.id_prod DESC
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;

$stmt = $db->prepare($sql);
$stmt->execute($params);
$productos = $stmt->fetchAll();

// Get promos
$stmt = $db->query('
    SELECT pr.id_promo, pr.nombre, pr.descripcion, pr.precio, pr.puntaje, pr.status
    FROM promod pr
    ORDER BY pr.id_promo DESC
    LIMIT 10
');
$promos = $stmt->fetchAll();

jsonOk([
    'productos' => $productos,
    'promos' => $promos,
    'pagination' => [
        'page' => $page,
        'limit' => $limit,
        'total' => (int)$total,
        'pages' => (int)ceil($total / $limit)
    ]
]);
