<?php
require_once __DIR__ . '/../../config/bootstrap.php';

use App\Services\AuthService;
use App\Services\PDFService;
use App\Services\Database;

$auth = new AuthService();

$signatureId = (int) ($_GET['id'] ?? 0);

try {
    $db = Database::getInstance();
    $signature = $db->fetchOne(
        "SELECT pdf_path FROM signatures WHERE id = :id",
        [':id' => $signatureId]
    );

    if (!$signature || empty($signature['pdf_path'])) {
        throw new Exception("PDF no encontrado");
    }

    $fullPath = storage_path($signature['pdf_path']);

    if (!file_exists($fullPath)) {
        throw new Exception("Archivo PDF no existe");
    }

    // Visualizar PDF en navegador (no descargar)
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="contrato_firmado_' . $signatureId . '.pdf"');
    header('Content-Length: ' . filesize($fullPath));
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');

    readfile($fullPath);
    exit;
} catch (Exception $e) {
    header('HTTP/1.1 404 Not Found');
    echo "PDF no disponible: " . $e->getMessage();
}
