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

require_login();
if (!user_can('billing.receivables') && !user_can('billing.view') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('Sin permisos.');
}

try {
    $service = new BillingReceivablesService(db());
    $doc = $service->getDocument($_GET['id'] ?? '', $_GET['env'] ?? 'sandbox');
    $type = strtolower(trim((string)($_GET['type'] ?? 'pdf')));
    $field = $type === 'xml' ? 'xml_file_path' : 'pdf_file_path';
    $path = isset($doc[$field]) ? (string)$doc[$field] : '';
    $base = realpath(__DIR__ . '/../../storage/billing');
    $candidate = $path;
    if ($candidate !== '' && $candidate[0] !== '/') $candidate = __DIR__ . '/../../' . ltrim($candidate, '/');
    $real = $candidate !== '' ? realpath($candidate) : false;
    if (!$base || !$real || strpos($real, $base) !== 0 || !is_file($real)) {
        if (empty($doc['document_id'])) throw new Exception('El documento no tiene identificador FACTO para recuperar archivos.');
        (new FactoDocumentsSyncService($doc['environment']))->refreshDocument($doc['document_id'], true);
        $doc = $service->getDocument($_GET['id'] ?? '', $doc['environment']);
        $path = isset($doc[$field]) ? (string)$doc[$field] : '';
        $candidate = $path;
        if ($candidate !== '' && $candidate[0] !== '/') $candidate = __DIR__ . '/../../' . ltrim($candidate, '/');
        $real = $candidate !== '' ? realpath($candidate) : false;
        if (!$base || !$real || strpos($real, $base) !== 0 || !is_file($real)) throw new Exception('Archivo no disponible en FACTO para este documento.');
    }

    $mime = $type === 'xml' ? 'application/xml' : 'application/pdf';
    header('Content-Type: ' . $mime);
    header('Content-Disposition: inline; filename="' . basename($real) . '"');
    header('Content-Length: ' . filesize($real));
    header('X-Content-Type-Options: nosniff');
    readfile($real);
} catch (Throwable $e) {
    error_log('Receivable document file error: ' . $e->getMessage());
    http_response_code(404);
    echo 'Archivo no disponible para este documento.';
}
