<?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_once __DIR__ . '/../../services/billing/BillingRuntimeGate.php';
require_once __DIR__ . '/../../services/facto/FactoDocumentsSyncService.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.');
}
$id=(int)($_GET['id']??0); $kind=strtolower(trim((string)($_GET['kind']??'pdf')));
if($id<=0 || !in_array($kind,array('pdf','xml'),true)){http_response_code(400);die('Solicitud inválida.');}
$stmt=db()->prepare("SELECT environment,document_id,document_number,pdf_file_path,xml_file_path FROM facto_documents WHERE id=? LIMIT 1");
$stmt->execute(array($id)); $row=$stmt->fetch(PDO::FETCH_ASSOC);
if(!$row){http_response_code(404);die('Documento no encontrado.');}
billing_assert_runtime_operation('download', $row['environment'] ?? 'sandbox', 'Descarga de documento emitido');
$root=realpath(dirname(__DIR__,2)); $storageRoot=realpath($root.'/storage/billing');
$resolve=function($relative) use ($root,$storageRoot){
    if(!$relative||!$root||!$storageRoot)return false;
    $absolute=realpath($root.'/'.ltrim($relative,'/'));
    return $absolute&&strpos($absolute,$storageRoot)===0&&is_file($absolute)?$absolute:false;
};
$relative=$kind==='pdf'?$row['pdf_file_path']:$row['xml_file_path'];
$absolute=$resolve($relative);
if(!$absolute&&!empty($row['document_id'])){
    try{
        (new FactoDocumentsSyncService($row['environment']))->refreshDocument($row['document_id'],true);
        $stmt->execute(array($id)); $row=$stmt->fetch(PDO::FETCH_ASSOC);
        $relative=$kind==='pdf'?$row['pdf_file_path']:$row['xml_file_path'];
        $absolute=$resolve($relative);
    }catch(Throwable $e){error_log('FACTO issued file recovery failed: '.$e->getMessage());}
}
if(!$absolute){http_response_code(404);die('Archivo no disponible en FACTO para este documento.');}
$name=($row['document_number']?:('documento_'.$id)).'.'.$kind;
header('Content-Type: '.($kind==='pdf'?'application/pdf':'application/xml; charset=UTF-8'));
header('Content-Length: '.filesize($absolute));
header('Content-Disposition: inline; filename="'.preg_replace('/[^A-Za-z0-9_.-]/','_',$name).'"');
header('X-Content-Type-Options: nosniff');
readfile($absolute);
