<?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('module.billing') && !user_can('billing.view') && !user_can('billing.manual.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('No autorizado.');
}

$operationId = (int)($_GET['operation_id'] ?? 0);
$stage = strtolower(trim((string)($_GET['stage'] ?? 'issued')));
$kind = strtolower(trim((string)($_GET['kind'] ?? 'pdf')));
if ($operationId <= 0 || !in_array($stage, array('preview','issued'), true) || !in_array($kind, array('pdf','xml','transfer_pdf'), true)) {
    http_response_code(400);
    die('Solicitud inválida.');
}

$columnMap = array(
    'preview' => array(
        'pdf' => array('preview_pdf_file_path','application/pdf','preview.pdf','inline'),
        'xml' => array('preview_xml_file_path','application/xml','preview.xml','attachment'),
        'transfer_pdf' => array('preview_transfer_copy_pdf_file_path','application/pdf','preview_copia_cedible.pdf','inline')
    ),
    'issued' => array(
        'pdf' => array('pdf_file_path','application/pdf','documento.pdf','inline'),
        'xml' => array('xml_file_path','application/xml','documento.xml','attachment'),
        'transfer_pdf' => array('transfer_copy_pdf_file_path','application/pdf','copia_cedible.pdf','inline')
    )
);
list($column, $mime, $fallback, $disposition) = $columnMap[$stage][$kind];

$stmt = db()->prepare("SELECT environment,{$column} AS file_path,COALESCE(document_number,preview_document_number) AS document_number FROM billing_manual_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 documento manual');
}
if (!$row || empty($row['file_path'])) {
    http_response_code(404);
    die('Archivo no disponible.');
}

$root = realpath(dirname(__DIR__, 2));
$storage = $root ? realpath($root . '/storage/billing') : false;
$absolute = $root ? realpath($root . '/' . ltrim((string)$row['file_path'], '/')) : false;
if (!$storage || !$absolute || strpos($absolute, $storage) !== 0 || !is_file($absolute)) {
    http_response_code(404);
    die('Archivo no disponible.');
}

$base = $row['document_number'] ?: ('operacion_' . $operationId);
$filename = preg_replace('/[^A-Za-z0-9_.-]/', '_', $base . '_' . $fallback);
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($absolute));
header('Content-Disposition: ' . $disposition . '; filename="' . $filename . '"');
readfile($absolute);
