<?php
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/billing/BillingPurchaseOrderService.php';

require_login();
if (!user_can('module.billing') && !user_can('billing.purchase_orders') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('No autorizado.');
}

try {
    $file = (new BillingPurchaseOrderService(db()))->resolveOrderPdf((int)($_GET['id'] ?? 0));
    $filename = preg_replace('/[^A-Za-z0-9_.-]/', '_', $file['order_number']) . '.pdf';
    header('Content-Type: application/pdf');
    header('Content-Length: ' . filesize($file['path']));
    header('Content-Disposition: inline; filename="' . $filename . '"');
    header('X-Content-Type-Options: nosniff');
    readfile($file['path']);
} catch (Throwable $e) {
    http_response_code(404);
    die('PDF no disponible.');
}
