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

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

if (!user_can('billing.inbox') && !user_can('billing.inbox.receive') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para ver recepcion DTE.'));
    exit;
}

try {
    $service = new BillingInboxReceptionService(db());
    echo json_encode(array(
        'success' => true,
        'data' => $service->listDocuments(array(
            'environment' => $_GET['env'] ?? 'sandbox',
            'tab' => $_GET['tab'] ?? 'pending',
            'status' => $_GET['status'] ?? '',
            'document_type_id' => $_GET['document_type_id'] ?? '',
            'rut' => $_GET['rut'] ?? '',
            'folio' => $_GET['folio'] ?? '',
            'purchase_order' => $_GET['purchase_order'] ?? '',
            'limit' => $_GET['limit'] ?? 80
        ))
    ), 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);
}
