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

<div class="d-flex align-items-center gap-3 mb-4">
  <div>
    <h4 class="fw-bold mb-1"><i class="bi bi-lightning-fill text-warning me-2"></i>Generate Content</h4>
    <p class="text-muted mb-0">Select a project and topics, then click Generate. The engine handles everything else.</p>
  </div>
</div>

<!-- Step 1: Select Project -->
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header bg-white py-3 d-flex align-items-center gap-2">
    <span class="badge bg-primary rounded-circle" style="width:26px;height:26px;line-height:26px;font-size:13px;display:inline-flex;align-items:center;justify-content:center;">1</span>
    <h6 class="fw-semibold mb-0">Select Project</h6>
  </div>
  <div class="card-body">
    <form method="GET" action="<?= BASE_URL ?>/content/generate" id="project-form">
      <div class="row g-3 align-items-end">
        <div class="col-md-6">
          <label class="form-label fw-medium">Project</label>
          <select name="project_id" class="form-select" onchange="this.form.submit()">
            <option value="">— Select a Project —</option>
            <?php foreach ($projects as $p): ?>
            <option value="<?= $p['id'] ?>" <?= $selProject == $p['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($p['business_name']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php if ($selProject): ?>
        <div class="col-auto">
          <a href="<?= BASE_URL ?>/projects/<?= $selProject ?>/edit" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-pencil me-1"></i>Edit Project Rules
          </a>
        </div>
        <?php endif; ?>
      </div>
    </form>
  </div>
</div>

<?php if ($selProject && empty($topics)): ?>
<div class="alert alert-info d-flex align-items-center gap-2">
  <i class="bi bi-info-circle fs-5"></i>
  <span>No pending topics for this project. <a href="<?= BASE_URL ?>/topics/create?project_id=<?= $selProject ?>">Add topics</a> or <a href="<?= BASE_URL ?>/topics/bulk-upload">bulk upload</a> first.</span>
</div>
<?php elseif ($selProject && !empty($topics)): ?>

<!-- Step 2: Select Topics -->
<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">
    <div class="d-flex align-items-center gap-2">
      <span class="badge bg-primary rounded-circle" style="width:26px;height:26px;line-height:26px;font-size:13px;display:inline-flex;align-items:center;justify-content:center;">2</span>
      <h6 class="fw-semibold mb-0">Select Topics to Generate</h6>
    </div>
    <div class="d-flex align-items-center gap-3">
      <label class="form-check d-flex align-items-center gap-2 mb-0 cursor-pointer">
        <input type="checkbox" id="select-all" class="form-check-input"> <span class="small">Select All (<?= count($topics) ?>)</span>
      </label>
      <span class="badge bg-warning-subtle text-warning" id="selected-badge">0 selected</span>
    </div>
  </div>
  <form method="POST" action="<?= BASE_URL ?>/content/generate" id="generate-form">
    <input type="hidden" name="project_id" value="<?= $selProject ?>">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover mb-0 align-middle">
          <thead class="table-light">
            <tr>
              <th width="40"></th>
              <th>Title</th>
              <th>Primary Keyword</th>
              <th>Page Type</th>
              <th>Intent</th>
              <th>Words</th>
            </tr>
          </thead>
          <tbody>
            <?php
            // Pre-selected from URL param
            $preSelected = !empty($_GET['topic_ids']) ? explode(',', $_GET['topic_ids']) : [];
            foreach ($topics as $t):
              $checked = in_array((string)$t['id'], $preSelected) ? 'checked' : '';
            ?>
            <tr class="topic-row" data-id="<?= $t['id'] ?>">
              <td>
                <input type="checkbox" name="topic_ids[]" value="<?= $t['id'] ?>" class="form-check-input topic-check" <?= $checked ?>>
              </td>
              <td>
                <div class="fw-medium"><?= htmlspecialchars(mb_strimwidth($t['title'], 0, 65, '…')) ?></div>
              </td>
              <td><span class="text-muted small"><?= htmlspecialchars($t['primary_keyword']) ?></span></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 small"><?= htmlspecialchars($t['search_intent']) ?></span></td>
              <td><?= number_format($t['target_word_count']) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <div class="card-footer bg-white py-3 d-flex align-items-center justify-content-between">
      <div class="text-muted small">
        <i class="bi bi-info-circle me-1"></i>
        Content will be generated sequentially. Large batches may take several minutes.
      </div>
      <button type="submit" class="btn btn-success btn-lg px-5" id="generate-btn" disabled>
        <i class="bi bi-lightning-fill me-2"></i>Generate <span id="btn-count"></span>
      </button>
    </div>
  </form>
</div>

<?php elseif (!$selProject): ?>
<div class="text-center text-muted py-5">
  <i class="bi bi-arrow-up-circle fs-1 d-block mb-3"></i>
  <p>Select a project above to see pending topics.</p>
</div>
<?php endif; ?>

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

function update() {
  const n = [...checks].filter(c => c.checked).length;
  if (badge) badge.textContent = n + ' selected';
  if (genBtn) genBtn.disabled = n === 0;
  if (btnCount) btnCount.textContent = n > 0 ? '(' + n + ' topics)' : '';
}

if (selectAll) {
  selectAll.addEventListener('change', () => {
    checks.forEach(c => c.checked = selectAll.checked);
    update();
  });
}
checks.forEach(c => c.addEventListener('change', update));
update(); // init for pre-selected

// Show loading on generate
const form = document.getElementById('generate-form');
if (form) {
  form.addEventListener('submit', () => {
    if (genBtn) {
      genBtn.disabled = true;
      genBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Generating…';
    }
  });
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
