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

$documents = mdw_saved_documents();
$templates = mdw_document_templates();
$clients = mdw_clients();

$id = $_GET['id'] ?? '';
$doc = null;
foreach ($documents as $item) if (($item['id'] ?? '') === $id) { $doc = $item; break; }
$templateKey = $doc['template'] ?? ($_GET['template'] ?? 'service-agreement');
$template = mdw_template_by_key($templateKey);
if (!$template) { mdw_flash('Unknown document template.', 'error'); header('Location: documents.php'); exit; }
$selectedClient = $doc['client_id'] ?? ($_GET['client'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $templateKey = $_POST['template'] ?? $templateKey;
    $template = mdw_template_by_key($templateKey);
    if (!$template) { mdw_flash('Unknown document template.', 'error'); header('Location: documents.php'); exit; }
    $id = $_POST['id'] ?: ('doc-' . date('Ymd-His') . '-' . substr(md5((string)mt_rand()), 0, 6));
    $fields = [];
    foreach ($template['fields'] as $fieldKey => $field) $fields[$fieldKey] = trim((string)($_POST['fields'][$fieldKey] ?? ''));
    $isNewDocument = empty($_POST['id']);
    if ($templateKey === 'invoice' && $isNewDocument && mdw_is_blank_invoice_number((string)($fields['invoice_number'] ?? ''))) {
        $fields['invoice_number'] = mdw_claim_next_invoice_number();
    }
    $clientId = trim((string)($_POST['client_id'] ?? ''));
    $clientName = mdw_client_name($clients, $clientId);
    $title = trim((string)($_POST['title'] ?? '')) ?: $template['name'];
    $status = trim((string)($_POST['status'] ?? 'Draft'));
    $newDoc = [
        'id' => $id,
        'template' => $templateKey,
        'title' => $title,
        'client_id' => $clientId,
        'client_name' => $clientName,
        'status' => $status,
        'source_system' => $templateKey === 'invoice' ? 'MDW Admin' : ($doc['source_system'] ?? 'MDW Admin'),
        'source_reference' => $templateKey === 'invoice' ? ($fields['invoice_number'] ?? '') : ($doc['source_reference'] ?? ''),
        'fields' => $fields,
        'created_at' => $doc['created_at'] ?? date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    ];
    $found = false;
    foreach ($documents as $idx => $item) if (($item['id'] ?? '') === $id) { $documents[$idx] = $newDoc; $found = true; break; }
    if (!$found) $documents[] = $newDoc;
    if (mdw_write_documents($documents)) { mdw_flash('Document saved.'); header('Location: document-view.php?id=' . urlencode($id)); exit; }
    mdw_flash('Could not save document. Check write permissions on devworks-admin/documents/saved/.', 'error');
}

$values = $doc['fields'] ?? [];
mdw_render_header($doc ? 'Edit Document' : 'Create Document');
?>
<section class="panel">
  <p><a class="button ghost" href="documents.php">← Back to Documents</a></p>
  <h2><?php echo mdw_h($template['name']); ?></h2>
  <p class="muted"><?php echo mdw_h($template['description']); ?></p>
  <form method="post">
    <input type="hidden" name="id" value="<?php echo mdw_h($doc['id'] ?? ''); ?>">
    <input type="hidden" name="template" value="<?php echo mdw_h($templateKey); ?>">
    <div class="split">
      <div><label>Document Title</label><input name="title" value="<?php echo mdw_h($doc['title'] ?? $template['name']); ?>"></div>
      <div><label>Client</label><select name="client_id"><option value="">No client selected</option><?php foreach($clients as $client): $cid=$client['id']??''; ?><option value="<?php echo mdw_h($cid); ?>" <?php echo $selectedClient===$cid?'selected':''; ?>><?php echo mdw_h($client['business_name'] ?: ($client['client_name'] ?? 'Unnamed')); ?></option><?php endforeach; ?></select></div>
      <div><label>Status</label><select name="status"><?php foreach(['Draft','Ready','Sent','Signed','Paid','Archived'] as $s): ?><option <?php echo (($doc['status'] ?? 'Draft')===$s)?'selected':''; ?>><?php echo mdw_h($s); ?></option><?php endforeach; ?></select></div>
    </div>
    <?php foreach ($template['fields'] as $fieldKey => $field): ?>
      <label><?php echo mdw_h($field['label']); ?></label>
      <?php $val = $values[$fieldKey] ?? ($field['default'] ?? ''); ?>
      <?php if (($field['type'] ?? 'text') === 'textarea'): ?>
        <textarea name="fields[<?php echo mdw_h($fieldKey); ?>]"><?php echo mdw_h($val); ?></textarea>
      <?php else: ?>
        <input name="fields[<?php echo mdw_h($fieldKey); ?>]" value="<?php echo mdw_h($val); ?>">
      <?php endif; ?>
    <?php endforeach; ?>
    <p class="row-actions" style="margin-top:18px">
      <button class="button" type="submit">Save Document</button>
      <?php if ($doc): ?><a class="button ghost" target="_blank" href="document-preview.php?id=<?php echo urlencode($doc['id']); ?>">Preview Saved Copy</a><?php endif; ?>
      <button class="button ghost" type="submit" formaction="document-preview.php" formmethod="post" formtarget="_blank">Preview Before Saving</button>
      <a class="button ghost" href="documents.php">Cancel</a>
    </p>
  </form>
</section>
<?php mdw_render_footer(); ?>
