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

$declarationId = $_GET['declaration_id'] ?? null;

if (!$declarationId) {
    http_response_code(400);
    echo json_encode(["error" => "Missing declaration_id"]);
    exit;
}

// Authoritative check: must be APPROVED
$status = MdDeclaration::getStatus($declarationId);
if ($status !== 'APPROVED') {
    http_response_code(403);
    echo json_encode(["error" => "Declaration not approved"]);
    exit;
}

// Generate or fetch cached PDF
$pdfPath = MdPdfGenerator::generate($declarationId);

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="MD_'.$declarationId.'.pdf"');
readfile($pdfPath);

audit_log(
    $pdo,
    $user,
    'view',
    'md_declaration',
    $declarationId,
    [
        'reason' => 'open',
        'source' => 'mobile'
    ]
);
