<?php

declare(strict_types=1);

use Fisharebest\Webtrees\DB;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Media;
use Fisharebest\Webtrees\Tree;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;

/**
 * @var string|null           $caption
 * @var Collection<int,Media> $media_objects
 * @var Tree                  $tree
 */

?>

<?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_individuals = DB::table('individuals')
    ->join('link', static function (JoinClause $join): void {
        $join->on('l_from', '=', 'i_id');
        $join->on('l_file', '=', 'i_file');
    })
    ->where('l_type', '=', 'OBJE')
    ->where('l_file', '=', $tree->id())
    ->groupBy(['l_to'])
    ->pluck(new Expression('COUNT(*) AS total'), 'l_to')
    ->map(static fn (string $n): int => (int) $n)
    ->all();

$count_families = DB::table('families')
    ->join('link', static function (JoinClause $join): void {
        $join->on('l_from', '=', 'f_id');
        $join->on('l_file', '=', 'f_file');
    })
    ->where('l_type', '=', 'OBJE')
    ->where('l_file', '=', $tree->id())
    ->groupBy(['l_to'])
    ->pluck(new Expression('COUNT(*) AS total'), 'l_to')
    ->map(static fn (string $n): int => (int) $n)
    ->all();

$count_sources = DB::table('sources')
    ->join('link', static function (JoinClause $join): void {
        $join->on('l_from', '=', 's_id');
        $join->on('l_file', '=', 's_file');
    })
    ->where('l_type', '=', 'OBJE')
    ->where('l_file', '=', $tree->id())
    ->groupBy(['l_to'])
    ->pluck(new Expression('COUNT(*) AS total'), 'l_to')
    ->map(static fn (string $n): int => (int) $n)
    ->all();
?>

<table
    id="wt-datatables-media"
    class="table table-bordered table-sm wt-table-media datatables d-none"
    <?= view('lists/datatables-attributes') ?>
    data-columns="<?= e(json_encode([
        null,
        ['type' => 'html'],
        ['visible' => array_sum($count_individuals) > 0],
        ['visible' => array_sum($count_families) > 0],
        ['visible' => array_sum($count_sources) > 0],
        ['visible' => (bool) $tree->getPreference('SHOW_LAST_CHANGE'), 'searchable' => false],
    ], JSON_THROW_ON_ERROR)) ?>"
>
    <caption class="visually-hidden">
        <?= $caption ?? I18N::translate('Media objects') ?>
    </caption>

    <thead>
        <tr>
            <th><?= I18N::translate('Media') ?></th>
            <th><?= I18N::translate('Title') ?></th>
            <th><?= I18N::translate('Individuals') ?></th>
            <th><?= I18N::translate('Families') ?></th>
            <th><?= I18N::translate('Sources') ?></th>
            <th><?= I18N::translate('Last change') ?></th>
        </tr>
    </thead>

    <tbody>
        <?php foreach ($media_objects as $media_object) : ?>
            <tr class="<?= $media_object->isPendingAddition() ? 'wt-new' : '' ?> <?= $media_object->isPendingDeletion() ? 'wt-old' : '' ?>">
                <!-- Thumbnails-->
                <td data-sort="<?= e($media_object->sortName()) ?>">
                    <?php foreach ($media_object->mediaFiles() as $media_file) : ?>
                        <?= $media_file->displayImage(100, 100, 'contain', []) ?>
                    <?php endforeach ?>
                </td>

                <!-- Title -->
                <td data-sort="<?= e($media_object->sortName()) ?>">
                    <a href="<?= e($media_object->url()) ?>">
                        <?= $media_object->fullName() ?>
                    </a>
                </td>

                <!-- Count of linked individuals -->
                <td class="text-center" data-sort="<?= $count_individuals[$media_object->xref()] ?? 0 ?>">
                    <?= I18N::number($count_individuals[$media_object->xref()] ?? 0) ?>
                </td>

                <!-- Count of linked families -->
                <td class="text-center" data-sort="<?= $count_families[$media_object->xref()] ?? 0 ?>">
                    <?= I18N::number($count_families[$media_object->xref()] ?? 0) ?>
                </td>

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

                <!-- Last change -->
                <td data-sort="<?= sprintf('x%07d', $media_object->lastChangeTimestamp()->timestamp()) ?>">
                    <?= view('components/datetime', ['timestamp' => $media_object->lastChangeTimestamp()]) ?>
                </td>
            </tr>
        <?php endforeach ?>
    </tbody>
</table>
