<?php
require_once __DIR__ . '/lib/functions.php';
require_once __DIR__ . '/lib/document-render.php';
mdw_require_login();

global $mdw_documents_file;
if (!isset($mdw_documents_file)) $mdw_documents_file = __DIR__ . '/data/documents.json';
$documents = mdw_read_json($mdw_documents_file, []);
$id = $_GET['id'] ?? '';
$doc = null;
foreach ($documents as $item) {
    if (($item['id'] ?? '') === $id) { $doc = $item; break; }
}
if (!$doc) { mdw_flash('Document not found.', 'error'); header('Location: documents.php'); exit; }
$template = mdw_template_by_key($doc['template'] ?? '');
if (!$template) { mdw_flash('Unknown document template.', 'error'); header('Location: documents.php'); exit; }

if (isset($_GET['download']) && $_GET['download'] === 'html') {
    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . mdw_slug($doc['title'] ?? 'document') . '.html"');
    echo mdw_document_full_html($doc);
    exit;
}

$paper = mdw_render_document_paper($doc);
mdw_render_header('View Document');
?>
<div class="doc-preview-actions">
  <button class="button" onclick="window.print()">Print / Save as PDF</button>
  <a class="button" target="_blank" href="document-preview.php?id=<?php echo urlencode($id); ?>">Pop-out Preview</a>
  <a class="button" href="document-email.php?id=<?php echo urlencode($id); ?>">Email Document</a>
  <a class="button" href="document-view.php?id=<?php echo urlencode($id); ?>&download=html">Download HTML</a>
  <a class="button ghost" href="document-edit.php?id=<?php echo urlencode($id); ?>">Edit</a>
  <a class="button ghost" href="documents.php">Back to Documents</a>
</div>
<?php echo $paper; ?>
<?php mdw_render_footer(); ?>
