<?php
/**
 * tag-search-fragment.php
 *
 * Shared HTMX fragment: returns matching tag suggestions for the mot-clé
 * interactive search input.
 *
 * Included by:
 *   - /admin/tag-search-fragment.php  (AdminAuth gated)
 *   - partage/index.php special route (public, session already booted)
 *
 * Expected POST:
 *   q      — search query string (partial tag name)
 *   tag[]  — already selected tag names (sent via hx-include, to exclude from suggestions)
 */
require_once __DIR__ . '/../../src/Database.php';

$query = trim(preg_replace('/\s+/', ' ', strtolower($_POST['tag_search_q'] ?? '')));
$currentTags = isset($_POST['tag']) && is_array($_POST['tag'])
    ? array_map(function($t) { return trim(preg_replace('/\s+/', ' ', strtolower($t))); }, $_POST['tag'])
    : [];

$db      = Database::getInstance();
$results = $db->searchTags($query);

// Deduplicate results by lowercase name
$seen = [];
$results = array_values(array_filter($results, function($tag) use (&$seen) {
    $key = strtolower($tag['name']);
    if (isset($seen[$key])) return false;
    $seen[$key] = true;
    return true;
}));

// Filter out already-selected tags (case-insensitive)
$results = array_values(array_filter($results, function($tag) use ($currentTags) {
    return !in_array(strtolower($tag['name']), $currentTags, true);
}));

// Check if query exactly matches an existing tag (case-insensitive)
$exactExists = false;
foreach ($results as $tag) {
    if (strcasecmp($tag['name'], $query) === 0) {
        $exactExists = true;
        break;
    }
}

// If no exact match and query non-empty, suggest creation
$canCreate = ($query !== '' && !$exactExists && !in_array($query, $currentTags, true));
?>
<?php if (empty($results) && !$canCreate): ?>
<div class="tag-search-empty">Aucun mot-clé trouvé.</div>
<?php endif; ?>

<?php foreach ($results as $tag): ?>
<button type="button" class="tag-search-item" data-tag-id="<?= (int)$tag['id'] ?>" data-tag-name="<?= htmlspecialchars($tag['name']) ?>">
    <span class="tag-search-item-name"><?= htmlspecialchars($tag['name']) ?></span>
    <span class="tag-search-item-count">(<?= (int)$tag['thesis_count'] ?>)</span>
</button>
<?php endforeach; ?>

<?php if ($canCreate): ?>
<button type="button" class="tag-search-item tag-search-item--create" data-tag-name="<?= htmlspecialchars($query) ?>">
    <span class="tag-search-item-name">Créer «&nbsp;<?= htmlspecialchars($query) ?>&nbsp;»</span>
</button>
<?php endif; ?>
