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



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

function loadData() {
    console.log("userObj:", 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 + "users/userList?pageNo=0&pageSize=100";

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
            "Content-Type": "application/json",
        },
        async: true,
        success: function(data) {
            console.log("mytenders:", data);
            html += '<div class="ibox-head">';
            html += '<h3 class="ibox-title" style="color:black; font-weight: 800; padding-bottom:4px;">Drivers</h3>';
            html += '</div>';
            html += '<div>';
            html += '<div id="mytenders"></div>';
            html += '</div>';

            var tableHTML = $(".crud_section");
            html += '<div class="ibox-body">';
            html += "<table class='table table-striped table-bordered table-hover' id='tendertableview' cellspacing='0' width='100%'>";
            html += '<thead><tr>';
            html += '  <th style="width:5%; text-align:center;"><input type="checkbox" id="selectAll"></th>';
            html += '  <th style="width:5%; text-align:center;">#</th>';
            html += '  <th>First Name</th>';
            html += '  <th>Last Name</th>';
            html += '  <th>Email</th>';
            html += '  <th>Phone No</th>';
            html += '  <th style="width:10%; text-align:center">Actions</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            data.forEach((item, i) => {
                html += `<tr>
                    <td style="text-align:center;"><input type="checkbox" class="row-checkbox" data-id="${item.users_id}"></td>
                    <td style="text-align:center;">${i + 1}</td>
                    <td><a href="javascript:controller.viewmytederdetailsbtn(${JSON.stringify(item)})"><p>${item.firstName}</p></a></td>
                    <td style="width:200px; text-align: left;">${item.lastName}</td>
                    <td style="width:300px; text-align: left;">${item.email}</td>
                    <td>${item.phoneNo}</td>
                    <td class="time" style="width:15%; text-align:center">
                        <div class="dropdown">
                            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Actions</button>
                            <div class="dropdown-menu">
                                 <a class="dropdown-item view-action" 
                                href="javascript:viewRowData('${encodeURIComponent(JSON.stringify(item))}')">
                                View
                                </a>
                                  <a class="dropdown-item edit-action" 
                            href="javascript:editRowData('${encodeURIComponent(JSON.stringify(item))}')"
                               data-id="${item.vehicleId}">
                                Edit
                            </a>

                                <a class="dropdown-item delete-action" href="#" data-id="${item.users_id}">Delete</a>
                            </div>
                        </div>
                    </td>
                </tr>`;
            });

            html += '</tbody></table></div>';
            tableHTML.html(html);
            $(".crud_section").html(html);

            // Initialize DataTable
            $('#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: 5,
                scroller: { loadingIndicator: true },
                orderCellsTop: true,
                fixedHeader: true,
                bProcessing: true,
                mark: true,
                responsive: true,
                autoWidth: true,
            });

            // Select All Checkbox functionality
            $("#selectAll").on("click", function() {
                $(".row-checkbox").prop("checked", this.checked);
            });

         
        }
    });
}

