<?php

declare(strict_types=1);

use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Fact;
use Fisharebest\Webtrees\Family;
use Fisharebest\Webtrees\GedcomRecord;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Services\GedcomEditService;
use Illuminate\Support\Collection;

/**
 * @var GedcomRecord $record
 */

?>

<?php
$add_facts = (new GedcomEditService())->factsToAdd($record, false);

// Add from pick list
switch ($record->tag()) {
    case Individual::RECORD_TYPE:
        $quick_facts  = array_filter(explode(',', $record->tree()->getPreference('INDI_FACTS_QUICK')));
        $quick_facts = Fact::sortFactTags(Collection::make($quick_facts))->all();
        $unique_facts = [
            'ADOP',
            'AFN',
            'BAPL',
            'BAPM',
            'BARM',
            'BASM',
            'BIRT',
            'BURI',
            'CAST',
            'CHAN',
            'CHR',
            'CHRA',
            'CONF',
            'CONL',
            'CREM',
            'DEAT',
            'ENDL',
            'FCOM',
            'GRAD',
            'NCHI',
            'NMR',
            'ORDN',
            'PROB',
            'REFN',
            'RELI',
            'RESN',
            'RETI',
            'RFN',
            'RIN',
            'SEX',
            'SLGC',
            'SSN',
            'WILL',
        ];
        break;

    case Family::RECORD_TYPE:
        $quick_facts  = array_filter(explode(',', $record->tree()->getPreference('FAM_FACTS_QUICK')));
        $quick_facts = Fact::sortFactTags(Collection::make($quick_facts))->all();
        $unique_facts = [
            'DIV',
            'DIVF',
            'ENGA',
            'MARR',
        ];
        break;

    default:
        $quick_facts  = [];
        $unique_facts = [];
        break;
}

// Filter existing tags
$filter_fn = static fn (string $tag): bool => !in_array($tag, $unique_facts, true) || $record->facts([$tag])->isEmpty();

$quick_facts = array_filter($quick_facts, $filter_fn);


// Create a label for a subtag
$label_fn = static fn (string $subtag): string => Registry::elementFactory()->make($record->tag() . ':' . $subtag)->label();

$quick_facts = array_combine($quick_facts, array_map($label_fn, $quick_facts));
$add_facts   = array_combine($add_facts, array_map($label_fn, $add_facts));

uasort($add_facts, I18N::comparator());

if (!Auth::canUploadMedia($record->tree(), Auth::user())) {
    unset($add_facts['OBJE'], $quick_facts['OBJE']);
}

echo view('edit/add-fact-row', [
    'add_facts'   => $add_facts,
    'quick_facts' => $quick_facts,
    'record'      => $record,
]);