<?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_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';
    $path = $type === 'xml' ? ($doc['xml_file_path'] ?? '') : ($doc['pdf_file_path'] ?? '');
    if (!$path) throw new Exception('Archivo no disponible.');

    $base = realpath(__DIR__ . '/../../storage/billing');
    $full = realpath(__DIR__ . '/../../' . ltrim($path, '/'));
    if (!$base || !$full || strpos($full, $base) !== 0 || !is_file($full)) {
        throw new Exception('Archivo no disponible en storage autorizado.');
    }

    if ($type === 'xml') {
        header('Content-Type: application/xml; charset=utf-8');
        header('Content-Disposition: attachment; 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"');
    }
    readfile($full);
} catch (Throwable $e) {
    http_response_code(404);
    echo $e->getMessage();
}
