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

require_login();

if (!user_can('billing.inbox') && !user_can('billing.payables') && !user_can('billing.documents') && !user_can('billing.view') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo 'No tienes permisos.';
    exit;
}

try {
    $id = $_GET['id'] ?? '';
    $env = $_GET['env'] ?? 'sandbox';
    $type = ($_GET['type'] ?? 'pdf') === 'xml' ? 'xml' : 'pdf';
    $service = new BillingPayablesService(db());
    try {
        $path = $service->filePathForDocument($id, $type, $env);
    } catch (Throwable $missing) {
        $doc = $service->getDocument($id, $env);
        if (empty($doc['inbox_document_id'])) throw $missing;
        (new FactoInboxDocumentsSyncService($env))->refreshInboxDocument($doc['inbox_document_id'], true);
        $path = $service->filePathForDocument($id, $type, $env);
    }

    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)$id) . '.xml"');
    } else {
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="dte_recibido_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', (string)$id) . '.pdf"');
    }
    header('Content-Length: ' . filesize($path));
    header('X-Content-Type-Options: nosniff');
    readfile($path);
} catch (Throwable $e) {
    error_log('Payable document file error: ' . $e->getMessage());
    http_response_code(404);
    echo 'Archivo no disponible para este documento.';
}
