<?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_login();

if (!user_can('billing.inbox') && !user_can('billing.payables') && !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());
    $path = $service->filePathForDocument($id, $type, $env);

    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)$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));
    readfile($path);
} catch (Throwable $e) {
    http_response_code(404);
    echo $e->getMessage();
}
