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

<div class="d-flex align-items-center justify-content-between mb-4">
  <div>
    <h4 class="fw-bold mb-1">Content Library</h4>
    <p class="text-muted mb-0">Browse, review, approve, and export all generated content.</p>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= BASE_URL ?>/content/generate" class="btn btn-success btn-sm">
      <i class="bi bi-lightning me-1"></i>Generate More
    </a>
  </div>
</div>

<!-- Filters + bulk actions bar -->
<div class="card border-0 shadow-sm mb-4">
  <div class="card-body py-3">
    <div class="d-flex align-items-center gap-3 flex-wrap">
      <form method="GET" action="<?= BASE_URL ?>/content" class="d-flex align-items-center gap-3 flex-wrap flex-grow-1">
        <select name="project_id" class="form-select" style="max-width:220px;" onchange="this.form.submit()">
          <option value="">All Projects</option>
          <?php foreach ($projects as $p): ?>
          <option value="<?= $p['id'] ?>" <?= $selProject == $p['id'] ? 'selected' : '' ?>><?= htmlspecialchars($p['business_name']) ?></option>
          <?php endforeach; ?>
        </select>
        <select name="status" class="form-select" style="max-width:160px;" onchange="this.form.submit()">
          <option value="">All Statuses</option>
          <?php foreach (['draft', 'approved', 'qa_failed', 'published'] as $s): ?>
          <option value="<?= $s ?>" <?= $statusFilter === $s ? 'selected' : '' ?>><?= ucfirst(str_replace('_', ' ', $s)) ?></option>
          <?php endforeach; ?>
        </select>
        <?php if ($selProject || $statusFilter): ?>
        <a href="<?= BASE_URL ?>/content" class="btn btn-sm btn-light"><i class="bi bi-x me-1"></i>Clear</a>
        <?php endif; ?>
      </form>

      <div class="ms-auto d-flex align-items-center gap-2 flex-shrink-0">
        <span class="text-muted small"><?= count($content) ?> result(s)</span>
        <!-- Delete Selected (shown when checkboxes are ticked) -->
        <button id="delete-selected-btn" class="btn btn-sm btn-danger d-none" type="button" onclick="submitBulk(false)">
          <i class="bi bi-trash me-1"></i>Delete Selected (<span id="sel-count">0</span>)
        </button>
        <!-- Delete All -->
        <?php if (!empty($content)): ?>
        <button class="btn btn-sm btn-outline-danger" type="button" onclick="submitBulk(true)">
          <i class="bi bi-trash3 me-1"></i>Delete All
        </button>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- Hidden bulk-delete form (populated by JS) -->
<form id="bulk-form" method="POST" action="<?= BASE_URL ?>/content/bulk-delete">
  <div id="bulk-ids"></div>
</form>

<?php if (empty($content)): ?>
<div class="card border-0 shadow-sm text-center py-5">
  <div class="card-body">
    <i class="bi bi-inbox fs-1 text-muted mb-3 d-block"></i>
    <h5>No content found</h5>
    <p class="text-muted">Generate content from your topics to see it here.</p>
    <a href="<?= BASE_URL ?>/content/generate" class="btn btn-primary">
      <i class="bi bi-lightning me-1"></i>Generate Content
    </a>
  </div>
