<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/helpers.php';

$pdo = getConnection();

try {
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $activo = isset($_GET['activo']) ? (int)$_GET['activo'] : 1;

    $sql = "SELECT id, nombre, contacto_nombre, telefono, email, direccion, dias_credito, dias_entrega, activo, created_at
            FROM lugarcompra WHERE activo = ?";
    $params = [$activo];

    if (!empty($search)) {
        $sql .= " AND (nombre LIKE ? OR contacto_nombre LIKE ? OR telefono LIKE ? OR email LIKE ?)";
        $s = "%$search%";
        $params = array_merge($params, [$s, $s, $s, $s]);
    }

    $sql .= " ORDER BY nombre ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $proveedores = $stmt->fetchAll(PDO::FETCH_ASSOC);

    json_success($proveedores);
} catch (Exception $e) {
    json_error('Error al listar proveedores: ' . $e->getMessage());
}
