<?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();
if (!user_can('module.billing') && !user_can('billing.export.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    exit('Sin permisos.');
}
$service = new BillingExportInvoiceService(db());
$op = $service->getOperation((int)($_GET['operation_id'] ?? 0));
if (!$op) { http_response_code(404); exit('Operación no encontrada.'); }
billing_assert_runtime_operation('download', $op['environment'] ?? 'sandbox', 'Descarga de factura de exportación');
$kind = (string)($_GET['kind'] ?? 'pdf');
$map = array(
    'preview_pdf' => array('preview_pdf_file_path','application/pdf','preview.pdf'),
    'preview_xml' => array('preview_xml_file_path','application/xml','preview.xml'),
    'pdf' => array('pdf_file_path','application/pdf','factura_exportacion.pdf'),
    'xml' => array('xml_file_path','application/xml','factura_exportacion.xml')
);
if (!isset($map[$kind])) { http_response_code(400); exit('Tipo de archivo inválido.'); }
list($column,$mime,$filename) = $map[$kind];
$relative = trim((string)($op[$column] ?? ''));
if ($relative === '') { http_response_code(404); exit('Archivo no disponible.'); }
$root = realpath(dirname(__DIR__,2));
$path = realpath($root . '/' . ltrim($relative,'/'));
$allowed = realpath($root . '/storage/billing');
if (!$path || !$allowed || strpos($path,$allowed) !== 0 || !is_file($path)) { http_response_code(404); exit('Archivo no encontrado.'); }
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path));
header('Content-Disposition: ' . ($mime === 'application/pdf' ? 'inline' : 'attachment') . '; filename="' . $filename . '"');
readfile($path);
