<?php
/**
 * language-search-fragment.php
 *
 * Shared HTMX fragment: returns matching language suggestions for the
 * "Autre(s) langue(s)" interactive search input.
 *
 * Included by:
 *   - /admin/language-search-fragment.php  (AdminAuth gated)
 *   - partage/index.php special route      (public, session already booted)
 *
 * Expected POST:
 *   q                  — search query string (partial language name)
 *   language_autre[]   — already selected language names (for exclusion)
 */
require_once __DIR__ . '/../../src/Database.php';

$query = trim(preg_replace('/\s+/', ' ', strtolower($_POST['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'])
    : [];

$db      = Database::getInstance();

// Search existing languages by name, excluding predefined ones (already shown as checkboxes)
$predefined = ["français", "anglais", "néerlandais", "francais", "neerlandais"];
if ($query !== '') {
    $placeholders = implode(',', array_fill(0, count($predefined), '?'));
    $stmt = $db->getConnection()->prepare(
        "SELECT l.id, UPPER(SUBSTR(l.name,1,1)) || SUBSTR(l.name,2) as name,
                COUNT(DISTINCT tl.thesis_id) as thesis_count
         FROM languages l
         LEFT JOIN thesis_languages tl ON l.id = tl.language_id
         WHERE LOWER(l.name) LIKE ?
           AND LOWER(l.name) NOT IN ($placeholders)
         GROUP BY l.id
         ORDER BY LOWER(l.name) = ? DESC, thesis_count DESC, LOWER(l.name)
         LIMIT 10"
    );
    $stmt->execute(array_merge([$query . '%'], $predefined, [$query]));
} else {
    $placeholders = implode(',', array_fill(0, count($predefined), '?'));
    $stmt = $db->getConnection()->prepare(
        "SELECT l.id, UPPER(SUBSTR(l.name,1,1)) || SUBSTR(l.name,2) as name,
                COUNT(DISTINCT tl.thesis_id) as thesis_count
         FROM languages l
         LEFT JOIN thesis_languages tl ON l.id = tl.language_id
         WHERE LOWER(l.name) NOT IN ($placeholders)
         GROUP BY l.id
         ORDER BY thesis_count DESC, LOWER(l.name)
         LIMIT 10"
    );
    $stmt->execute($predefined);
}

$results = $stmt->fetchAll();

// Deduplicate results by lowercase name
$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;
}));

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

// Check if query exactly matches an existing language (case-insensitive)
// Also check against predefined languages to avoid suggesting creation of a checkbox language
$exactExists = false;
foreach ($results as $lang) {
    if (strcasecmp($lang['name'], $query) === 0) {
        $exactExists = true;
        break;
    }
}
if (!$exactExists && $query !== '') {
    $normalisedQuery = strtolower($query);
    $normalisedPredefined = array_map('strtolower', $predefined);
    if (in_array($normalisedQuery, $normalisedPredefined, true)) {
        $exactExists = true;
    }
}

// If no exact match and query non-empty, suggest creation
$canCreate = ($query !== '' && !$exactExists && !in_array($query, $currentLanguages, 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; ?>
