var crud_section_view = '';
crud_section_view += '<div class="tab">';
crud_section_view += '<div id="createNewRecorddiv">';
crud_section_view += '<button id="createNewCommodity" class="upload_btn ui button btn btn-success" style="background: burlywood; color: white;" onclick="createStepperForm();">Add New</button>';
crud_section_view += '</div>';
crud_section_view += '</div>';
$(".crud_section_header").html(crud_section_view);



var userObj = JSON.parse(localStorage.getItem('userObj'));
loadData();

function loadData() {
    console.log("userObjuserObj", userObj);

    var html3 = "";
    html3 += '<div class="ui segment inspectionssection" style="height: 600px">';
    html3 += '<div class="ui active inverted dimmer">';
    html3 += '<div class="ui text loader">Loading</div>';
    html3 += '</div>';
    html3 += '<p></p>';
    html3 += '</div>';
    $(".crud_section").html(html3);
    var html = "";
    var url = serverURL + "apiEndpoints/getAPIEndpointsTobeMappedPaginated/0/1000";

    $.ajax({
        url: url,
        type: 'GET',
        headers: {
            Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
            "Content-Type": "application/json",
        },
        success: function(data, textStatus, xhr) {
            console.log("getAPIEndpointsTobeMappedPaginated", data.content);

            html = html + ' <div class="ibox-head">';
            html = html + '<h3 class="ibox-title" style="color:black; font-weight:  800;padding-bottom:4px ">Menu Access Mapping</h3>';
            html = html + '</div>';

            html = html + '<div>';
            html = html + '<div id="mytenders">';
            html = html + ' </div>';
            html = html + ' </div>';
            var jsonData = data.content;


            var tableHTML = $(".crudsection");
            html = html + ' <div class="ibox-body">';
            html = html + "<table class='table table-striped table-bordered table-hover' id='tendertableview' cellspacing='0' width='100%'>";
            html = html + '  <thead>';
            html = html + '   <tr>';
            html = html + '     <th style="display:none"></th>';
            html = html + '     <th  style="display:none">#</th>';
            html = html + '      <th>Name</th>';
            html = html + '      <th>Url</th>';
            html = html + '      <th>Method</th>';
            html = html + '      <th>Method Name</th>';
            // html = html + '      <th style="width:10%; text-align:center">Actions</th>';

            html = html + '   </tr>';
            html = html + ' </thead>';
            html = html + "<tbody>";
            for (var i = 0; i < jsonData.length; i++) {

                html = html + ' <tr>';
                html = html + '  <td style="display:none">';
                html = html + '  <div class="ckbox ckbox-theme">';
                html = html + '      <input id="checkbox1" type="checkbox" checked="checked" class="mail-checkbox">';
                html = html + '    </div>';
                html = html + '  </td>';
                html = html + '  <td style="display:none">';
                html = html + '    <a href="#" class="star star-checked"><i></i></a>';
                html = html + '  </td>';


                html = html + '  <td>';
                html = html + '   <div class="media">';
                html = html + '       <div class="media-body">';
                html = html + "          <a href='javascript:controller.viewmytederdetailsbtn(" + JSON.stringify(jsonData[i]) + ")'><p>" + jsonData[i].controllerName + " </p></a>";
                html = html + '         </div>';
                html = html + '     </div>';
                html = html + '  </td>';

                html = html + '  <td style="width:200px; text-align: left;">';
                html = html + '   <div class="media">';
                html = html + '       <div class="media-body">';
                html = html + '           <p>' + jsonData[i].urlPattern + ' </p>';
                html = html + '         </div>';
                html = html + '     </div>';
                html = html + '  </td>';

                html = html + '  <td style="width:300px; text-align: left;">';
                html = html + '   <div class="media">';
                html = html + '       <div class="media-body">';
                html = html + "<p  style='color:#black; '>" + jsonData[i].httpMethod + " </p>";
                // html = html + '           <p>' + jsonData[i].tenderName + ' </p>';
                html = html + '         </div>';
                html = html + '     </div>';
                html = html + '  </td>';

                html = html + '  <td>';
                html = html + '   <div class="media">';
                html = html + '       <div class="media-body">';
                html = html + '           <p>' + jsonData[i].methodName + ' </p>';
                html = html + '         </div>';
                html = html + '     </div>';
                html = html + '  </td>';


                // html += " <td class='time' style='width:15%; text-align:center'>";
                // html += "<a href='javascript:controller.viewmytederdetailsbtn(" + JSON.stringify(jsonData[i]) + ")' style='color:#23b7e5; font-weight:800; font-size:16px; text-align:center; margin-right:10px;'>View</a>"
                // html += "</td>";

                html = html + '</tr>';

            }
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + ' </div>';

            tableHTML.html(html);
            $(".crud_section").html(html);
            $('#tendertableview').DataTable({
                dom: "Bfrltip",
                "bJQueryUI": true,
                "aLengthMenu": [
                    [2, 3, 5, 10, 20, 25, 50, 75, -1],
                    [2, 3, 5, 10, 20, 25, 50, 75, "All"]
                ],
                "iDisplayLength": 10,
                "scroller": {
                    loadingIndicator: true
                },
                "orderCellsTop": true,
                "fixedHeader": true,

                "bProcessing": true,
                "mark": true,
                "responsive": true,
                'autoWidth': true,

            });
        },
        fail: function(xhr, textStatus) {},
        error: function(xhr, textStatus) {}
    });

}



