<?php $pageTitle = 'Prompt Templates'; require __DIR__ . '/../layout/header.php'; ?>

<div class="d-flex align-items-center justify-content-between mb-4">
  <div>
    <h4 class="fw-bold mb-1">Prompt Templates</h4>
    <p class="text-muted mb-0">Templates define how the AI generates content for each page type. Variables like <code>{{business_name}}</code> are auto-injected.</p>
  </div>
  <a href="<?= BASE_URL ?>/templates/create" class="btn btn-primary">
    <i class="bi bi-plus-lg me-1"></i>New Template
  </a>
</div>

<!-- Filter by Page Type -->
<div class="mb-3 d-flex gap-2 flex-wrap" id="pt-filter">
  <button class="btn btn-sm btn-primary active" data-filter="all">All</button>
  <?php foreach ($pageTypes as $pt): ?>
  <button class="btn btn-sm btn-outline-secondary" data-filter="<?= $pt['id'] ?>"><?= htmlspecialchars($pt['name']) ?></button>
  <?php endforeach; ?>
</div>

<?php if (empty($templates)): ?>
<div class="card border-dashed border-2 text-center py-5">
  <div class="card-body">
    <i class="bi bi-chat-square-text fs-1 text-muted mb-3 d-block"></i>
    <h5>No templates yet</h5>
    <p class="text-muted">The system comes with default templates per page type — make sure you've run the seed SQL. Or create a custom template.</p>
    <a href="<?= BASE_URL ?>/templates/create" class="btn btn-primary">Create Template</a>
  </div>
</div>
<?php else: ?>
<div class="row g-3" id="templates-grid">
  <?php foreach ($templates as $tpl): ?>
  <div class="col-md-6 col-xl-4 template-card" data-page-type="<?= $tpl['page_type_id'] ?>">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between mb-2">
          <div>
            <span class="badge bg-primary-subtle text-primary mb-1"><?= htmlspecialchars($tpl['page_type_name']) ?></span>
            <h6 class="fw-semibold mb-0"><?= htmlspecialchars($tpl['name']) ?></h6>
          </div>
          <div class="d-flex gap-1">
            <span class="badge bg-light text-muted border">v<?= htmlspecialchars($tpl['version']) ?></span>
            <span class="badge <?= $tpl['is_active'] ? 'bg-success-subtle text-success' : 'bg-secondary-subtle text-secondary' ?>">
              <?= $tpl['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
          </div>
        </div>
        <p class="text-muted small mb-3"><?= htmlspecialchars(mb_strimwidth(strip_tags($tpl['system_prompt']), 0, 120, '…')) ?></p>
        <div class="border-top pt-2 d-flex justify-content-between align-items-center">
          <button class="btn btn-sm btn-link text-primary p-0" onclick="previewTemplate(<?= $tpl['id'] ?>)">
            <i class="bi bi-eye me-1"></i>Preview
          </button>
          <div class="d-flex gap-1">
            <a href="<?= BASE_URL ?>/templates/<?= $tpl['id'] ?>/edit" class="btn btn-sm btn-outline-primary">
              <i class="bi bi-pencil"></i>
            </a>
            <form method="POST" action="<?= BASE_URL ?>/templates/<?= $tpl['id'] ?>/delete" class="d-inline confirm-delete">
              <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Template Preview</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="preview-content">
        <div class="text-center py-4"><div class="spinner-border text-primary"></div></div>
      </div>
    </div>
  </div>
</div>

<?php
$templatesJson = json_encode(array_column($templates, null, 'id'));
$extraJs = <<<JS
<script>
const templates = {$templatesJson};

document.querySelectorAll('#pt-filter button').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('#pt-filter button').forEach(b => b.classList.remove('active', 'btn-primary'));
    btn.classList.add('active', 'btn-primary');
    const filter = btn.dataset.filter;
    document.querySelectorAll('.template-card').forEach(card => {
      card.style.display = filter === 'all' || card.dataset.pageType === filter ? '' : 'none';
    });
  });
});

function previewTemplate(id) {
  const tpl = templates[id];
  if (!tpl) return;
  document.getElementById('preview-content').innerHTML =
    '<h6 class="fw-semibold text-primary">System Prompt</h6>' +
    '<pre class="bg-dark text-light p-3 rounded small" style="white-space:pre-wrap;">' + escHtml(tpl.system_prompt) + '</pre>' +
    '<h6 class="fw-semibold text-success mt-4">User Prompt</h6>' +
    '<pre class="bg-dark text-light p-3 rounded small" style="white-space:pre-wrap;">' + escHtml(tpl.user_prompt) + '</pre>';
  new bootstrap.Modal(document.getElementById('previewModal')).show();
}

function escHtml(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
