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

require_login();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('billing.documents') && !user_can('billing.view') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success'=>false,'message'=>'No tienes permisos para ver documentos emitidos.'));
    exit;
}
try {
    $service = new BillingIssuedDocumentsService(db());
    $result = $service->listDocuments(array(
        'environment'=>$_GET['env'] ?? (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'production'),
        'search'=>$_GET['search'] ?? '',
        'family'=>$_GET['family'] ?? 'all',
        'origin'=>$_GET['origin'] ?? 'all',
        'from'=>$_GET['from'] ?? '',
        'to'=>$_GET['to'] ?? ''
    ));
    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);
}
