<?php
/**
 * include/journal_selector.php
 * Drop-in partial for journal selection in pages_create.php and pages_edit.php
 *
 * Expects:
 *   $pdo          — PDO connection
 *   $input        — current field values array (uses $input['journal_id'])
 */

// Fetch all active journals grouped by category
$_jSelector = [];
try {
    $_jSelector = $pdo->query("
        SELECT j.journal_id, j.name, j.slug,
               c.name AS category_name, c.display_order
        FROM journals j
        LEFT JOIN journal_categories c ON c.category_id = j.category_id
        WHERE j.is_active = 1
        ORDER BY c.display_order ASC, c.name ASC, j.name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    // journals table may not exist — fail silently
}

// Group by category
$_byCategory = ['(No Category)' => []];
foreach ($_jSelector as $j) {
    $cat = $j['category_name'] ?: '(No Category)';
    $_byCategory[$cat][] = $j;
}
if (empty($_byCategory['(No Category)'])) unset($_byCategory['(No Category)']);

$_selectedJid = (int)($input['journal_id'] ?? 0);
?>

<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
    <i class="fas fa-book text-blue-600"></i>
    <h2 class="font-semibold text-gray-700">Journal</h2>
    <span class="ml-auto text-xs text-gray-400">Optional — link this page to a journal</span>
  </div>
  <div class="p-5">
    <?php if(empty($_jSelector)): ?>
    <p class="text-sm text-gray-400 italic">
      No journals found.
      <a href="journals.php" class="text-blue-600 hover:underline">Add journals first →</a>
    </p>
    <?php else: ?>

    <!-- Search + Select -->
    <div class="space-y-3">
      <!-- Quick search -->
      <div class="relative">
        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-300 text-xs"></i>
        <input type="text" id="journalSearchInput"
               placeholder="Type to filter journals..."
               class="w-full border border-gray-200 rounded-lg pl-8 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
               oninput="filterJournalSelect(this.value)">
      </div>

      <!-- Hidden input that actually gets submitted -->
      <input type="hidden" name="journal_id" id="journalIdHidden" value="<?= $_selectedJid ?: '' ?>">

      <!-- Visual card list -->
      <div id="journalCardList"
           class="max-h-56 overflow-y-auto border border-gray-200 rounded-xl divide-y divide-gray-50">

        <!-- None option -->
        <div class="journal-option flex items-center gap-3 px-4 py-2.5 cursor-pointer hover:bg-gray-50 transition <?= !$_selectedJid ? 'bg-blue-50' : '' ?>"
             data-id="0" data-name="none"
             onclick="selectJournal(0, 'No journal / Global page', this)">
          <div class="w-7 h-7 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
            <i class="fas fa-globe text-gray-400 text-xs"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-sm font-medium text-gray-500">No journal / Global page</div>
            <div class="text-xs text-gray-400">Page appears across all journals</div>
          </div>
          <i class="fas fa-check text-blue-600 text-xs <?= !$_selectedJid ? '' : 'hidden' ?>" id="check-0"></i>
        </div>

        <?php foreach($_byCategory as $catName => $catJournals): ?>
        <!-- Category header -->
        <div class="journal-cat-header px-4 py-1.5 bg-gray-50 text-xs font-semibold text-gray-400 uppercase tracking-wide sticky top-0">
          <?= htmlspecialchars($catName) ?>
        </div>
        <?php foreach($catJournals as $j):
              $isSelected = ($j['journal_id'] == $_selectedJid);
        ?>
        <div class="journal-option flex items-center gap-3 px-4 py-2.5 cursor-pointer hover:bg-gray-50 transition <?= $isSelected ? 'bg-blue-50' : '' ?>"
             data-id="<?= $j['journal_id'] ?>"
             data-name="<?= strtolower(htmlspecialchars($j['name'])) ?>"
             onclick="selectJournal(<?= $j['journal_id'] ?>, '<?= addslashes($j['name']) ?>', this)">
          <div class="w-7 h-7 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0">
            <i class="fas fa-book text-blue-400 text-xs"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-sm font-medium text-gray-800 truncate"><?= htmlspecialchars($j['name']) ?></div>
            <div class="text-xs text-gray-400 font-mono">/<?= htmlspecialchars($j['slug']) ?></div>
          </div>
          <i class="fas fa-check text-blue-600 text-xs <?= $isSelected ? '' : 'hidden' ?>"
             id="check-<?= $j['journal_id'] ?>"></i>
        </div>
        <?php endforeach; ?>
        <?php endforeach; ?>
      </div>

      <!-- Selected display -->
      <div id="journalSelectedDisplay"
           class="flex items-center gap-2 text-sm <?= $_selectedJid ? 'text-blue-700' : 'text-gray-400' ?>">
        <i class="fas <?= $_selectedJid ? 'fa-check-circle text-blue-600' : 'fa-info-circle' ?>"></i>
        <span id="journalSelectedLabel">
          <?php
          if ($_selectedJid) {
              $found = array_values(array_filter($_jSelector, fn($j) => $j['journal_id'] == $_selectedJid));
              echo $found ? htmlspecialchars($found[0]['name']) : 'Unknown journal';
          } else {
              echo 'No journal selected (global page)';
          }
          ?>
        </span>
      </div>
    </div>

    <?php endif; ?>
  </div>
</div>

<script>
function selectJournal(id, name, el) {
    // Update hidden input
    document.getElementById('journalIdHidden').value = id || '';

    // Clear all checks + bg
    document.querySelectorAll('.journal-option').forEach(opt => {
        opt.classList.remove('bg-blue-50');
        const chk = opt.querySelector('[id^="check-"]');
        if (chk) chk.classList.add('hidden');
    });

    // Mark selected
    el.classList.add('bg-blue-50');
    const thisChk = document.getElementById('check-' + id);
    if (thisChk) thisChk.classList.remove('hidden');

    // Update display
    const disp = document.getElementById('journalSelectedDisplay');
    const lbl  = document.getElementById('journalSelectedLabel');
    if (id) {
        disp.className = 'flex items-center gap-2 text-sm text-blue-700';
        disp.querySelector('i').className = 'fas fa-check-circle text-blue-600';
        lbl.textContent = name;
    } else {
        disp.className = 'flex items-center gap-2 text-sm text-gray-400';
        disp.querySelector('i').className = 'fas fa-info-circle';
        lbl.textContent = 'No journal selected (global page)';
    }
}

function filterJournalSelect(q) {
    const query = q.toLowerCase().trim();
    const opts  = document.querySelectorAll('.journal-option');
    const cats  = document.querySelectorAll('.journal-cat-header');

    opts.forEach(opt => {
        const name = opt.dataset.name || '';
        opt.style.display = (!query || name.includes(query)) ? '' : 'none';
    });

    // Hide category headers with no visible items
    cats.forEach(cat => {
        let next = cat.nextElementSibling;
        let hasVisible = false;
        while (next && !next.classList.contains('journal-cat-header')) {
            if (next.style.display !== 'none' && next.classList.contains('journal-option')) {
                hasVisible = true;
            }
            next = next.nextElementSibling;
        }
        cat.style.display = hasVisible ? '' : 'none';
    });
}
</script>