<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/auth.php';
require_once '../../core/permissions.php';
require_once '../../services/billing/BillingDocumentTypeService.php';

require_login();

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

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

try {
    $environment = $_GET['environment'] ?? (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'sandbox');
    $service = new BillingDocumentTypeService(db());
    echo json_encode(array('success' => true, 'items' => $service->listIssuedTypes($environment)), 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);
}