</div>
<?php else: ?>
<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="content-table">
        <thead class="table-light">
          <tr>
            <th style="width:36px;">
              <input type="checkbox" id="select-all" title="Select all" style="cursor:pointer;">
            </th>
            <th>Code</th>
            <th>Title</th>
            <th>Business</th>
            <th>Page Type</th>
            <th>Keyword</th>
            <th>Words</th>
            <th>KD%</th>
            <th>QA</th>
            <th>Status</th>
            <th>Tokens</th>
            <th>Date</th>
            <th class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($content as $row): ?>
          <tr>
            <td>
              <input type="checkbox" class="row-check" data-id="<?= $row['id'] ?>" style="cursor:pointer;">
            </td>
            <td>
              <?php if (!empty($row['content_code'])): ?>
              <span class="badge bg-dark text-white font-monospace" style="font-size:10px;letter-spacing:.03em;"><?= htmlspecialchars($row['content_code']) ?></span>
              <?php else: ?>
              <span class="text-muted small">—</span>
              <?php endif; ?>
            </td>
            <td class="fw-medium" style="max-width:300px;">
              <a href="<?= BASE_URL ?>/content/<?= $row['id'] ?>" class="text-dark text-decoration-none hover-primary">
                <?= htmlspecialchars(mb_strimwidth($row['title'], 0, 55, '…')) ?>
              </a>
            </td>
            <td class="small text-muted"><?= htmlspecialchars($row['business_name']) ?></td>
            <td><span class="badge bg-secondary-subtle text-secondary small"><?= htmlspecialchars($row['page_type_name']) ?></span></td>
            <td class="small text-muted"><?= htmlspecialchars(mb_strimwidth($row['primary_keyword'], 0, 28, '…')) ?></td>
            <td><?= number_format($row['word_count'] ?? 0) ?></td>
            <td><?= $row['keyword_density'] ?? '—' ?><?= $row['keyword_density'] ? '%' : '' ?></td>
            <td>
              <?php if ($row['qa_passed'] !== null): ?>
              <span class="badge <?= $row['qa_passed'] ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?>">
                <i class="bi bi-<?= $row['qa_passed'] ? 'check' : 'x' ?>"></i>
                <?= $row['qa_passed'] ? 'Pass' : 'Fail' ?>
              </span>
              <?php else: ?>—<?php endif; ?>
            </td>
            <td>
              <?php
              $statusColors = ['draft' => 'warning', 'approved' => 'success', 'qa_failed' => 'danger', 'published' => 'primary'];
              $sc = $statusColors[$row['status']] ?? 'secondary';
              ?>
              <span class="badge bg-<?= $sc ?>-subtle text-<?= $sc ?>">
                <?= htmlspecialchars(str_replace('_', ' ', ucfirst($row['status']))) ?>
              </span>
            </td>
            <td class="small text-muted"><?= number_format(($row['input_tokens'] ?? 0) + ($row['output_tokens'] ?? 0)) ?></td>
            <td class="small text-muted"><?= date('M j', strtotime($row['created_at'])) ?></td>
            <td class="text-end">
              <div class="d-flex gap-1 justify-content-end">
                <a href="<?= BASE_URL ?>/content/<?= $row['id'] ?>" class="btn btn-sm btn-outline-primary" title="View">
                  <i class="bi bi-eye"></i>
                </a>
                <div class="dropdown">
                  <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-download"></i>
                  </button>
                  <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="<?= BASE_URL ?>/content/<?= $row['id'] ?>/export/html"><i class="bi bi-file-code me-2"></i>Export HTML</a></li>
                    <li><a class="dropdown-item" href="<?= BASE_URL ?>/content/<?= $row['id'] ?>/export/word"><i class="bi bi-file-word me-2"></i>Export Word</a></li>
                    <li><a class="dropdown-item" href="<?= BASE_URL ?>/content/<?= $row['id'] ?>/export/json"><i class="bi bi-filetype-json me-2"></i>Export JSON</a></li>
                  </ul>
                </div>
                <?php if ($row['status'] !== 'approved'): ?>
                <form method="POST" action="<?= BASE_URL ?>/content/<?= $row['id'] ?>/approve" class="d-inline">
                  <button class="btn btn-sm btn-success" title="Approve"><i class="bi bi-check2"></i></button>
                </form>
                <?php endif; ?>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php endif; ?>

<?php
$extraJs = <<<JS
<script>
if (document.getElementById('content-table')) {
  $('#content-table').DataTable({ pageLength: 25, order: [[10, 'desc']], columnDefs: [{ orderable: false, targets: [0, 12] }] });
}

// Track selected IDs across DataTable pages
const selected = new Set();

document.addEventListener('change', function(e) {
  if (e.target.id === 'select-all') {
    const checked = e.target.checked;
    document.querySelectorAll('.row-check').forEach(cb => {
      cb.checked = checked;
      checked ? selected.add(cb.dataset.id) : selected.delete(cb.dataset.id);
    });
  } else if (e.target.classList.contains('row-check')) {
    e.target.checked ? selected.add(e.target.dataset.id) : selected.delete(e.target.dataset.id);
  }
  updateBulkBar();
});

function updateBulkBar() {
  const btn  = document.getElementById('delete-selected-btn');
  const cnt  = document.getElementById('sel-count');
  if (!btn) return;
  if (selected.size > 0) {
    btn.classList.remove('d-none');
    cnt.textContent = selected.size;
  } else {
    btn.classList.add('d-none');
  }
}

function submitBulk(deleteAll) {
  const label = deleteAll
    ? 'Delete ALL content? This cannot be undone.'
    : 'Delete ' + selected.size + ' selected item(s)?';
  if (!confirm(label)) return;

  const form = document.getElementById('bulk-form');
  const container = document.getElementById('bulk-ids');
  container.innerHTML = '';

  if (deleteAll) {
    container.innerHTML = '<input type="hidden" name="delete_all" value="1">';
  } else {
    selected.forEach(id => {
      const inp = document.createElement('input');
      inp.type  = 'hidden';
      inp.name  = 'ids[]';
      inp.value = id;
      container.appendChild(inp);
    });
  }
  form.submit();
}
</script>
JS;
require __DIR__ . '/../layout/footer.php';
?>
