<?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/BillingInboxReceptionService.php';
require_once '../../services/facto/FactoInboxDocumentsSyncService.php';

require_login();

if (!user_can('billing.inbox') && !user_can('billing.inbox.receive') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    exit('Sin permisos.');
}

try {
    $service = new BillingInboxReceptionService(db());
    $doc = $service->getDocument($_GET['id'] ?? '', $_GET['env'] ?? 'sandbox');
    $type = ($_GET['type'] ?? 'pdf') === 'xml' ? 'xml' : 'pdf';
    $path = $type === 'xml' ? ($doc['xml_file_path'] ?? '') : ($doc['pdf_file_path'] ?? '');
    $base = realpath(__DIR__ . '/../../storage/billing');
    $full = $path ? realpath(__DIR__ . '/../../' . ltrim($path, '/')) : false;
    if (!$base || !$full || strpos($full, $base) !== 0 || !is_file($full)) {
        if (empty($doc['inbox_document_id'])) throw new Exception('El documento no tiene identificador FACTO para recuperar archivos.');
        (new FactoInboxDocumentsSyncService($doc['environment']))->refreshInboxDocument($doc['inbox_document_id'], true);
        $doc = $service->getDocument($_GET['id'] ?? '', $doc['environment']);
        $path = $type === 'xml' ? ($doc['xml_file_path'] ?? '') : ($doc['pdf_file_path'] ?? '');
        $full = $path ? realpath(__DIR__ . '/../../' . ltrim($path, '/')) : false;
        if (!$base || !$full || strpos($full, $base) !== 0 || !is_file($full)) throw new Exception('Archivo no disponible en FACTO para este documento.');
    }

    if ($type === 'xml') {
        header('Content-Type: application/xml; charset=utf-8');
        header('Content-Disposition: inline; filename="dte_recibido_' . preg_replace('/[^A-Za-z0-9_-]/', '_', (string)$doc['document_number']) . '.xml"');
    } else {
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="dte_recibido_' . preg_replace('/[^A-Za-z0-9_-]/', '_', (string)$doc['document_number']) . '.pdf"');
    }
    header('Content-Length: ' . filesize($full));
    header('X-Content-Type-Options: nosniff');
    readfile($full);
} catch (Throwable $e) {
    error_log('Received document file error: ' . $e->getMessage());
    http_response_code(404);
    echo 'Archivo no disponible para este documento.';
}
