<?php
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/billing/BillingPurchaseOrderService.php';

require_login();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('module.billing') && !user_can('billing.purchase_orders') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para gestionar órdenes de compra.'));
    exit;
}

try {
    $service = new BillingPurchaseOrderService(db());
    $kind = strtolower(trim((string)($_GET['kind'] ?? 'bootstrap')));
    $query = trim((string)($_GET['q'] ?? ''));
    $limit = max(1, min(60, (int)($_GET['limit'] ?? 30)));
    if ($kind === 'suppliers') {
        $result = $service->searchSuppliers($query, $limit);
    } elseif ($kind === 'products') {
        $result = $service->searchProducts($query, $limit);
    } else {
        $result = $service->bootstrap();
    }
    echo json_encode(array('success' => true, 'data' => $result), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
