<?php

require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/format.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/crm/CrmQuotePdfService.php';

require_login();
require_permission('module.crm');

try {
    $result = (new CrmQuotePdfService(db()))->render((int)($_GET['id'] ?? 0));
    $content = (string)$result['content'];
    header('Content-Type: application/pdf');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: attachment; filename="' . $result['filename'] . '"');
    header('Cache-Control: private, no-store, max-age=0');
    header('X-Content-Type-Options: nosniff');
    echo $content;
} catch (Throwable $e) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'No fue posible generar el PDF de la cotización.';
}
