<?php
require_once __DIR__ . '/document-templates.php';

function mdw_doc_text(string $text): string {
    return nl2br(mdw_h($text));
}

function mdw_doc_header(array $doc): string {
    return '<div class="doc-letterhead">'
        . '<div class="doc-brand-row">'
        . '<img class="doc-logo-icon" src="../images/logo/murdock-devworks-icon.png" alt="Murdock DevWorks" onerror="this.style.display=\'none\'">'
        . '<div><div class="doc-brand-name">Murdock DevWorks</div>'
        . '<div class="doc-brand-sub">Independent Software • Self-Hosted Tools • Digital Downloads</div></div>'
        . '</div>'
        . '</div>';
}

function mdw_render_invoice_table(array $doc): string {
    $rows = preg_split('/\r\n|\r|\n/', mdw_doc_display_value($doc, 'line_items')) ?: [];
    $html = '<table class="doc-table"><tr><th>Service</th><th>Qty</th><th>Amount</th></tr>';
    foreach ($rows as $line) {
        $line = trim($line);
        if ($line === '') continue;
        $parts = array_map('trim', explode('|', $line));
        $html .= '<tr><td>' . mdw_h($parts[0] ?? '') . '</td><td>' . mdw_h($parts[1] ?? '') . '</td><td>' . mdw_h($parts[2] ?? '') . '</td></tr>';
    }
    $html .= '<tr><td colspan="2"><strong>Subtotal</strong></td><td>' . mdw_h(mdw_doc_display_value($doc, 'subtotal')) . '</td></tr>';
    $html .= '<tr><td colspan="2"><strong>Tax</strong></td><td>' . mdw_h(mdw_doc_display_value($doc, 'tax')) . '</td></tr>';
    $html .= '<tr><td colspan="2"><strong>Total Due</strong></td><td><strong>' . mdw_h(mdw_doc_display_value($doc, 'total_due')) . '</strong></td></tr>';
    $html .= '</table>';
    return $html;
}

function mdw_render_document_paper(array $doc): string {
    $templateKey = (string)($doc['template'] ?? '');
    $template = mdw_template_by_key($templateKey) ?: ['sections' => [], 'fields' => []];
    ob_start();
    ?>
<div class="doc-paper">
<?php echo mdw_doc_header($doc); ?>
<h1><?php echo mdw_h($doc['title'] ?? ($template['name'] ?? 'Document')); ?></h1>
<?php if (!empty($doc['client_name'])): ?><p><strong>Client:</strong> <?php echo mdw_h($doc['client_name']); ?></p><?php endif; ?>
<?php if ($templateKey === 'pricing-guide'): ?>
  <p><strong>Prepared For:</strong> <?php echo mdw_h(mdw_doc_display_value($doc, 'prepared_for')); ?></p>
  <p><strong>Effective Date:</strong> <?php echo mdw_h(mdw_doc_display_value($doc, 'effective_date')); ?></p>
  <div class="doc-note"><?php echo mdw_doc_text(mdw_doc_display_value($doc, 'intro')); ?></div>
  <h2>Starting Price Guide</h2>
  <table class="doc-table">
    <tr><th>Service</th><th>Starting Range</th></tr>
    <tr><td>Simple Business Website</td><td><?php echo mdw_h(mdw_doc_display_value($doc, 'simple_site')); ?></td></tr>
    <tr><td>Custom Site With Admin</td><td><?php echo mdw_h(mdw_doc_display_value($doc, 'custom_site')); ?></td></tr>
    <tr><td>Custom Web App / Workflow Tool</td><td><?php echo mdw_h(mdw_doc_display_value($doc, 'web_app')); ?></td></tr>
    <tr><td>Monthly Maintenance</td><td><?php echo mdw_h(mdw_doc_display_value($doc, 'maintenance')); ?></td></tr>
    <tr><td>Hosting / Setup / Migration Assistance</td><td><?php echo mdw_h(mdw_doc_display_value($doc, 'setup_migration')); ?></td></tr>
    <tr><td>Custom Integrations</td><td><?php echo mdw_h(mdw_doc_display_value($doc, 'custom_integrations')); ?></td></tr>
  </table>
  <h2>Notes</h2><p><?php echo mdw_doc_text(mdw_doc_display_value($doc, 'terms')); ?></p>
<?php elseif ($templateKey === 'invoice'): ?>
  <div class="inline-fields"><div><h3>Invoice #</h3><p><?php echo mdw_h(mdw_doc_display_value($doc, 'invoice_number')); ?></p></div><div><h3>Date</h3><p><?php echo mdw_h(mdw_doc_display_value($doc, 'invoice_date')); ?></p></div><div><h3>Due</h3><p><?php echo mdw_h(mdw_doc_display_value($doc, 'due_date')); ?></p></div></div>
  <h2>Bill To</h2><p><?php echo mdw_h(mdw_doc_display_value($doc, 'client_name')); ?></p>
  <h2>Project / Description</h2><p><?php echo mdw_h(mdw_doc_display_value($doc, 'project_name')); ?></p>
  <?php echo mdw_render_invoice_table($doc); ?>
  <h2>Payment Notes</h2><p><?php echo mdw_doc_text(mdw_doc_display_value($doc, 'payment_notes')); ?></p>
<?php else: ?>
  <?php foreach (($template['sections'] ?? []) as $sectionTitle => $fieldKeys): ?>
    <h2><?php echo mdw_h($sectionTitle); ?></h2>
    <?php foreach ($fieldKeys as $fieldKey): $field = $template['fields'][$fieldKey] ?? null; if (!$field) continue; $value = mdw_doc_display_value($doc, $fieldKey); ?>
      <div class="doc-field-block"><h3><?php echo mdw_h($field['label'] ?? $fieldKey); ?></h3><p><?php echo mdw_doc_text($value); ?></p></div>
    <?php endforeach; ?>
  <?php endforeach; ?>
  <?php if (!empty($template['legal_note'])): ?><div class="doc-note"><?php echo mdw_doc_text($template['legal_note']); ?></div><?php endif; ?>
<?php endif; ?>
<div class="signature-grid"><div><strong>Client Signature</strong><br><br>_________________________________<br>Date: ________________</div><div><strong>Murdock DevWorks</strong><br><br>_________________________________<br>Date: ________________</div></div>
<div class="doc-footer">Murdock DevWorks • Practical software, self-hosted tools, and digital products</div>
</div>
    <?php
    return ob_get_clean();
}

function mdw_document_full_html(array $doc): string {
    $css = '';
    $cssFile = dirname(__DIR__) . '/assets/admin.css';
    if (file_exists($cssFile)) $css = file_get_contents($cssFile);
    return '<!doctype html><html><head><meta charset="utf-8"><title>' . mdw_h($doc['title'] ?? 'Document') . '</title><style>' . $css . '</style></head><body>' . mdw_render_document_paper($doc) . '</body></html>';
}
