<?php
$pageTitle = $mode === 'create' ? 'New Prompt Template' : 'Edit Template';
$v = fn($key) => htmlspecialchars($template[$key] ?? '', ENT_QUOTES, 'UTF-8');
require __DIR__ . '/../layout/header.php';
?>

<div class="d-flex align-items-center gap-3 mb-4">
  <a href="<?= BASE_URL ?>/templates" class="btn btn-sm btn-light"><i class="bi bi-arrow-left"></i></a>
  <div>
    <h4 class="fw-bold mb-0"><?= $mode === 'create' ? 'New Prompt Template' : 'Edit Template' ?></h4>
    <p class="text-muted mb-0 small">Use <code>{{variable_name}}</code> for dynamic injection. Available variables shown below.</p>
  </div>
</div>

<form method="POST" action="<?= $action ?>">
  <div class="row g-4">
    <div class="col-lg-8">

      <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white py-3">
          <h6 class="fw-semibold mb-0"><i class="bi bi-gear text-secondary me-2"></i>Template Settings</h6>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-medium">Template Name <span class="text-danger">*</span></label>
              <input type="text" name="name" class="form-control" required value="<?= $v('name') ?>" placeholder="e.g. Blog Article - SEO Standard">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-medium">Page Type <span class="text-danger">*</span></label>
              <select name="page_type_id" class="form-select" required>
                <option value="">— Select —</option>
                <?php foreach ($pageTypes as $pt): ?>
                <option value="<?= $pt['id'] ?>" <?= ($template['page_type_id'] ?? '') == $pt['id'] ? 'selected' : '' ?>><?= htmlspecialchars($pt['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label fw-medium">Version</label>
              <input type="text" name="version" class="form-control" value="<?= $v('version') ?: '1.0' ?>" placeholder="1.0">
            </div>
            <div class="col-12">
              <div class="form-check form-switch">
                <input type="hidden" name="is_active" value="0">
                <input class="form-check-input" type="checkbox" name="is_active" value="1" id="is_active"
                       <?= ($template['is_active'] ?? 1) ? 'checked' : '' ?>>
                <label class="form-check-label fw-medium" for="is_active">Active (used for generation)</label>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white py-3 d-flex align-items-center justify-content-between">
          <h6 class="fw-semibold mb-0"><i class="bi bi-cpu text-primary me-2"></i>System Prompt</h6>
          <span class="badge bg-primary-subtle text-primary small">AI Role + Rules</span>
        </div>
        <div class="card-body">
          <div class="form-text mb-2">Defines the AI's persona, brand context, writing rules, and quality standards.</div>
          <textarea name="system_prompt" class="form-control font-mono" rows="14" required
                    placeholder="You are an expert content writer for {{business_name}}. Tone: {{tone_voice}}. Audience: {{target_audience}}…"><?= $v('system_prompt') ?></textarea>
        </div>
      </div>

      <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white py-3 d-flex align-items-center justify-content-between">
          <h6 class="fw-semibold mb-0"><i class="bi bi-person-raised-hand text-success me-2"></i>User Prompt</h6>
          <span class="badge bg-success-subtle text-success small">The Request</span>
        </div>
        <div class="card-body">
          <div class="form-text mb-2">The specific generation request sent per topic. Include topic details here.</div>
          <textarea name="user_prompt" class="form-control font-mono" rows="8" required
                    placeholder="Write a {{target_word_count}}-word blog article about: {{title}}. Primary keyword: {{primary_keyword}}…"><?= $v('user_prompt') ?></textarea>
        </div>
      </div>

      <div class="d-flex gap-2 justify-content-end">
        <a href="<?= BASE_URL ?>/templates" class="btn btn-light">Cancel</a>
        <button type="submit" class="btn btn-primary px-4">
          <i class="bi bi-<?= $mode === 'create' ? 'plus-lg' : 'check-lg' ?> me-1"></i>
          <?= $mode === 'create' ? 'Create Template' : 'Save Changes' ?>
        </button>
      </div>

    </div>

    <!-- Variable Reference -->
    <div class="col-lg-4">
      <div class="card border-0 shadow-sm sticky-top" style="top:70px;">
        <div class="card-header bg-white py-3">
          <h6 class="fw-semibold mb-0"><i class="bi bi-code-slash text-warning me-2"></i>Available Variables</h6>
        </div>
        <div class="card-body p-0">
          <div class="accordion accordion-flush" id="varAccordion">

            <div class="accordion-item border-0">
              <h2 class="accordion-header">
                <button class="accordion-button py-2 small fw-semibold" type="button" data-bs-toggle="collapse" data-bs-target="#varProject">
                  <i class="bi bi-briefcase text-primary me-2"></i>Project Variables
                </button>
              </h2>
              <div id="varProject" class="accordion-collapse collapse show" data-bs-parent="#varAccordion">
                <div class="accordion-body py-2 px-3">
                  <?php
                  $projectVars = ['business_name','website_url','target_audience','content_intent','brand_positioning','tone_voice','brand_dos','brand_donts','pov_type','seo_philosophy','compliance_rules','cta_style','no_no_words'];
                  foreach ($projectVars as $v2): ?>
                  <code class="d-block small text-muted mb-1 cursor-pointer var-tag" onclick="insertVar('{{<?= $v2 ?>}}')" title="Click to copy">{{<?= $v2 ?>}}</code>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>

            <div class="accordion-item border-0 border-top">
              <h2 class="accordion-header">
                <button class="accordion-button py-2 small fw-semibold collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#varTopic">
                  <i class="bi bi-tag text-success me-2"></i>Topic Variables
                </button>
              </h2>
              <div id="varTopic" class="accordion-collapse collapse" data-bs-parent="#varAccordion">
                <div class="accordion-body py-2 px-3">
                  <?php
                  $topicVars = ['title','primary_keyword','supporting_keywords','search_intent','content_angle','target_word_count'];
                  foreach ($topicVars as $v2): ?>
                  <code class="d-block small text-muted mb-1 cursor-pointer var-tag" onclick="insertVar('{{<?= $v2 ?>}}')" title="Click to copy">{{<?= $v2 ?>}}</code>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>

            <div class="accordion-item border-0 border-top">
              <h2 class="accordion-header">
                <button class="accordion-button py-2 small fw-semibold collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#varPageType">
                  <i class="bi bi-file-richtext text-warning me-2"></i>Page Type Variables
                </button>
              </h2>
              <div id="varPageType" class="accordion-collapse collapse" data-bs-parent="#varAccordion">
                <div class="accordion-body py-2 px-3">
                  <?php
                  $ptVars = ['page_type_name','structure_rules','content_blocks','seo_rules','min_word_count','max_word_count'];
                  foreach ($ptVars as $v2): ?>
                  <code class="d-block small text-muted mb-1 cursor-pointer var-tag" onclick="insertVar('{{<?= $v2 ?>}}')" title="Click to copy">{{<?= $v2 ?>}}</code>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>

          </div>
        </div>
        <div class="card-footer bg-light py-2">
          <div class="text-muted" style="font-size:11px;"><i class="bi bi-info-circle me-1"></i>Click any variable to insert at cursor position</div>
        </div>
      </div>
    </div>

  </div>
</form>

<?php
$extraJs = <<<JS
<script>
let lastFocused = null;
document.querySelectorAll('textarea').forEach(t => t.addEventListener('focus', () => lastFocused = t));

function insertVar(text) {
  const target = lastFocused || document.querySelector('[name="system_prompt"]');
  if (!target) return;
  const pos = target.selectionStart;
  const val = target.value;
  target.value = val.slice(0, pos) + text + val.slice(target.selectionEnd);
  target.selectionStart = target.selectionEnd = pos + text.length;
  target.focus();
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
