<?php

use Fisharebest\Webtrees\Gedcom;
use Fisharebest\Webtrees\Http\RequestHandlers\ReorderChildrenAction;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\View;

?>

<h2 class="wt-page-title"><?= $title ?></h2>

<form method="post" action="<?= e(route(ReorderChildrenAction::class, ['tree' => $tree->name(), 'xref' => $family->xref()])) ?>" class="wt-page-content">
    <?= csrf_field() ?>

    <div class="wt-sortable-list">
        <?php foreach ($family->facts(['CHIL']) as $fact) : ?>
            <div class="card my-2 wt-sortable-item" data-sortbydate="<?= $fact->target()->getBirthDate()->julianDay() ?>">
                <input type="hidden" name="order[]" value="<?= $fact->id() ?>">
                <div class="card-header">
                    <?= view('edit/reorder-card-header', ['title' => $fact->target()->fullName()]) ?>
                </div>

                <div class="card-body">
                    <?= $fact->target()->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 2) ?>
                    <?= $fact->target()->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 2) ?>
                </div>
            </div>
        <?php endforeach ?>
    </div>

    <p>
        <button class="btn btn-primary" type="submit">
            <?= view('icons/save') ?>
            <?= /* I18N: A button label. */ I18N::translate('save') ?>
        </button>

        <button class="btn btn-secondary" id="btn-default-order" type="button">
            <?= view('icons/sort') ?>
            <?= /* I18N: A button label. */ I18N::translate('sort by date of birth') ?>
        </button>

        <a class="btn btn-secondary" href="<?= e($family->url()) ?>">
            <?= view('icons/cancel') ?>
            <?= /* I18N: A button label. */ I18N::translate('cancel') ?>
        </a>
    </p>
</form>

<?php View::push('javascript') ?>
<script>
    new Sortable(document.querySelector(".wt-sortable-list"), {
        handle: ".card-header",
    });

    $("#btn-default-order").on("click", function () {
        $(".wt-sortable-list .wt-sortable-item").sort(function (x, y) {
            return Math.sign(x.dataset.sortbydate - y.dataset.sortbydate);
        }).appendTo(".wt-sortable-list");
    });
</script>
<?php View::endpush() ?>
