<?php
/**
 * Partial: répertoire index columns.
 * Rendered both on full page load and as HTMX partial swap.
 *
 * Expected variables:
 *   $repData       array  output of Database::getRepertoireFilterData()
 *   $activeFilters array{years:int[], ap:string[], or:string[], fi:string[], kw:string[]}
 */

$activeSets = [
    'years' => array_map('strval', $activeFilters['years'] ?? []),
    'ap'    => $activeFilters['ap'] ?? [],
    'or'    => $activeFilters['or'] ?? [],
    'fi'    => $activeFilters['fi'] ?? [],
    'kw'    => $activeFilters['kw'] ?? [],
];

// Build the student map from matched students only
$studentMap = []; // name => id
foreach ($repData['students'] as $s) {
    if (empty($s['authors'])) continue;
    foreach (explode(',', $s['authors']) as $name) {
        $name = trim($name);
        if ($name !== '' && !isset($studentMap[$name])) {
            $studentMap[$name] = (int)$s['id'];
        }
    }
}
ksort($studentMap);

/**
 * Build the toggle URL for a filter button.
 * Toggles $value in $dim; keeps all other active filters intact.
 */
function repToggleUrl(array $sets, string $dim, string $value): string {
    if (in_array($value, $sets[$dim], true)) {
        $sets[$dim] = array_values(array_filter($sets[$dim], fn($v) => $v !== $value));
    } else {
        $sets[$dim][] = $value;
    }
    $params = [];
    foreach ($sets['years'] as $v) $params[] = 'fy[]=' . urlencode((string)$v);
    foreach ($sets['ap']    as $v) $params[] = 'ap[]=' . urlencode($v);
    foreach ($sets['or']    as $v) $params[] = 'or[]=' . urlencode($v);
    foreach ($sets['fi']    as $v) $params[] = 'fi[]=' . urlencode($v);
    foreach ($sets['kw']    as $v) $params[] = 'kw[]=' . urlencode($v);
    $qs = implode('&', $params);
    return '/repertoire' . ($qs ? '?' . $qs : '');
}

$anyActive = !empty($activeSets['years']) || !empty($activeSets['ap'])
          || !empty($activeSets['or'])    || !empty($activeSets['fi'])
          || !empty($activeSets['kw']);

// Per-column: does this dimension have ANY matched entry in the current result set?
// When a column has zero matched entries despite other filters being active, it means
// no thesis in the matched set carries that FK — the column has no useful cross-filter
// signal and its entries must NOT be faded (the user may still want to select them).
$colHasMatches = [
    'years' => !empty(array_filter($repData['years'],        fn($i) => $i['matched'])),
    'ap'    => !empty(array_filter($repData['ap_programs'],  fn($i) => $i['matched'])),
    'or'    => !empty(array_filter($repData['orientations'], fn($i) => $i['matched'])),
    'fi'    => !empty(array_filter($repData['finality_types'], fn($i) => $i['matched'])),
    'kw'    => !empty(array_filter($repData['keywords'],     fn($i) => $i['matched'])),
];

