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

<div class="d-flex align-items-center justify-content-between mb-4">
  <div>
    <h4 class="fw-bold mb-1">Topics</h4>
    <p class="text-muted mb-0">Manage content topics. Select topics to generate content in one click.</p>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= BASE_URL ?>/topics/bulk-upload" class="btn btn-outline-secondary">
      <i class="bi bi-upload me-1"></i>Bulk Upload
    </a>
    <a href="<?= BASE_URL ?>/topics/create<?= $projectId ? '?project_id=' . $projectId : '' ?>" class="btn btn-primary">
      <i class="bi bi-plus-lg me-1"></i>Add Topic
    </a>
  </div>
</div>

<!-- Project Filter -->
<div class="card border-0 shadow-sm mb-4">
  <div class="card-body py-3">
    <form method="GET" action="<?= BASE_URL ?>/topics" class="d-flex align-items-center gap-3 flex-wrap">
      <label class="fw-medium text-nowrap mb-0">Filter by Project:</label>
      <select name="project_id" class="form-select" style="max-width:280px;" onchange="this.form.submit()">
        <option value="">— All Projects —</option>
        <?php foreach ($projects as $p): ?>
        <option value="<?= $p['id'] ?>" <?= $projectId == $p['id'] ? 'selected' : '' ?>>
          <?= htmlspecialchars($p['business_name']) ?>
        </option>
        <?php endforeach; ?>
      </select>
      <?php if ($projectId): ?>
      <a href="<?= BASE_URL ?>/content/generate?project_id=<?= $projectId ?>" class="btn btn-success ms-auto">
        <i class="bi bi-lightning me-1"></i>Generate Content for This Project
      </a>
      <?php endif; ?>
    </form>
  </div>
</div>

<?php if (empty($topics) && $projectId): ?>
<div class="card border-dashed border-2 text-center py-5">
  <div class="card-body">
    <i class="bi bi-tags fs-1 text-muted mb-3 d-block"></i>
    <h5>No topics yet for this project</h5>
    <p class="text-muted">Add topics manually or bulk upload via CSV.</p>
    <div class="d-flex gap-2 justify-content-center">
      <a href="<?= BASE_URL ?>/topics/create?project_id=<?= $projectId ?>" class="btn btn-primary">
        <i class="bi bi-plus-lg me-1"></i>Add Topic
      </a>
      <a href="<?= BASE_URL ?>/topics/bulk-upload" class="btn btn-outline-secondary">
        <i class="bi bi-upload me-1"></i>Bulk Upload
      </a>
    </div>
  </div>
</div>
<?php elseif (empty($topics)): ?>
<div class="alert alert-info">Select a project above to see its topics.</div>
<?php else: ?>

<!-- Status Summary -->
<div class="row g-2 mb-3">
  <?php
  $statusCounts = array_count_values(array_column($topics, 'status'));
  $statusDefs = [
    'pending'    => ['label' => 'Pending',    'color' => 'warning'],
    'generating' => ['label' => 'Generating', 'color' => 'info'],
    'generated'  => ['label' => 'Generated',  'color' => 'success'],
    'approved'   => ['label' => 'Approved',   'color' => 'primary'],
    'failed'     => ['label' => 'Failed',     'color' => 'danger'],
  ];
  foreach ($statusDefs as $s => $def):
    $cnt = $statusCounts[$s] ?? 0;
    if ($cnt === 0) continue;
  ?>
  <div class="col-auto">
    <span class="badge bg-<?= $def['color'] ?>-subtle text-<?= $def['color'] ?> px-3 py-2 fs-6">
      <?= $def['label'] ?>: <?= $cnt ?>
    </span>
  </div>
  <?php endforeach; ?>
</div>

