<?php
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_login();
if (!user_can('billing.documents') && !user_can('billing.view') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403); die('No autorizado.');
}
$operationId = (int)($_GET['operation_id'] ?? 0);
$kind = strtolower(trim((string)($_GET['kind'] ?? 'pdf')));
$stage = strtolower(trim((string)($_GET['stage'] ?? 'issued')));
if ($operationId <= 0 || !in_array($kind,array('pdf','xml'),true) || !in_array($stage,array('preview','issued'),true)) {
    http_response_code(400); die('Solicitud inválida.');
}
$column = $stage === 'preview'
    ? ($kind === 'pdf' ? 'preview_pdf_file_path' : 'preview_xml_file_path')
    : ($kind === 'pdf' ? 'pdf_file_path' : 'xml_file_path');
$stmt = db()->prepare("SELECT environment,{$column} AS file_path,COALESCE(document_number,preview_document_number) AS document_number FROM billing_tax_operations WHERE id=? LIMIT 1");
$stmt->execute(array($operationId));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) { billing_assert_runtime_operation('download', $row['environment'] ?? 'sandbox', 'Descarga de nota tributaria'); }
if (!$row || empty($row['file_path'])) { http_response_code(404); die('Archivo no disponible.'); }
$root = realpath(dirname(__DIR__,2));
$storageRoot = realpath($root . '/storage/billing');
$absolute = realpath($root . '/' . ltrim($row['file_path'],'/'));
if (!$storageRoot || !$absolute || strpos($absolute,$storageRoot)!==0 || !is_file($absolute)) { http_response_code(404); die('Ruta no válida.'); }
$filename = ($row['document_number'] ?: ('operacion_'.$operationId)) . '.' . $kind;
header('Content-Type: ' . ($kind==='pdf' ? 'application/pdf' : 'application/xml'));
header('Content-Length: ' . filesize($absolute));
header('Content-Disposition: ' . ($kind==='pdf' ? 'inline' : 'attachment') . '; filename="' . preg_replace('/[^A-Za-z0-9_.-]/','_',$filename) . '"');
readfile($absolute);
