<?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.prepare') && !user_can('billing.issue.export') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success'=>false,'message'=>'No tienes permisos para preparar 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 {
    $payload = json_decode((string)($_POST['payload'] ?? ''), true);
    if (!is_array($payload)) throw new InvalidArgumentException('Payload de exportación inválido.');
    $service = new BillingExportInvoiceService(db());
    $result = $service->preview($payload, 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);
}
