<?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();
$category = $_GET['category'] ?? 'All';
$q = strtolower(trim((string)($_GET['q'] ?? '')));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        $deleteMessage = '';
        mdw_delete_saved_document($id, $deleteMessage) ? mdw_flash($deleteMessage ?: 'Document deleted.') : mdw_flash($deleteMessage ?: 'Could not delete document. Check write permissions on documents/saved/.', 'error');
        header('Location: documents.php'); exit;
    }
}

mdw_render_header('Documents');
?>
<section class="panel">
  <h2>Documents</h2>
  <p class="muted">Create branded contracts, proposals, intake forms, invoices, licenses, and setup documents. Saved records now write to documents/saved/records, invoices write to documents/invoices, and CSV exports write to documents/exports.</p>
</section>

<section class="panel">
  <h2>Quick Access</h2>
  <div class="doc-template-grid compact">
  <?php foreach ($templates as $key => $template): if (empty($template['quick'])) continue; ?>
    <section class="doc-template">
      <span class="doc-category"><?php echo mdw_h($template['category'] ?? 'General'); ?></span>
      <h3><?php echo mdw_h($template['name']); ?></h3>
      <p class="muted"><?php echo mdw_h($template['description']); ?></p>
      <a class="button" href="document-edit.php?template=<?php echo urlencode($key); ?>">Create / Fill Out</a>
    </section>
  <?php endforeach; ?>
  </div>
</section>

<section class="panel" style="margin-top:20px">
  <h2>Document Library</h2>
  <form class="toolbar" method="get">
    <input name="q" placeholder="Search documents..." value="<?php echo mdw_h($_GET['q'] ?? ''); ?>">
    <select name="category"><option>All</option><?php foreach (mdw_document_categories() as $cat): ?><option <?php echo $category===$cat?'selected':''; ?>><?php echo mdw_h($cat); ?></option><?php endforeach; ?></select>
    <button class="button" type="submit">Filter</button>
    <a class="button ghost" href="documents.php">Reset</a>
  </form>
  <table><thead><tr><th>Template</th><th>Category</th><th>Description</th><th>Action</th></tr></thead><tbody>
  <?php foreach ($templates as $key => $template):
    $cat = $template['category'] ?? 'General';
    if ($category !== 'All' && $category !== $cat) continue;
    $hay = strtolower($template['name'] . ' ' . $template['description'] . ' ' . $cat);
    if ($q && !str_contains($hay, $q)) continue;
  ?>
    <tr><td><strong><?php echo mdw_h($template['name']); ?></strong></td><td><span class="doc-category"><?php echo mdw_h($cat); ?></span></td><td><?php echo mdw_h($template['description']); ?></td><td><a class="button" href="document-edit.php?template=<?php echo urlencode($key); ?>">Create</a></td></tr>
  <?php endforeach; ?>
  </tbody></table>
</section>

<section class="panel" id="saved-documents" style="margin-top:20px">
  <h2>Saved Documents</h2>
  <p class="muted">Saved documents are client-ready copies created from templates. Invoices created here use MDW invoice numbers and can be exported later to the accounting program. <a class="button ghost" href="invoices-export.php">Export invoice CSV</a></p>
  <?php if (!$documents): ?>
    <p class="muted">No saved documents yet.</p>
  <?php else: ?>
  <table>
    <thead><tr><th>Title</th><th>Client</th><th>Type</th><th>Status</th><th>Updated</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach (array_reverse($documents) as $doc): $tkey=$doc['template']??''; $t=$templates[$tkey]??[]; ?>
      <tr>
        <td><strong><?php echo mdw_h($doc['title'] ?? 'Untitled'); ?></strong></td>
        <td><?php echo mdw_h($doc['client_name'] ?? mdw_client_name($clients, $doc['client_id'] ?? '')); ?></td>
        <td><?php echo mdw_h($t['name'] ?? ($doc['template'] ?? 'Document')); ?><br><span class="doc-category"><?php echo mdw_h($t['category'] ?? ''); ?></span></td>
        <td><?php echo mdw_h($doc['status'] ?? 'Draft'); ?></td>
        <td><?php echo mdw_h($doc['updated_at'] ?? ''); ?></td>
        <td class="row-actions">
          <a class="button" href="document-view.php?id=<?php echo urlencode($doc['id'] ?? ''); ?>">View / Print</a>
          <a class="button ghost" href="document-edit.php?id=<?php echo urlencode($doc['id'] ?? ''); ?>">Edit</a>
          <form method="post" onsubmit="return confirm('Delete this document?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?php echo mdw_h($doc['id'] ?? ''); ?>"><button class="button danger" type="submit">Delete</button></form>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <?php endif; ?>
</section>
<?php mdw_render_footer(); ?>
