<?php

use Fisharebest\Webtrees\Http\RequestHandlers\CreateSubmitterAction;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Tree;

/**
 * @var Tree $tree
 */

?>

<form method="post" action="<?= e(route(CreateSubmitterAction::class, ['tree' => $tree->name()])) ?>" id="wt-modal-form">
    <?= csrf_field() ?>

    <?= view('modals/header', ['title' => I18N::translate('Create a submitter')]) ?>

    <div class="modal-body">
        <?= view('modals/submitter-fields') ?>
    </div>

    <?= view('modals/footer-save-cancel') ?>
</form>

<script>
  // Submit the modal form using AJAX
  document.getElementById('wt-modal-form').addEventListener('submit', function (event) {
    event.preventDefault();
    let form = event.target;
    let modal_content = document.querySelector('#wt-ajax-modal .modal-content');
    let select = document.getElementById(modal_content.dataset.wtSelectId);

    $.ajax({
      url: form.action,
      type: form.method,
      data: new FormData(form),
      async: false,
      cache: false,
      contentType: false,
      processData: false,
      success: function (data) {
        if (select) {
          // If this modal was activated by the "new" button in a select
          // edit control, then insert the result and select it.
          webtrees.resetTomSelect(select.tomselect, data.value, data.text);

          $('#wt-ajax-modal').modal('hide');
        } else {
          modal_content.innerHTML = data.html;
        }
      },
      failure: function (data) {
        modal_content.innerHTML = data.html;
      },
    });
  });
</script>
