<?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/BillingUnifiedIssuerService.php';

require_login();
header('Content-Type: application/json; charset=utf-8');

if (!user_can('billing.manual.prepare') && !user_can('billing.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para preparar documentos manuales.'));
    exit;
}

try {
    $service = new BillingUnifiedIssuerService(db());
    $kind = strtolower(trim((string)($_GET['kind'] ?? 'bootstrap')));
    $q = trim((string)($_GET['q'] ?? ''));
    $limit = max(1, min(60, (int)($_GET['limit'] ?? 30)));

    switch ($kind) {
        case 'customers':
            $result = $service->searchCustomers($q, $limit);
            break;
        case 'products':
            $result = $service->searchProducts($q, $limit);
            break;
        case 'sources':
            $result = $service->searchSourceDocuments(
                (string)($_GET['document_key'] ?? ''),
                $q,
                (string)($_GET['environment'] ?? 'sandbox'),
                $limit
            );
            break;
        case 'bootstrap':
        default:
            $result = $service->bootstrap((string)($_GET['environment'] ?? 'sandbox'));
            break;
    }

    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);
}
