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() {

    let html = '';
    html += '<div class="ibox-head">';
    html += '<h3 class="ibox-title" style="font-weight:800;">Cargo Dispatch</h3>';
    html += '</div>';

    html += '<div class="ibox-body">';
    html += `<table class="table table-striped table-bordered" id="dispatchTable">
        <thead>
            <tr>
                <th>#</th>
                <th>Dispatch Type</th>
                <th>Vehicle</th>
                <th>Device ID</th>
                <th>Route Name</th>
                <th>ETD</th>
                <th>ETA</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>`;
    html += '</div>';

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

    $.ajax({
        url: serverURL + "dispatch/list",
        type: "GET",
        headers: {
            Authorization: "Bearer " + userObj.accessToken
        },
        success: function (data) {

            let rows = '';
            data.forEach((item, i) => {
                rows += `
                    <tr>
                        <td>${i + 1}</td>
                        <td>${item.dispatchType}</td>
                        <td>${item.vehicle}</td>
                        <td>${item.deviceId}</td>
                        <td>${item.routeName}</td>
                        <td>${item.etd}</td>
                        <td>${item.eta}</td>
                        <td>
                            <button class="btn btn-sm btn-primary"
                                onclick="editRowData('${encodeURIComponent(JSON.stringify(item))}')">Edit</button>
                        </td>
                    </tr>`;
            });

            $("#dispatchTable tbody").html(rows);
            $('#dispatchTable').DataTable();
        }
    });
}


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(data = {}) {

    let html = '';
    html += `<form class="ui form form_section" id="main_submit_form">

    <div class="three fields">
        <div class="field">
            <label>Dispatch Type *</label>
            <select name="dispatchType" class="ui dropdown">
                <option value="Regular Dispatch">Regular Dispatch</option>
            </select>
        </div>

        <div class="field">
            <label>Vehicle *</label>
            <input type="text" name="vehicle" value="${data.vehicle || ''}">
        </div>

        <div class="field">
            <label>Device ID *</label>
            <input type="text" name="deviceId" value="${data.deviceId || ''}">
        </div>
    </div>

    <div class="three fields">
        <div class="field">
            <label>Container</label>
            <input type="text" name="container" value="${data.container || ''}">
        </div>

        <div class="field">
            <label>Declaration No.</label>
            <input type="text" name="declarationNo" value="${data.declarationNo || ''}">
        </div>

        <div class="field">
            <label>Consignee</label>
            <input type="text" name="consignee" value="${data.consignee || ''}">
        </div>
    </div>

    <div class="three fields">
        <div class="field">
            <label>Route Name *</label>
            <input type="text" name="routeName" value="${data.routeName || ''}">
        </div>

        <div class="field">
            <label>Route Code</label>
            <input type="text" name="routeCode" value="${data.routeCode || ''}">
        </div>

        <div class="field">
            <label>Binding Driver</label>
            <input type="text" name="bindingDriver" value="${data.bindingDriver || ''}">
        </div>
    </div>

    <div class="three fields">
        <div class="field">
            <label>Driver Tel</label>
            <input type="text" name="driverTel" value="${data.driverTel || ''}">
        </div>

        <div class="field">
            <label>ETD *</label>
            <input type="datetime-local" name="etd" value="${data.etd || ''}">
        </div>

        <div class="field">
            <label>ETA *</label>
            <input type="datetime-local" name="eta" value="${data.eta || ''}">
        </div>
    </div>

    <div class="three fields">
        <div class="field">
            <label>Agency</label>
            <input type="text" name="agency" value="${data.agency || ''}">
        </div>

        <div class="field">
            <label>Asset Type</label>
            <select name="assetType" class="ui dropdown">
                <option value="Truck">Truck</option>
                <option value="Van">Van</option>
                <option value="Container">Container</option>
                <option value="Trailer">Trailer</option>

            </select>
        </div>

        <div class="field">
            <label>Completion Rules</label>
            <select name="completionRules" class="ui dropdown">
                <option value="Complete(Leave destination)">Complete (Leave destination)</option>
            </select>
        </div>
    </div>

    <div class="field">
        <label>Goods Description</label>
        <textarea name="goodsDescription">${data.goodsDescription || ''}</textarea>
    </div>

    <div style="margin-top:15px;">
        <button type="button" onclick="saveDispatch()" class="ui green button">
            Confirm
        </button>
        <button type="button" onclick="loadData()" class="ui button">
            Reset
        </button>
    </div>

    </form>`;

    $(".crud_section").html(html);
    $('.ui.dropdown').dropdown();
}


function saveDispatch() {
    let formJson = $("#main_submit_form").serializeObject();

    if (!formJson.vehicle || !formJson.deviceId || !formJson.routeName) {
        controller.showToastMsg("Please fill all required fields", "#ff6666");
        return;
    }

    let url = serverURL + "dispatch/create";

    controller.allPostRequest(url, formJson, '', function () {
        loadData();
    });
}










// 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();
}