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

global $mdw_documents_file;
if (!isset($mdw_documents_file)) $mdw_documents_file = __DIR__ . '/data/documents.json';

$doc = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $templateKey = (string)($_POST['template'] ?? 'pricing-guide');
    $template = mdw_template_by_key($templateKey);
    if (!$template) {
        http_response_code(400);
        echo 'Unknown document template.';
        exit;
    }
    $fields = [];
    foreach ($template['fields'] as $fieldKey => $field) {
        $fields[$fieldKey] = trim((string)($_POST['fields'][$fieldKey] ?? ''));
    }
    if ($templateKey === 'invoice' && mdw_is_blank_invoice_number((string)($fields['invoice_number'] ?? ''))) {
        $fields['invoice_number'] = mdw_peek_next_invoice_number();
    }
    $clients = mdw_clients();
    $clientId = trim((string)($_POST['client_id'] ?? ''));
    $clientName = mdw_client_name($clients, $clientId);
    $doc = [
        'id' => (string)($_POST['id'] ?? ''),
        'template' => $templateKey,
        'title' => trim((string)($_POST['title'] ?? '')) ?: $template['name'],
        'client_id' => $clientId,
        'client_name' => $clientName,
        'source_system' => $templateKey === 'invoice' ? 'MDW Admin' : '',
        'source_reference' => $templateKey === 'invoice' ? ($fields['invoice_number'] ?? '') : '',
        'fields' => $fields,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    ];
} else {
    $documents = mdw_read_json($mdw_documents_file, []);
    $id = $_GET['id'] ?? '';
    foreach ($documents as $item) {
        if (($item['id'] ?? '') === $id) { $doc = $item; break; }
    }
}

if (!$doc) {
    http_response_code(404);
    echo 'Document not found.';
    exit;
}

?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo mdw_h($doc['title'] ?? 'Document Preview'); ?> | Preview</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body class="doc-preview-body">
<div class="doc-popout-toolbar no-print">
  <div class="doc-popout-title"><strong>Document Preview</strong><span>Review, print, or save as PDF</span></div>
  <div class="doc-popout-actions">
    <button class="button" onclick="window.print()">Print / Save as PDF</button>
    <button class="button ghost" onclick="window.close()">Close</button>
  </div>
</div>
<main class="doc-popout-main">
<?php echo mdw_render_document_paper($doc); ?>
</main>
</body>
</html>