function editRowData(res) {
    
        var data = JSON.parse(decodeURIComponent(res));

     var htmlsection = "";
    htmlsection += '<form class="ui form form_section" id="main_submit_form">';
    htmlsection += '  <div id="step_zero">';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>First Name <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="firstName" value="'+data.firstName+'" name="firstName" placeholder="First Name">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Last Name<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="lastName" name="lastName" value="'+data.lastName+'" placeholder="Last Name">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Other Name<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="30" id="otherNames" name="otherNames" value="'+data.otherNames+'" placeholder="Other Name">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Email <span class="asteric">*</span></label>';
    htmlsection += '        <input type="email" maxlength="30" id="email" name="email" value="'+data.email+'" placeholder="Email">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Username<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="username" name="username" value="'+data.username+'" placeholder="Username">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Password<span class="asteric">*</span></label>';
    htmlsection += '        <input type="password" maxlength="30" id="password" name="password" value="abc123" placeholder="eg abc123">';
    htmlsection += '   <i class="fa fa-eye" onclick="viewPass()" id="togglePassword"></i>';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Phone Number<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="13" id="phoneNo" name="phoneNo"value="'+data.phoneNo+'" placeholder="Phone No eg +254722000000">';
    htmlsection += ' <p id="validationMessage"></p>';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>National ID No <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="nationalIDNo" name="nationalIDNo" value="'+data.nationalIDNo+'" placeholder="National ID No">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '<div class="field">';
    htmlsection += '    <label>Roles</label>';
    htmlsection += '    <select id="roleName" name="roleName" class="ui search dropdown">';
    htmlsection += '    </select>';
    htmlsection += '</div>';
    htmlsection += '</div>';

     htmlsection += '<div class="btns" style="display:flex; gap:10px; margin-top:10px;">';
    htmlsection += '  <button onclick="updateRecord('+data.users_id+')" type="button" class="ui green right labeled icon button">Update<i class="fa fa-check"></i></button>';
    htmlsection += '  <button onclick="loadData()" type="button" class="ui red right labeled icon button">Return<i class="fa fa-arrow-left"></i></button>';
    htmlsection += '</div>';

    htmlsection += '</div>';

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

    var option_role = "";
    var url_pp = serverURL + 'roles/roleList?pageNo=0&pageSize=100';
    controller.getAuthRequest(url_pp, true, function(data, status) {
        option_role += controller.loadSelect(data, 'name', 'name', '');
        $('#roleName').html(option_role);
    });

   
}


function viewRowData(data) {
    var jsondata = JSON.parse(decodeURIComponent(data));

    let rolesText = "";
    if (jsondata.roles && jsondata.roles.length > 0) {
        rolesText = jsondata.roles.join(", ");
    }

    let tableRows = `
        <tr>
            <th>User ID</th><td>${jsondata.userId || ''}</td>
            <th>Username</th><td>${jsondata.username || ''}</td>
        </tr>
        <tr>
            <th>First Name</th><td>${jsondata.firstName || ''}</td>
            <th>Other Names</th><td>${jsondata.otherNames || ''}</td>
        </tr>
        <tr>
            <th>Last Name</th><td>${jsondata.lastName || ''}</td>
            <th>Email</th><td>${jsondata.email || ''}</td>
        </tr>
        <tr>
            <th>Phone Number</th><td>${jsondata.phoneNo || ''}</td>
            <th>National ID</th><td>${jsondata.nationalIDNo || ''}</td>
        </tr>
        <tr>
            <th>Roles</th><td>${rolesText}</td>
            <th>Sub Admin</th><td>${jsondata.subAdmin ? 'Yes' : 'No'}</td>
        </tr>
        <tr>
            <th>Account Locked</th><td>${jsondata.locked ? 'Yes' : 'No'}</td>
            <th>Account Expired</th><td>${jsondata.expired ? 'Yes' : 'No'}</td>
        </tr>
        <tr>
            <th>Last Login</th><td>${jsondata.lastLogin || 'Never'}</td>
            <th></th><td></td>
        </tr>
    `;

    let html = `
        <div class="form_section">

            <h3 style="font-weight:800; margin-bottom:20px;">User Details</h3>

            <div style="background:#fff; padding:15px; border-radius:6px; border:1px solid #eee;">
                <table class="table table-bordered table-striped">
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <div class="text-right" style="margin-top:20px;">
                    <a href="javascript:void(0);" onclick="loadData()" class="btn btn-warning">
                        Return
                    </a>
                </div>
            </div>

        </div>
    `;

    $(".crud_section").html(html);
}



function deleteRowData(id) {
    console.log("Deleting role with ID:", id);
    if (confirm("Are you sure you want to delete this role?")) {
        // Add your delete logic here
    }
}