function createStepperForm() {
    isEdit = false;
    var htmlsection = "";
    htmlsection += '<div class="ui grid">';
    htmlsection += '<div class="twelve wide column form-wrapper" style="width: 100% ! important">';

    htmlsection += '<div class="ui mini steps" style="overflow:hidden;width:100%;font-family: \'Monda\', sans-serif;">';
    htmlsection += '<div class="active step step_zero"><span class="fa fa-folder-open-o"></span> <div class="content"> <div class="title">Menu Details</div><div class="description"></div> </div></div>';
    htmlsection += '</div>';
    htmlsection += '<div id="error-msg" class="ui error message"> <p><strong>Note: </strong> All Fields are Mandatory</p></div>';
    htmlsection += '<div class="ui tall stacked segment">';
    htmlsection += '<div id="step_zero">';

    htmlsection += '<form class="ui form" id="main_submit_form">';
    htmlsection += '   <h4>Menu Details</h4>';


    htmlsection += '    <div class="two fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Role<span class="asteric">*</span></label>';
    htmlsection += '    <select  class="ui fluid dropdown search" name="ad_Role_ID" id="ad_Role_ID">';
    htmlsection += '    <option selected value="">-Select Option-</option>';
    htmlsection += '    </select>';
    htmlsection += '      </div>';

    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Menus<span class="asteric">*</span></label>';
    htmlsection += '    <select  class="ui fluid dropdown search multiple" name="ad_Menu_IDs" id="ad_Menu_IDs">';
    htmlsection += '    <option selected value="">-Select Option-</option>';
    htmlsection += '    </select>';
    htmlsection += '      </div>';
    htmlsection += '    </div>';
    htmlsection += '</form>';

    htmlsection += '<div class="btns" style="display: flex; margin: 2px">';
    htmlsection += '<button id="nexttostepone" onclick="processStepzero()" type="button" class="ui green right labeled icon button"><i class="fa fa-angle-double-right"></i>Save</button>';
    htmlsection += '</div>';
    htmlsection += '</div>';

    htmlsection += '</div>';
    $(".crud_section").html(htmlsection);

    $('.ui.dropdown').dropdown({
        fullTextSearch: true
    });


    var option2 = ""
    var url = serverURL + "membership/role/getActiveRole";
    controller.requestWithToken(url, function(data, status) {
        var jsondata = data.content;
        if (jsondata.length > 0) {
            option2 += "<option selected value=''>-Select Option-</option>";
            option2 += controller.loadSelect(jsondata, 'id', 'name', '');
            $('#ad_Role_ID').html(option2);
        } else {
            option2 += "<option value=''>-Select Option-</option>";
            $('#ad_Role_ID').html(option2);
        }
    });



    var option = ""
    var url = serverURL + "dashboard/getAllMenus/0/1000";
    controller.requestWithToken(url, function(data, status) {

        var jsdata = data.content;
        if (jsdata.length > 0) {
            option += controller.loadSelect(jsdata, 'id', 'name', '');
            $('#ad_Menu_IDs').html(option);
        } else {
            option += "<option value=''>-Select Option-</option>";
            $('#ad_Menu_IDs').html(option);
        }
    });
}









// Navigations
function processStepzero() {
    var formJson = $("#main_submit_form").serializeObject();

    if (formJson.ad_Role_ID == "") {
        controller.showToastMsg("Role Required", "#ff6666");
    } else if (formJson.ad_Menu_IDs == "") {
        controller.showToastMsg("Description Required", "#ff6666");
    } else {

        formJson.ad_Menu_IDs = [formJson.ad_Menu_IDs];
        setTimeout(function() {
            $('#nexttostepone').html("Saving & Exit");
            $("#nexttostepone").attr("disabled", false);
        }, 1000);

        $('#nexttostepone').html("Saving... Please Wait!");
        $("#nexttostepone").attr("disabled", true);
        var url = serverURL + "dashboard/mappOrUpdateMenuMapping";
        controller.allPostRequest(url, formJson, '', function(data, status) {
            if (data) {
                $('#nexttostepone').html("Save");
                $("#nexttostepone").attr("disabled", false);
                isEdit = false;
                loadData();
            }
        });
    }

}




function processStepZeroUpdate(recordID) {
    var formJson = $("#main_submit_form").serializeObject();
    var recordID = localStorage.getItem("menuRoles_id");
    $('#backtostepzero').html("Updating... Please Wait!");
    $("#backtostepzero").attr("disabled", true);

    if (formJson.roleName == "") {
        controller.showToastMsg("Name Required", "#ff6666");
    } else if (formJson.roleDescription == "") {
        controller.showToastMsg("Description Required", "#ff6666");
    } else {
        setTimeout(function() {
            $('#nexttostepone').html("Saving & Exit");
            $("#nexttostepone").attr("disabled", false);
        }, 1000);


        formJson.id = recordID;
        var url = serverURL + "menuRoles/updateMenuRoles";
        controller.allPostRequest(url, formJson, '', function(data, status) {
            isEdit = false;
            $('#backtostepzero').html("Save & Exit");
            $("#backtostepzerok").attr("disabled", false);
            loadData();
        });
    }




}


function refresh() {
    window.location.reload();
}