<?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_login();

if (!user_can('module.billing') && !user_can('billing.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('Forbidden');
}

$logId = (int) ($_GET['log_id'] ?? 0);
if ($logId <= 0) {
    http_response_code(400);
    die('Log invalido');
}

$pdo = db();
$stmt = $pdo->prepare("\n    SELECT id, mode, environment, pdf_file_path\n    FROM billing_issue_logs\n    WHERE id = ?\n      AND mode IN ('draft_preview','issue')\n    LIMIT 1\n");
$stmt->execute(array($logId));
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    billing_assert_runtime_operation('download', $row['environment'] ?? 'sandbox', 'Descarga de preview tributario');
}
if (!$row || empty($row['pdf_file_path'])) {
    http_response_code(404);
    die('PDF no disponible');
}

$appRoot = realpath(dirname(__DIR__, 2));
$relative = ltrim(str_replace(array('..', '\\'), array('', '/'), (string) $row['pdf_file_path']), '/');
$file = realpath($appRoot . '/' . $relative);
$storageRoot = realpath($appRoot . '/storage/billing');

if (!$file || !$storageRoot || strpos($file, $storageRoot) !== 0 || !is_file($file)) {
    http_response_code(404);
    die('Archivo no encontrado');
}

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="documento_facto_' . (int) $logId . '.pdf"');
header('Content-Length: ' . filesize($file));
header('Cache-Control: private, max-age=0, must-revalidate');
readfile($file);
exit;
