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

require_login();
csrf_require_valid_request();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('billing.export.issue.sandbox') && !user_can('billing.issue.export') && !user_can('billing.issue.sandbox') && !user_can('billing.issue.production') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success'=>false,'message'=>'No tienes permisos para emitir facturas de exportación.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success'=>false,'message'=>'Método no permitido.'));
    exit;
}
try {
    $service = new BillingExportInvoiceService(db());
    $result = $service->issue((int)($_POST['operation_id'] ?? 0), $_POST['confirmation'] ?? '', function_exists('current_user_id') ? current_user_id() : null);
    echo json_encode(array('success'=>true,'result'=>$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);
}
