<?php

$id = Str::random(5);

$moduleHtml = '
    <div id="{id}" class="form-builder"></div>

    <script>
        var docReady{id} = function (fn) {
            var stateCheck = setInterval(function () {
                if (document.readyState !== "complete") return;
                clearInterval(stateCheck);
                try {fn()} catch (e) {}
            }, 1000);
        };
        docReady{id}(function () {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState === XMLHttpRequest.DONE) {
                    if (xmlhttp.status === 200) {
                        let formContainer = document.getElementById("{id}");
                        formContainer.innerHTML = xmlhttp.responseText;

                        let form = formContainer.getElementsByTagName("form")[0];
                        if (! form) {
                            console.log("Form not found");
                            return;
                        }

                        let formId = form.getAttribute("id");
                        if (! formId) {
                            console.log("Form id not found");
                            return;
                        }

                        let validationRequest{id} = new ValidationRequest(formId);
                        validationRequest{id}.init();
                    }
                }
            };
            xmlhttp.open("GET", "/api/builder/form-builder", true);
            xmlhttp.send();
        });
    </script>
';

$moduleHtml = str_replace('{id}', $id, $moduleHtml);

$moduleSettings = '
    {
        "ref": null
    }
';
?>

<div class="row clearfix border-0">
    <div class="col-12"
         data-noedit
         data-module="form-builder"
         data-dialog-width="500px"
         data-module-desc="Form Builder"
         data-html="{{ encode_uri_component($moduleHtml) }}"
         data-settings="{{ encode_uri_component($moduleSettings) }}"
    >
    </div>
</div>
