<?php use Fisharebest\Webtrees\I18N; ?>
<?php use Illuminate\Database\Query\JoinClause; ?>
<?php use Illuminate\Database\Capsule\Manager as DB; ?>

<?php
// Count the number of linked records. These numbers include private records.
// It is not good to bypass privacy, but many servers do not have the resources
// to process privacy for every record in the tree
$count_sources = DB::table('sources')
    ->join('link', function (JoinClause $join): void {
        $join->on('l_from', '=', 's_id');
        $join->on('l_file', '=', 's_file');
    })
    ->where('l_type', '=', 'REPO')
    ->where('l_file', '=', $tree->id())
    ->groupBy('l_to')
    ->select(['l_to', DB::raw('COUNT(*) AS total')])
    ->pluck('total', 'l_to')
    ->all();
?>

<table
    class="table table-bordered table-sm wt-table-repository datatables d-none"
    <?= view('lists/datatables-attributes') ?>
    data-columns="<?= e(json_encode([
        null,
        ['visible' => array_sum($count_sources) > 0],
        ['visible' => (bool) $tree->getPreference('SHOW_LAST_CHANGE'), 'searchable' => false],
    ])) ?>"
>
    <caption class="sr-only">
        <?= $caption ?? I18N::translate('Repositories') ?>
    </caption>

    <thead>
        <tr>
            <th><?= I18N::translate('Repository name') ?></th>
            <th><?= I18N::translate('Sources') ?></th>
            <th><?= I18N::translate('Last change') ?></th>
        </tr>
    </thead>

    <tbody>
        <?php foreach ($repositories as $repository) : ?>
            <tr class="<?= $repository->isPendingDeletion() ? 'old' : ($repository->isPendingAddition() ? 'new' : '') ?>">
                <!-- Repository name -->
                <td data-sort="<?= e($repository->getSortName()) ?>">
                    <a href="<?= e($repository->url()) ?>">
                        <?= $repository->getFullName() ?>
                    </a>
                </td>

                <!-- Count of linked sources -->
                <td class="center" data-sort="<?= $count_sources[$repository->xref()] ?? 0 ?>">
                    <?= I18N::number($count_sources[$repository->xref()] ?? 0) ?>
                </td>

                <!-- Last change -->
                <td data-sort="<?= $repository->lastChangeTimestamp(true) ?>">
                    <?= $repository->lastChangeTimestamp() ?>
                </td>
            </tr>
        <?php endforeach ?>
    </tbody>
</table>
