<?php

declare(strict_types=1);

use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\GedcomRecord;
use Fisharebest\Webtrees\Http\RequestHandlers\ControlPanel;
use Fisharebest\Webtrees\Http\RequestHandlers\ManageTrees;
use Fisharebest\Webtrees\Http\RequestHandlers\TreePrivacyAction;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\View;

/**
 * @var array<string,string>                                                                            $all_tags
 * @var int                                                                                             $count_trees
 * @var array<string,string>                                                                            $privacy_constants
 * @var list<object{default_resn_id:int,resn:string,xref:string,record:GedcomRecord|null,label:string}> $privacy_restrictions
 * @var string                                                                                          $title
 * @var Tree                                                                                            $tree
 */

?>

<?= view('components/breadcrumbs', ['links' => [route(ControlPanel::class) => I18N::translate('Control panel'), route(ManageTrees::class, ['tree' => $tree->name()]) => I18N::translate('Manage family trees'), $title]]) ?>

<h1><?= $title ?></h1>

<form method="post" action="<?= e(route(TreePrivacyAction::class, ['tree' => $tree->name()])) ?>">
    <!-- REQUIRE_AUTHENTICATION -->
    <div class="row mb-3">
        <div class="col-form-label col-sm-4">
            <label>
                <?= /* I18N: A configuration setting */ I18N::translate('Show the family tree') ?>
            </label>
            <div class="hidden-xs">
                <span class="badge visitors"><?= I18N::translate('visitors') ?></span>
                <span class="badge members"><?= I18N::translate('members') ?></span>
            </div>
        </div>
        <div class="col-sm-8">
            <?= view('components/select', ['name' => 'REQUIRE_AUTHENTICATION', 'selected' => (int) $tree->private(), 'options' => [I18N::translate('Show to visitors'), I18N::translate('Show to members')]]) ?>
            <div class="form-text">
                <?= /* I18N: Help text for the “Family tree” configuration setting */ I18N::translate('Enabling this option will force all visitors to sign in before they can view any data on the website.') ?>
            </div>
        </div>
    </div>

    <!-- SHOW_DEAD_PEOPLE -->
    <div class="row mb-3">
        <div class="col-form-label col-sm-4">
            <label for="SHOW_DEAD_PEOPLE">
                <?= /* I18N: A configuration setting */ I18N::translate('Show dead individuals') ?>
            </label>
            <div class="hidden-xs">
                <span class="badge visitors"><?= I18N::translate('visitors') ?></span>
                <span class="badge members"><?= I18N::translate('members') ?></span>
            </div>
        </div>
        <div class="col-sm-8">
            <?= view('components/select', ['name' => 'SHOW_DEAD_PEOPLE', 'selected' => $tree->getPreference('SHOW_DEAD_PEOPLE'), 'options' => array_slice(Auth::accessLevelNames(), 0, 2, true)]) ?>
            <div class="form-text">
                <?= /* I18N: Help text for the “Show dead individuals” configuration setting */ I18N::translate('Set the privacy access level for all dead individuals.') ?>
            </div>
        </div>
    </div>


    <!-- MAX_ALIVE_AGE -->
    <div class="row mb-3">
        <label class="col-form-label col-sm-4" for="MAX_ALIVE_AGE">
            <?= I18N::translate('Age at which to assume an individual is dead') ?>
        </label>
        <div class="col-sm-8">
            <input class="form-control" id="MAX_ALIVE_AGE" min="1" max="9999" name="MAX_ALIVE_AGE" required type="number" value="<?= e($tree->getPreference('MAX_ALIVE_AGE')) ?>">
            <div class="form-text">
                <?= /* I18N: Help text for the “Age at which to assume an individual is dead” configuration setting */ I18N::translate('If this individual has any events other than death, burial, or cremation more recent than this number of years, they are considered to be “alive”. Children’s birth dates are considered to be such events for this purpose.') ?>
            </div>
        </div>
    </div>

    <!-- HIDE_LIVE_PEOPLE -->
    <fieldset class="row mb-3">
        <legend class="col-sm-4 col-form-label">
            <?= /* I18N: A configuration setting */ I18N::translate('Show living individuals') ?>
            <div class="hidden-xs">
                <span class="badge visitors"><?= I18N::translate('visitors') ?></span>
                <span class="badge members"><?= I18N::translate('members') ?></span>
            </div>
        </legend>

        <div class="col-sm-8">
            <?= view('components/select', ['name' => 'HIDE_LIVE_PEOPLE', 'selected' => $tree->getPreference('HIDE_LIVE_PEOPLE'), 'options' => ['0' => I18N::translate('Show to visitors'), '1' => I18N::translate('Show to members')]]) ?>
            <div class="form-text">
                <?= /* I18N: Help text for the “Show living individuals” configuration setting */ I18N::translate('If you show living individuals to visitors, all other privacy restrictions are ignored. Do this only if all the data in your tree is public.') ?>
            </div>
        </div>
    </fieldset>

    <!-- KEEP_ALIVE_YEARS_BIRTH / KEEP_ALIVE_YEARS_DEATH -->
    <fieldset class="row mb-3">
        <legend class="col-form-label col-sm-4">
            <?= /* I18N: A configuration setting. …who were born in the last XX years or died in the last YY years */ I18N::translate('Extend privacy to dead individuals') ?>
        </legend>
        <div class="col-sm-8">
            <?php
            echo
                /* I18N: Extend privacy to dead individuals who were… */ I18N::translate(
                    'born in the last %1$s years or died in the last %2$s years',
                    '<input type="text" name="KEEP_ALIVE_YEARS_BIRTH" value="' . $tree->getPreference('KEEP_ALIVE_YEARS_BIRTH') . '" size="5" maxlength="3">',
                    '<input type="text" name="KEEP_ALIVE_YEARS_DEATH" value="' . $tree->getPreference('KEEP_ALIVE_YEARS_DEATH') . '" size="5" maxlength="3">'
                ) ?>
            <div class="form-text">
                <?= /* I18N: Help text for the “Extend privacy to dead individuals” configuration setting */ I18N::translate('In some countries, privacy laws apply not only to living individuals, but also to those who have died recently. This option will allow you to extend the privacy rules for living individuals to those who were born or died within a specified number of years. Leave these values empty to disable this feature.') ?>
            </div>
        </div>
    </fieldset>

    <!-- SHOW_LIVING_NAMES -->
    <div class="row mb-3">
        <div class="col-form-label col-sm-4">
            <label for="SHOW_LIVING_NAMES">
                <?= /* I18N: A configuration setting */ I18N::translate('Show names of private individuals') ?>
            </label>
            <div class="hidden-xs">
                <span class="badge visitors"><?= I18N::translate('visitors') ?></span>
                <span class="badge members"><?= I18N::translate('members') ?></span>
                <span class="badge managers"><?= I18N::translate('managers') ?></span>
            </div>
        </div>
        <div class="col-sm-8">
            <?= view('components/select', ['name' => 'SHOW_LIVING_NAMES', 'selected' => $tree->getPreference('SHOW_LIVING_NAMES'), 'options' => array_slice(Auth::accessLevelNames(), 0, 3, true)]) ?>
            <div class="form-text">
                <?= /* I18N: Help text for the “Show names of private individuals” configuration setting */ I18N::translate('This option will show the names (but no other details) of private individuals. Individuals are private if they are still alive or if a privacy restriction has been added to their individual record. To hide a specific name, add a privacy restriction to that name record.') ?>
            </div>
        </div>
    </div>

    <!-- SHOW_PRIVATE_RELATIONSHIPS -->
    <div class="row mb-3">
        <div class="col-form-label col-sm-4">
            <label for="SHOW_PRIVATE_RELATIONSHIPS">
                <?= /* I18N: A configuration setting */ I18N::translate('Show private relationships') ?>
            </label>
            <div class="hidden-xs">
                <span class="badge visitors"><?= I18N::translate('visitors') ?></span>
                <span class="badge members"><?= I18N::translate('members') ?></span>
            </div>
        </div>
        <div class="col-sm-8">
            <?= view('components/select', ['name' => 'SHOW_PRIVATE_RELATIONSHIPS', 'selected' => $tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS'), 'options' => ['0' => I18N::translate('Hide from everyone'), '1' => I18N::translate('Show to visitors')]]) ?>
            <div class="form-text">
                <?= /* I18N: Help text for the “Show private relationships” configuration setting */ I18N::translate('This option will retain family links in private records. This means that you will see empty “private” boxes on the pedigree chart and on other charts with private individuals.') ?>
            </div>
        </div>
    </div>
    <h2><?= /* I18N: Privacy restrictions are set by RESN tags in GEDCOM. */ I18N::translate('Privacy restrictions') ?></h2>
    <p>
        <?= /* I18N: Privacy restrictions are RESN tags in GEDCOM. */ I18N::translate('You can set the access for a specific record, fact, or event by adding a restriction to it. If a record, fact, or event does not have a restriction, the following default restrictions will be used.') ?>
    </p>

    <script id="new-resn-template" type="text/html">
        <tr>
            <td class="w-50">
                <select class="form-select record-type-selector mb-3">
                    <option value="all"><?= I18N::translate('All records') ?></option>
                    <option value="individual"><?= I18N::translate('Individual') ?></option>
                    <option value="family"><?= I18N::translate('Family') ?></option>
                    <option value="source"><?= I18N::translate('Source') ?></option>
                    <option value="repository"><?= I18N::translate('Repository') ?></option>
                    <option value="note"><?= I18N::translate('Note') ?></option>
                    <option value="media"><?= I18N::translate('Media object') ?></option>
                </select>

                <div class="select-record select-all">
                    <div class="d-none">
                        <select name="xref[]">
                            <option selected="selected"></option>
                        </select>
                    </div>
                </div>

                <div class="select-record select-individual d-none">
                    <?= view('components/select-individual', ['name' => 'xref[]', 'id' => '', 'tree' => $tree, 'disabled' => true, 'required' => true]) ?>
                </div>

                <div class="select-record select-family d-none">
                    <?= view('components/select-family', ['name' => 'xref[]', 'id' => '', 'tree' => $tree, 'disabled' => true, 'required' => true]) ?>
                </div>

                <div class="select-record select-source d-none">
                    <?= view('components/select-source', ['name' => 'xref[]', 'id' => '', 'tree' => $tree, 'disabled' => true, 'required' => true]) ?>
                </div>

                <div class="select-record select-repository d-none">
                    <?= view('components/select-repository', ['name' => 'xref[]', 'id' => '', 'tree' => $tree, 'disabled' => true, 'required' => true]) ?>
                </div>

                <div class="select-record select-note d-none">
                    <?= view('components/select-note', ['name' => 'xref[]', 'id' => '', 'tree' => $tree, 'disabled' => true, 'required' => true]) ?>
                </div>

                <div class="select-record select-media d-none">
                    <?= view('components/select-media', ['name' => 'xref[]', 'id' => '', 'tree' => $tree, 'disabled' => true, 'required' => true]) ?>
                </div>
            </td>

            <td>
                <?= view('components/select', ['name' => 'tag_type[]', 'id' => '', 'selected' => '', 'options' => $all_tags]) ?>
            </td>

            <td>
                <?= view('components/select', ['name' => 'resn[]', 'id' => '', 'selected' => 'privacy', 'options' => $privacy_constants]) ?>
            </td>

            <td>
            </td>
        </tr>
    </script>

    <table class="table table-bordered table-sm table-hover" id="default-resn">
        <caption class="visually-hidden">
            <?= I18N::translate('Privacy restrictions - these apply to records and facts that do not contain a GEDCOM RESN tag') ?>
        </caption>
        <thead>
            <tr>
                <th class="w-50">
                    <?= I18N::translate('Record') ?>
                </th>
                <th>
                    <?= I18N::translate('Fact or event') ?>
                </th>
                <th>
                    <?= I18N::translate('Access level') ?>
                </th>
                <th>
                    <button class="btn btn-primary" id="add-resn" type="button">
                <?= view('icons/add') ?>
                        <?= /* I18N: A button label. */ I18N::translate('add') ?>
                    </button>
                </th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($privacy_restrictions as $privacy_restriction) : ?>
                <tr>
                    <td>
                        <?php if ($privacy_restriction->record) : ?>
                            <a href="<?= e($privacy_restriction->record->url()) ?>"><?= $privacy_restriction->record->fullName() ?></a>
                        <?php elseif ($privacy_restriction->xref) : ?>
                            <div class="text-danger">
                                <?= $privacy_restriction->xref ?> — <?= I18N::translate('This record does not exist.') ?>
                            </div>
                        <?php else : ?>
                            <div class="text-muted">
                                <?= I18N::translate('All records') ?>
                            </div>
                        <?php endif ?>
                    </td>
                    <td>
                        <?php if ($privacy_restriction->label === '') : ?>
                            <div class="text-muted">
                                <?= I18N::translate('All facts and events') ?>
                            </div>
                        <?php else : ?>
                            <?= $privacy_restriction->label ?>
                        <?php endif ?>
                    </td>
                    <td>
                        <?= Auth::privacyRuleNames()[$privacy_restriction->resn] ?>
                    </td>
                    <td>
                        <label for="delete-<?= $privacy_restriction->default_resn_id ?>">
                            <input id="delete-<?= $privacy_restriction->default_resn_id ?>" name="delete[]" type="checkbox" value="<?= $privacy_restriction->default_resn_id ?>">
                            <?= I18N::translate('Delete') ?>
                        </label>
                    </td>
                </tr>
            <?php endforeach ?>
        </tbody>
    </table>

    <div class="row mb-3">
        <div class="offset-sm-4 col-sm-8">
            <button type="submit" class="btn btn-primary">
                <?= view('icons/save') ?>
                <?= I18N::translate('save') ?>
            </button>

            <a class="btn btn-secondary" href="<?= route(ManageTrees::class, ['tree' => $tree->name()]) ?>">
                <?= view('icons/cancel') ?>
                <?= I18N::translate('cancel') ?>
            </a>
            <!-- Coming soon
            <div class="form-check">
                <?php if ($count_trees > 1) : ?>
                <label>
                    <input type="checkbox" name="all_trees">
                    <?= /* I18N: Label for checkbox */ I18N::translate('Apply these preferences to all family trees') ?>
                </label>
                <?php endif ?>
            </div>
            <div class="form-check">
                <label>
                    <input type="checkbox" name="new_trees">
                    <?= /* I18N: Label for checkbox */ I18N::translate('Apply these preferences to new family trees') ?>
                </label>
            </div>
            -->
        </div>
    </div>

    <?= csrf_field() ?>
</form>

<?php View::push('javascript') ?>
<script>
  'use strict';

  /**
   * Hide/show the feedback labels for a privacy option.
   *
   * @param sel    the control to change
   * @param who    "visitors", "members" or "managers"
   * @param access true or false
   */
  function setPrivacyFeedback (sel, who, access) {
    var formGroup = $(sel).closest('.row');

    if (access) {
      $('.' + who, formGroup).addClass('bg-success').removeClass('bg-secondary');
      $('.' + who + ' i', formGroup).addClass('fa-check').removeClass('fa-times');
    } else {
      $('.' + who, formGroup).addClass('bg-secondary').removeClass('bg-success');
      $('.' + who + ' i', formGroup).addClass('fa-times').removeClass('fa-check');
    }
  }

  /**
   * Update all the privacy feedback labels.
   */
  function updatePrivacyFeedback () {
    var requireAuthentication = parseInt($('[name=REQUIRE_AUTHENTICATION]').val(), 10);
    var showDeadPeople = parseInt($('[name=SHOW_DEAD_PEOPLE]').val(), 10);
    var hideLivePeople = parseInt($('[name=HIDE_LIVE_PEOPLE]').val(), 10);
    var showLivingNames = parseInt($('[name=SHOW_LIVING_NAMES]').val(), 10);
    var showPrivateRelationships = parseInt($('[name=SHOW_PRIVATE_RELATIONSHIPS]').val(), 10);

    setPrivacyFeedback('[name=REQUIRE_AUTHENTICATION]', 'visitors', requireAuthentication === 0);
    setPrivacyFeedback('[name=REQUIRE_AUTHENTICATION]', 'members', true);

    setPrivacyFeedback('[name=SHOW_DEAD_PEOPLE]', 'visitors', requireAuthentication === 0 && (showDeadPeople >= 2 || hideLivePeople === 0));
    setPrivacyFeedback('[name=SHOW_DEAD_PEOPLE]', 'members', showDeadPeople >= 1 || hideLivePeople === 0);

    setPrivacyFeedback('[name=HIDE_LIVE_PEOPLE]', 'visitors', requireAuthentication === 0 && hideLivePeople === 0);
    setPrivacyFeedback('[name=HIDE_LIVE_PEOPLE]', 'members', true);

    setPrivacyFeedback('[name=SHOW_LIVING_NAMES]', 'visitors', requireAuthentication === 0 && showLivingNames >= 2);
    setPrivacyFeedback('[name=SHOW_LIVING_NAMES]', 'members', showLivingNames >= 1);
    setPrivacyFeedback('[name=SHOW_LIVING_NAMES]', 'managers', showLivingNames >= 0);

    setPrivacyFeedback('[name=SHOW_PRIVATE_RELATIONSHIPS]', 'visitors', requireAuthentication === 0 && showPrivateRelationships >= 1);
    setPrivacyFeedback('[name=SHOW_PRIVATE_RELATIONSHIPS]', 'members', showPrivateRelationships >= 1);
  }

  // Activate the privacy feedback labels.
  updatePrivacyFeedback();
  $('[name=REQUIRE_AUTHENTICATION], [name=HIDE_LIVE_PEOPLE], [name=SHOW_DEAD_PEOPLE], [name=SHOW_LIVING_NAMES], [name=SHOW_PRIVATE_RELATIONSHIPS]').on('change', function () {
    updatePrivacyFeedback();
  });

  // Mute a line when it is marked for deletion
  $('#default-resn').on('click', 'input[type=checkbox]', function () {
    if ($(this).prop('checked')) {
      $($(this).closest('tr').addClass('text-muted'));
    } else {
      $($(this).closest('tr').removeClass('text-muted'));
    }
  });

  // Add a new row to the table
  $('#add-resn').on('click', function () {
    $('#default-resn tbody').prepend($('#new-resn-template').html());

    document.querySelectorAll('#default-resn tbody tr:first-child select.tom-select')
      .forEach(element => webtrees.initializeTomSelect(element));

    let row = document.getElementById('default-resn').querySelector('tbody tr');
    webtrees.initializeIFSRO(row.querySelector('select'), row);
  });
</script>
<?php View::endpush() ?>
