<?php
/**
 * GET /api/compras/listar.php
 * Parámetros: page, limit, q
 */
require_once '../config/database.php';
require_once '../includes/helpers.php';

$pdo = getConnection();

try {
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
    $offset = ($page - 1) * $limit;
    $q = isset($_GET['q']) ? trim($_GET['q']) : '';

    $params = [];
    $where = " WHERE 1=1 ";

    if ($q !== '') {
        $where .= " AND (l.nombre LIKE :q OR EXISTS (SELECT 1 FROM compras_detalle d WHERE d.compra_id = c.id AND d.numero_factura LIKE :q)) ";
        $params[':q'] = "%$q%";
    }

    // Obtener total de registros para paginación
    $countSql = "SELECT COUNT(*) FROM compras c LEFT JOIN lugarcompra l ON l.id = c.id_lugarCompra $where";
    $stmtCount = $pdo->prepare($countSql);
    $stmtCount->execute($params);
    $total = intval($stmtCount->fetchColumn());

    // Obtener compras ordenadas de forma descendente (más recientes primero)
    $sql = "SELECT c.id, c.fecha_compra, c.total, c.tipo_pago, c.estado_pago, l.nombre AS proveedor_nombre,
                   (SELECT GROUP_CONCAT(DISTINCT d.numero_factura SEPARATOR ', ') FROM compras_detalle d WHERE d.compra_id = c.id) AS numero_factura
            FROM compras c
            LEFT JOIN lugarcompra l ON l.id = c.id_lugarCompra
            $where
            ORDER BY c.id DESC
            LIMIT :limit OFFSET :offset";

    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    foreach ($params as $key => $val) {
        $stmt->bindValue($key, $val);
    }
    $stmt->execute();
    $compras = $stmt->fetchAll(PDO::FETCH_ASSOC);

    json_success([
        'compras' => $compras,
        'pagination' => [
            'page' => $page,
            'limit' => $limit,
            'total' => $total
        ]
    ]);
} catch (Exception $e) {
    json_error('Error: ' . $e->getMessage());
}
?>
