<?php

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

/**
 * @var Tree $tree
 */

?>

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

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

    <div class="modal-body">
        <?= view('modals/submission-fields', ['tree' => $tree]) ?>
    </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.selectId);

        $.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 select2
                    // edit control, then insert the result and select it.
                    let option       = new Option(data.text, data.id, true, true);
                    option.innerHTML = option.innerText;

                    $(select)
                        .select2({ escapeMarkup: (x) => x })
                        .empty()
                        .append(option)
                        .trigger("change");

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