<div class="card border-0 shadow-sm">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-hover mb-0 align-middle" id="topics-table">
        <thead class="table-light">
          <tr>
            <th width="20"><input type="checkbox" id="select-all" class="form-check-input"></th>
            <th>Title / Keyword</th>
            <th>Page Type</th>
            <th>Search Intent</th>
            <th>Words</th>
            <th>Status</th>
            <th>Created</th>
            <th class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($topics as $t): ?>
          <tr>
            <td><input type="checkbox" class="form-check-input topic-check" value="<?= $t['id'] ?>"></td>
            <td>
              <div class="fw-medium"><?= htmlspecialchars(mb_strimwidth($t['title'], 0, 60, '…')) ?></div>
              <div class="text-muted small"><i class="bi bi-key me-1"></i><?= htmlspecialchars($t['primary_keyword']) ?></div>
            </td>
            <td><span class="badge bg-secondary-subtle text-secondary"><?= htmlspecialchars($t['page_type_name']) ?></span></td>
            <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($t['search_intent']) ?></span></td>
            <td><?= number_format($t['target_word_count']) ?></td>
            <td>
              <?php
              $statusMap = [
                'pending'    => 'warning',
                'generating' => 'info',
                'generated'  => 'success',
                'approved'   => 'primary',
                'failed'     => 'danger',
              ];
              $sc = $statusMap[$t['status']] ?? 'secondary';
              echo '<span class="badge bg-' . $sc . '-subtle text-' . $sc . '">' . htmlspecialchars($t['status']) . '</span>';
              ?>
            </td>
            <td class="text-muted small"><?= date('M j', strtotime($t['created_at'])) ?></td>
            <td class="text-end">
              <div class="d-flex gap-1 justify-content-end">
                <a href="<?= BASE_URL ?>/topics/<?= $t['id'] ?>/edit" class="btn btn-sm btn-outline-primary" title="Edit"><i class="bi bi-pencil"></i></a>
                <form method="POST" action="<?= BASE_URL ?>/topics/<?= $t['id'] ?>/delete" class="d-inline confirm-delete">
                  <button class="btn btn-sm btn-outline-danger" title="Delete"><i class="bi bi-trash"></i></button>
                </form>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php if ($projectId): ?>
  <div class="card-footer bg-white py-3 d-flex align-items-center gap-3">
    <span class="text-muted small" id="selected-count">0 selected</span>
    <!-- Hidden form used by JS to POST topic_ids directly to generate -->
    <form method="POST" action="<?= BASE_URL ?>/content/generate" id="generate-form" style="display:none;">
      <input type="hidden" name="project_id" value="<?= $projectId ?>">
      <div id="generate-form-ids"></div>
    </form>
    <button id="generate-selected-btn" type="button" onclick="submitGenerate()"
            class="btn btn-success btn-sm disabled">
      <i class="bi bi-lightning me-1"></i>Generate Selected
    </button>
    <a href="<?= BASE_URL ?>/content/generate?project_id=<?= $projectId ?>" class="btn btn-outline-success btn-sm ms-auto">
      <i class="bi bi-lightning me-1"></i>Generate All Pending
    </a>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<?php
$extraJs = <<<JS
<script>
const selectAll = document.getElementById('select-all');
const checks    = document.querySelectorAll('.topic-check');
const countEl   = document.getElementById('selected-count');
const genBtn    = document.getElementById('generate-selected-btn');

function updateSelected() {
  const selected = [...checks].filter(c => c.checked).map(c => c.value);
  if (countEl) countEl.textContent = selected.length + ' selected';
  if (genBtn) {
    if (selected.length > 0) genBtn.classList.remove('disabled');
    else genBtn.classList.add('disabled');
  }
}

function submitGenerate() {
  const selected = [...checks].filter(c => c.checked).map(c => c.value);
  if (!selected.length) return;
  const container = document.getElementById('generate-form-ids');
  container.innerHTML = '';
  selected.forEach(function(id) {
    const inp = document.createElement('input');
    inp.type = 'hidden'; inp.name = 'topic_ids[]'; inp.value = id;
    container.appendChild(inp);
  });
  document.getElementById('generate-form').submit();
}

if (selectAll) {
  selectAll.addEventListener('change', () => {
    checks.forEach(c => c.checked = selectAll.checked);
    updateSelected();
  });
}
checks.forEach(c => c.addEventListener('change', updateSelected));

if (document.getElementById('topics-table')) {
  $('#topics-table').DataTable({ pageLength: 25, order: [[6, 'desc']] });
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