// Common HTMX attributes for all active filter buttons
$hx = 'hx-target="#repertoire-index" hx-swap="outerHTML" hx-push-url="true" hx-indicator="#rep-indicator"';
?>
<div id="repertoire-index" class="repertoire-index">

    <!-- ANNÉES -->
    <section class="repertoire-col" data-col="years">
        <h2>Années</h2>
        <ul>
        <?php foreach ($repData['years'] as $item):
            $val      = (string)$item['value'];
            $isActive = in_array($val, $activeSets['years'], true);
            $isFaded  = $anyActive && $colHasMatches['years'] && !$item['matched'] && !$isActive;
            $cls      = 'rep-entry'
                      . ($isActive ? ' rep-entry--selected' : '')
                      . ($isFaded  ? ' rep-entry--faded'    : '');
            $url      = repToggleUrl($activeSets, 'years', $val);
        ?>
            <li>
                <button type="button" class="<?= $cls ?>"
                        aria-pressed="<?= $isActive ? 'true' : 'false' ?>"
                        <?= $isFaded ? 'disabled' : "hx-get=\"" . htmlspecialchars($url) . "\" $hx" ?>>
                    <?= htmlspecialchars($val) ?>
                </button>
            </li>
        <?php endforeach; ?>
        </ul>
    </section>

    <!-- ATELIERS PLURIDISCIPLINAIRES -->
    <section class="repertoire-col" data-col="ap">
        <h2>Ateliers Pluridisciplinaires</h2>
        <ul>
        <?php foreach ($repData['ap_programs'] as $item):
            $val      = $item['value'];
            $isActive = in_array($val, $activeSets['ap'], true);
            $isFaded  = $anyActive && $colHasMatches['ap'] && !$item['matched'] && !$isActive;
            $cls      = 'rep-entry'
                      . ($isActive ? ' rep-entry--selected' : '')
                      . ($isFaded  ? ' rep-entry--faded'    : '');
            $url      = repToggleUrl($activeSets, 'ap', $val);
        ?>
            <li>
                <button type="button" class="<?= $cls ?>"
                        aria-pressed="<?= $isActive ? 'true' : 'false' ?>"
                        <?= $isFaded ? 'disabled' : "hx-get=\"" . htmlspecialchars($url) . "\" $hx" ?>>
                    <?= htmlspecialchars($val) ?>
                </button>
            </li>
        <?php endforeach; ?>
        </ul>
    </section>

    <!-- ORIENTATIONS -->
    <section class="repertoire-col" data-col="or">
        <h2>Orientations</h2>
        <ul>
        <?php foreach ($repData['orientations'] as $item):
            $val      = $item['value'];
            $isActive = in_array($val, $activeSets['or'], true);
            $isFaded  = $anyActive && $colHasMatches['or'] && !$item['matched'] && !$isActive;
            $cls      = 'rep-entry'
                      . ($isActive ? ' rep-entry--selected' : '')
                      . ($isFaded  ? ' rep-entry--faded'    : '');
            $url      = repToggleUrl($activeSets, 'or', $val);
        ?>
            <li>
                <button type="button" class="<?= $cls ?>"
                        aria-pressed="<?= $isActive ? 'true' : 'false' ?>"
                        <?= $isFaded ? 'disabled' : "hx-get=\"" . htmlspecialchars($url) . "\" $hx" ?>>
                    <?= htmlspecialchars($val) ?>
                </button>
            </li>
        <?php endforeach; ?>
        </ul>
    </section>

    <!-- FINALITÉ DU MASTER -->
    <section class="repertoire-col" data-col="fi">
        <h2>Finalité du Master</h2>
        <ul>
        <?php foreach ($repData['finality_types'] as $item):
            $val      = $item['value'];
            $isActive = in_array($val, $activeSets['fi'], true);
            $isFaded  = $anyActive && $colHasMatches['fi'] && !$item['matched'] && !$isActive;
            $cls      = 'rep-entry'
                      . ($isActive ? ' rep-entry--selected' : '')
                      . ($isFaded  ? ' rep-entry--faded'    : '');
            $url      = repToggleUrl($activeSets, 'fi', $val);
        ?>
            <li>
                <button type="button" class="<?= $cls ?>"
                        aria-pressed="<?= $isActive ? 'true' : 'false' ?>"
                        <?= $isFaded ? 'disabled' : "hx-get=\"" . htmlspecialchars($url) . "\" $hx" ?>>
                    <?= htmlspecialchars($val) ?>
                </button>
            </li>
        <?php endforeach; ?>
        </ul>
    </section>

    <!-- ÉTUDIANTES -->
    <section class="repertoire-col" data-col="students">
        <h2>Étudiantes</h2>
        <ul>
        <?php if (empty($studentMap)): ?>
            <li class="rep-empty">—</li>
        <?php else: ?>
            <?php foreach ($studentMap as $name => $id): ?>
            <li>
                <a href="/tfe?id=<?= (int)$id ?>" class="rep-entry rep-entry--link">
                    <?= htmlspecialchars($name) ?>
                </a>
            </li>
            <?php endforeach; ?>
        <?php endif; ?>
        </ul>
    </section>

    <!-- MOTS-CLÉS -->
    <section class="repertoire-col" data-col="kw">
        <h2>Mots-clés</h2>
        <ul>
        <?php foreach ($repData['keywords'] as $item):
            $val      = $item['value'];
            $isActive = in_array($val, $activeSets['kw'], true);
            $isFaded  = $anyActive && $colHasMatches['kw'] && !$item['matched'] && !$isActive;
            $cls      = 'rep-entry'
                      . ($isActive ? ' rep-entry--selected' : '')
                      . ($isFaded  ? ' rep-entry--faded'    : '');
            $url      = repToggleUrl($activeSets, 'kw', $val);
        ?>
            <li>
                <button type="button" class="<?= $cls ?>"
                        aria-pressed="<?= $isActive ? 'true' : 'false' ?>"
                        <?= $isFaded ? 'disabled' : "hx-get=\"" . htmlspecialchars($url) . "\" $hx" ?>>
                    <?= htmlspecialchars($val) ?>
                </button>
            </li>
        <?php endforeach; ?>
        </ul>
    </section>

</div>
