
// ====================
// Start Support Ticket
// ====================

$(document).ready(function () {

    var $application = $("#APPLICATION_MNEMONIC").val(),
            $sessionStorage = JSON.parse(sessionStorage.getItem($application) || "{}"),
            $CKEditor;

    // ----------------------
    // Initialize the Editor.
    // ----------------------

    ClassicEditor
            .create(document.querySelector('#supportticket_message'), {
                toolbar: {
                    items: [
                        'heading',
                        '|',
                        'bold',
                        'italic',
                        'underline',
                        'link',
                        'bulletedList',
                        'numberedList',
                        '|',
                        'fontColor',
                        'fontSize',
                        'fontFamily',
                        '|',
                        'indent',
                        'outdent',
                        'alignment',
                        '|',
                        'horizontalLine',
                        'insertTable',
                        '|',
                        'undo',
                        'redo',
                        '|'
                    ]},
                link: {
                    addTargetToExternalLinks: true,
                    defaultProtocol: "http://"

                }
            })
            .then(editor => {
                $CKEditor = editor;
            })
            .catch(error => {
                console.error('CK-Editor error...');
                console.error(error);
            });

    // -----------
    // Save Button
    // -----------

    $(".btnSubmit").on("click", function (e) {

        e.preventDefault();

        $("#startSupportTicket").submit();

    });

    // --------------
    // Cancel Button.
    // --------------

    $(".btnCancel").on("click", function () {

        $sessionStorage.action = $sessionStorage.startSupportTicket || "";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // ---------------------
    // Show "Other Category"
    // ---------------------

    $('#supportticket_category').on('change', function () {

        const isOther =
                $(this).find('option:selected').data('tokens') === 'Other';

        $('.other_catagory').toggleClass('d-none', !isOther);

        if (!isOther) {
            $('#supportticket_category_other').val('');
        }

    });



    // ---------------
    // Validate Inputs
    // ---------------

    $("#startSupportTicket").submit(function (e) {

        var supportticket_subject = $("#supportticket_subject"),
                supportticket_category = $("#supportticket_category"),
                supportticket_category_other = $("#supportticket_category_other"),
                supportticket_message = $("#supportticket_message");

        clearInputErrors();

        supportticket_subject.val(supportticket_subject.val().replace(/\s+/g, " ").trim());
        supportticket_category.val(supportticket_category.val().replace(/\s+/g, " ").trim());

        if (isBlank(supportticket_subject)) {
            createInputError(supportticket_subject, "Subject is required");
            return false;
        }

        if ($("option:selected", supportticket_category).val() === "") {
            createInputError(supportticket_category, "Catagory is required");
            return false;
        }

        if ($("option:selected", supportticket_category).data('tokens') === "Other" && isBlank(supportticket_category_other)) {
            createInputError(supportticket_category_other, "Other Catagory is required");
            return false;
        }

        // Make sure editor is ready
        const html = ($CKEditor) ? $CKEditor.getData() : "";

        // Convert HTML -> plain text and trim (handles <p>&nbsp;</p> etc.)
        const text = html
                .replace(/<[^>]*>/g, " ")
                .replace(/&nbsp;/g, " ")
                .replace(/\s+/g, " ")
                .trim();

        if (!text) {
            // highlight editor UI (not just hidden textarea)
            const editableEl = $CKEditor?.ui?.view?.editable?.element;
            if (editableEl)
                $(editableEl).addClass("is-invalid");

            createInputError(supportticket_message, "Message is required");
            return false;
        }


        e.preventDefault();

        $CKEditor.updateSourceElement();

// show spinner + prevent double submit
        $("#ticketSending").removeClass("d-none");
        $(".btnSubmit, .btnCancel").prop("disabled", true);


        $.post("./", $(this).serialize())
                .done(function () {

                    $sessionStorage.action = $sessionStorage.startSupportTicket || "";
                    sessionStorage.setItem($application, JSON.stringify($sessionStorage));
                    formSubmit($sessionStorage);

                })
                .fail(function () {

                    // show a friendly message (optional)
                    alert("Something went wrong sending the ticket. Please try again.");

                })
                .always(function () {

                    // hide spinner + re-enable buttons
                    $("#ticketSending").addClass("d-none");
                    $(".btnSubmit, .btnCancel").prop("disabled", false);

                });
    });

});