<?php
/**
 * language-search-fragment.php
 *
 * Shared HTMX fragment: returns matching language suggestions for the
 * "Autre(s) langue(s)" interactive search input.
 */
require_once __DIR__ . '/../../src/Database.php';

$query = trim(preg_replace('/\s+/', ' ', strtolower($_POST['language_search_q'] ?? '')));

$currentLanguages = isset($_POST['language_autre']) && is_array($_POST['language_autre'])
    ? array_map(function($l) { return trim(preg_replace('/\s+/', ' ', strtolower($l))); }, $_POST['language_autre'])
    : [];

error_log("[lang-search] q=" . var_export($query, true) . " cur=" . json_encode($currentLanguages));

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

error_log("[lang-search] raw results count=" . count($results) . " rows=" . json_encode(array_slice($results, 0, 5)));

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

// Exclude the main languages (handled by the checkbox list above)
$excludedLanguages = ['français', 'anglais', 'néerlandais'];

// Filter out already-selected and excluded main languages
$results = array_values(array_filter($results, function($lang) use ($currentLanguages, $excludedLanguages) {
    $lower = strtolower($lang['name']);
    return !in_array($lower, $currentLanguages, true)
        && !in_array($lower, $excludedLanguages, true);
}));

// Exact match check
$exactExists = false;
foreach ($results as $lang) {
    if (strcasecmp($lang['name'], $query) === 0) {
        $exactExists = true;
        break;
    }
}

$inCurrent = in_array($query, $currentLanguages, true);
$isExcluded = in_array($query, $excludedLanguages, true);
$canCreate = ($query !== '' && !$exactExists && !$inCurrent && !$isExcluded);

error_log("[lang-search] exactExists=" . var_export($exactExists, true) . " inCurrent=" . var_export($inCurrent, true) . " canCreate=" . var_export($canCreate, true));
?>
<?php if (empty($results) && !$canCreate): ?>
<div class="tag-search-empty">Aucune langue trouvée.</div>
<?php endif; ?>

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