function createNewRecord() {
    var htmlsection = "";
    htmlsection += '<form class="ui form form_section" id="main_submit_form">';
    htmlsection += '  <div id="step_zero">';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>First Name <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="firstName" name="firstName" placeholder="First Name">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Last Name<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="lastName" name="lastName" placeholder="Last Name">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Other Name<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="30" id="otherNames" name="otherNames" placeholder="Other Name">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Email <span class="asteric">*</span></label>';
    htmlsection += '        <input type="email" maxlength="30" id="email" name="email" placeholder="Email">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Username<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="username" name="username" placeholder="Username">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Password<span class="asteric">*</span></label>';
    htmlsection += '        <input type="password" maxlength="30" id="password" name="password" placeholder="eg abc123">';
    htmlsection += '   <i class="fa fa-eye" onclick="viewPass()" id="togglePassword"></i>';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Phone Number<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="13" id="phoneNo" name="phoneNo" placeholder="Phone No eg +254722000000">';
    htmlsection += ' <p id="validationMessage"></p>';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>National ID No <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="nationalIDNo" name="nationalIDNo" placeholder="National ID No">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '<div class="field">';
    htmlsection += '    <label>Roles</label>';
    htmlsection += '    <select id="roleName" name="roleName" class="ui search dropdown">';
    htmlsection += '<option selected value="">-Select Option-</option>';
    htmlsection += '    </select>';
    htmlsection += '</div>';
    htmlsection += '</div>';

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

    htmlsection += '</form>';
    $(".crud_section").html(htmlsection);
    $('.ui.dropdown').dropdown({
        fullTextSearch: true
    });

   
    


    var option_role = "";
    var url_pp = serverURL + 'roles/roleList?pageNo=0&pageSize=100';
    controller.getAuthRequest(url_pp, true, function(data, status) {
        option_role += "<option selected value=''>-Select Option-</option>";

        option_role += controller.loadSelect(data, 'name', 'name', '');
        $('#roleName').html(option_role);
    });

   

}











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

     if (!Array.isArray(formJson.roleName)) {
        if (!formJson.roleName) {
            formJson.roleName = [];
        } else {
            formJson.roleName = [formJson.roleName];
        }
    }
    if (formJson.firstName == "") {
        controller.showToastMsg("First Name Required", "#ff6666");
    } else if (formJson.lastName == "") {
        controller.showToastMsg("Last Name Required", "#ff6666");
    } else if (formJson.otherNames == "") {
        controller.showToastMsg("Other Name Required", "#ff6666");
    } else if (formJson.email == "") {
        controller.showToastMsg("Email Required", "#ff6666");
    } else if (formJson.username == "") {
        controller.showToastMsg("Username Required", "#ff6666");
    } else if (formJson.password == "") {
        controller.showToastMsg("Password Required", "#ff6666");
    } else if (formJson.phoneNo == "") {
        controller.showToastMsg("Phone Number Required", "#ff6666");
    } else if (formJson.nationalIDNo == "") {
        controller.showToastMsg("National ID No Number Required", "#ff6666");
    } else {
        setTimeout(function() {
            $('#nexttostepone').html("Saving & Exit");
            $("#nexttostepone").attr("disabled", false);
        }, 1000);

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

}




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

     if (!Array.isArray(formJson.roleName)) {
        if (!formJson.roleName) {
            formJson.roleName = [];
        } else {
            formJson.roleName = [formJson.roleName];
        }
    }
    if (formJson.firstName == "") {
        controller.showToastMsg("First Name Required", "#ff6666");
    } else if (formJson.lastName == "") {
        controller.showToastMsg("Last Name Required", "#ff6666");
    } else if (formJson.otherNames == "") {
        controller.showToastMsg("Other Name Required", "#ff6666");
    } else if (formJson.email == "") {
        controller.showToastMsg("Email Required", "#ff6666");
    } else if (formJson.username == "") {
        controller.showToastMsg("Username Required", "#ff6666");
    } else if (formJson.password == "") {
        controller.showToastMsg("Password Required", "#ff6666");
    } else if (formJson.phoneNo == "") {
        controller.showToastMsg("Phone Number Required", "#ff6666");
    } else if (formJson.nationalIDNo == "") {
        controller.showToastMsg("National ID No Number Required", "#ff6666");
    }else {
        setTimeout(function() {
            $('#nexttostepone').html("Saving & Exit");
            $("#nexttostepone").attr("disabled", false);
        }, 1000);


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




}


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