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 += '<button class="upload_btn ui button btn btn-warning" style="background: #E2852E !important; color: white;" onclick="loadData();">View Devices List</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() {
    stopTracking(); // Stop any ongoing tracking sessions
    // 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 + "devices/all";
    // var url = serverURL + "devices?page=0&size=100&sort=deviceId,asc";

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
            "Content-Type": "application/json",
        },
        async: true,
   success: function(res) {

    var data = res;
    console.log("devices:", data);

    var html = "";

    html += `
        <div class="ibox-head">
            <h3 class="ibox-title" style="color:black; font-weight:800; padding:8px;">Assets</h3>
        </div>

        <div id="devices"></div>

        <div class="ibox-body">
            <table class="table table-striped table-bordered table-hover" id="devicetableview" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th style="width:5%; text-align:center;"><input type="checkbox" id="selectAll"></th>
                        <th style="width:5%; text-align:center;">#</th>
                        <th>Name</th>
                        <th>Serial No</th>
                        <th>Make</th>
                        <th>Model</th>
                        <th>Type</th>
                        <th>Manufacturer</th>
                        <th>IMEI</th>
                        <th>SIM 1</th>
                        <th>SIM 2</th>
                        <th>Warranty No</th>
                         <th>Status</th>
                        <th>Warranty Months</th>
                        <th>Firmware</th>
                        <th>Notes</th>
                        <th style="width:10%; text-align:center">Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;

    data.forEach((item, i) => {

        var isOnline = item.isOnline ? 'Online' : 'Offline';
        html += `
            <tr>
                <td style="text-align:center;">
                    <input type="checkbox" class="row-checkbox" data-id="${item.deviceId}">
                </td>

                <td style="text-align:center;">${i + 1}</td>

                <td>${item.name ?? ''}</td>
                <td>${item.serialNo ?? ''}</td>
                <td>${item.make ?? ''}</td>
                <td>${item.model ?? ''}</td>
                <td>${item.type ?? ''}</td>
                <td>${item.manufacturer ?? ''}</td>
                <td>${item.imei ?? ''}</td>
                <td>${item.sim1Number ?? ''}</td>
                <td>${item.sim2Number ?? ''}</td>
                <td>${item.warrantyNumber ?? ''}</td>
                 <td>${isOnline ?? ''}</td>
                <td>${item.warrantyPeriodMonths ?? ''}</td>
                <td>${item.firmwareVersion ?? ''}</td>
                <td>${item.notes ?? ''}</td>

                <td class="time" style="text-align:center;">
                    <div class="dropdown">
                        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" style="font-size:14px;">
                            Actions
                        </button>
                        <div class="dropdown-menu">
                                <a class="dropdown-item view-action" href="javascript:viewRowData('${encodeURIComponent(JSON.stringify(item))}')"data-id="${item.deviceId}">
                                    View
                                </a>

                                   <a class="dropdown-item edit-action" 
                            href="javascript:editRowData('${encodeURIComponent(JSON.stringify(item))}')"
                               data-id="${item.deviceId}">
                                Edit
                            </a>

                            <a class="dropdown-item delete-action" href="#" data-id="${item.deviceId}">
                                Deactivate
                            </a>


                                 <a class="dropdown-item" 
                                 href="javascript:checkshistorydevice(${item.serialNo})" >
                                Status & History
                                </a>

                                  <a class="dropdown-item" 
                                 href="javascript:checkstatusdevice(${item.serialNo})" >
                                Check Status
                                </a>

                                 <a class="dropdown-item" 
                                 href="javascript:createSetdevice(${item.serialNo})" >
                                Set IP/Domain
                                </a>

                                 <a class="dropdown-item" 
                                 href="javascript:checkdevicelogs(${item.serialNo})" >
                                 Device Logs
                                </a>


                                 <a class="dropdown-item" 
                                 href="javascript:vehiclealrmlist(${item.serialNo})" >
                                 View Alarm
                                </a>
                             

                                 <a class="dropdown-item" 
                                 href="javascript:unlockdevice(${item.serialNo})" >
                                Unlock
                                </a>

                               

                                 <a class="dropdown-item" 
                                 href="javascript:createAssign(${item.deviceId})" >
                                Assign Vehicle
                                </a>

                                 <a class="dropdown-item" 
                                 href="javascript:createAssign(${item.deviceId})" >
                                Geofence
                                </a>


                                


                               <a class="dropdown-item" 
                                 href="javascript:unassigndevicevicel(${item.deviceId})" >
                                Unassign
                                </a>
                                

                         
                                 <a class="dropdown-item view-action" href="javascript:trackRowData(${item.serialNo}) "data-id="${item.deviceId}">
                                    Track Cargo
                                </a>

                        </div>
                    </div>
                </td>
            </tr>
        `;
    });

    html += `
                </tbody>
            </table>
        </div>
    `;

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

    // Initialize DataTable
    $('#devicetableview').DataTable({
        dom: "Bfrltip",
        aLengthMenu: [
            [5, 10, 20, 25, 50, 75, -1],
            [5, 10, 20, 25, 50, 75, "All"]
        ],
        iDisplayLength: 5,
        responsive: true,
        autoWidth: false
    });

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

   

}



    });
}




function vehiclealrmlist(serialNo){
  $(".modal.fade.createralarmview").modal("show");
 var url = serverURL + 'alarms?deviceSn='+serialNo+"&page=0&size=10&&sort=id,asc";
    controller.getAuthRequest(url, true, function(res, status) {

        console.log("data", res.content)
        if(res.content){
            var data = res.content;

           var html_v = "";

            var tableHTML = $(".vehicleInsurancelist");
            html_v += '<div class="ibox-body">';
            html_v += "<table class='table table-striped table-bordered table-hover' id='vehiclepermitslisttbl' cellspacing='0' width='100%'>";
            html_v += '<thead><tr>';
            html_v += '  <th>Alarm Type</th>';
            html_v += '  <th>Status HX</th>';
            html_v += '  <th>Source Ip</th>';
            html_v += '  <th>Speed Kmh</th>';
            html_v += '</tr></thead>';
            html_v += '<tbody>';

            data.forEach((item, i) => {

                html_v += `<tr>

                    <td>
                        <a>
                            <p style="color: #1581BF !important" >${item.alarmType}</p>
                        </a>
                    </td>

                    <td style="width:200px; text-align:left;">${item.alarmStatusHex}</td>

                    <td style="width:200px; text-align:left;">${item.sourceIp}</td>

                    <td>${item.speedKmh}</td>

                   
                </tr>`;
            });

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

            // Initialize DataTable
            $('#vehiclepermitslisttbl').DataTable({
                dom: "Bfrltip",
                bJQueryUI: true,
                aLengthMenu: [
                    [5, 10, 20, 25, 50, 75, -1],
                    [5, 10, 20, 25, 50, 75, "All"]
                ],
                iDisplayLength: 5,
                scroller: { loadingIndicator: true },
                orderCellsTop: true,
                fixedHeader: true,
                bProcessing: true,
                mark: true,
                responsive: true,
                autoWidth: true,
            });

            
        }
       
        
    });
}












function createAssign(deviceId) {
    localStorage.setItem("deviceId", deviceId)
    $(".modal.fade.createmodalform").modal("show");
      var htmlsections   = `<form class="ui form">
                                     <div class="two fields">
                                        <div class="field">
                                            <label>Vehicle</label>
                                            <select  class="ui fluid dropdown search" name="vehicleId" id="vehicleId">';
                                                <option selected value="">-Select Option-</option>';
                                            </select>';                                           
                                         </div>
                                        </div>
     
                            <button type="button" class="btn btn-success createAssignbtn" id="createAssignbtn" style="width: 200px; margin-top: 20px;">
                             Confirm
                            </button>
                            </form>`;

    $(".modalformection").html(htmlsections);

 var option_role = "";
    var url_pp = serverURL + 'vehicles?page=0&size=100&sort=vehicleId,asc';
    controller.getAuthRequest(url_pp, true, function(data, status) {
        option_role += "<option selected value=''>-Select Option-</option>";
        var resdata = data.content;

        option_role += controller.loadSelect(resdata, 'vehicleId', 'plateNumber', '');
        $('#vehicleId').html(option_role);
    });
   

    // Remove previous click handlers to prevent multiple submissions
    $("#createAssignbtn").off("click").on("click", function(event) {
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();

        // Get form values
        var vehicleId = $("#vehicleId").val();
       

        var url = serverURL + "devices/"+deviceId+"/assign/"+vehicleId;

        controller.allPutRequest(url, '', '', function(data, status) {
            if (data) {
                $(".modal.fade.createmodalform").modal("hide");
            }
        });
    });
}

function createSetdevice(serialNo) {

    // Show the modal
    $(".modal.fade.createmodalform").modal("show");


    var htmlsections   = `<form class="ui form">

                                     <div class="two fields">

                                          

                                            <div class="field">
                                            <label>IP/Domain</label>
                                            <input type="text" max-length="60" name="ip" id="ip" placeholder="Enter Ip/Domain eg bsl.co.ke">
                                            </div>

                                                                                        <div class="field">
                                            <label>Port</label>
                                            <input type="text" name="port" id="port" placeholder="Port eg 8080">
                                            </div>
                                        </div>
     
                            <button type="button" class="btn btn-success createbtn" id="createAssignbtncon" style="width: 200px; margin-top: 20px;">
                             Confirm
                            </button>
                            </form>`;

    $(".modalformection").html(htmlsections);


    // Remove previous click handlers to prevent multiple submissions
    $("#createAssignbtncon").off("click").on("click", function(event) {
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();

        // Get form values
        // var command = $("#command").val();
        var ip = $("#ip").val();
        var port = $("#port").val();

        var command =  "*269#1,"+ip+","+port+",1";
        //"269#1,4.tcp.eu.ngrok.io,12231,1"

        var formJson = {
            "deviceSn": serialNo,
            "command": command
            }

        var url = serverURL + "devices/command/set";

        controller.allPostRequestDevice(url, formJson, '', function(data, status) {
            if(data.resultCode==0){
                controller.showToastMsg("IP/Domain Set Successfully", "#1a5589");
            }else{
                controller.showToastMsg("Failed setting ip/domain to device", "#ff6666");

            }
        });

        // controller.allPostRequest(url, formJson, '', function(data, status) {
        //     if (data) {
        //         $(".modal.fade.createmodalform").modal("hide");
        //     }
        // });
    });
}


function checkstatusdevice(serialNo) {


    var url = serverURL + "device-status/"+serialNo+"/current";
                $(".modal.fade.createmodalform").modal("show");

        controller.getAuthRequest(url, true, function(data, status) {

                                        var item = data;

            let htmlsectionsect = `
                <div class="ibox-body">
                    <table class="table table-bordered">
                        <tbody>

                            <tr><th>Device ID</th><td>${item.deviceId ?? ''}</td></tr>
                            <tr><th>IP 1 Address</th><td>${item.ip1Address ?? ''}</td></tr>
                            <tr><th>IP 1 Port</th><td>${item.ip1Port ?? ''}</td></tr>
                            <tr><th>IP 1 Mode</th><td>${item.ip1Mode ?? ''}</td></tr>

                            <tr><th>IP 2 Address</th><td>${item.ip2Address ?? ''}</td></tr>
                            <tr><th>IP 2 Port</th><td>${item.ip2Port ?? ''}</td></tr>
                            <tr><th>IP 2 Mode</th><td>${item.ip2Mode ?? ''}</td></tr>

                            <tr><th>CGR</th><td>${item.cgr ?? ''}</td></tr>
                            <tr><th>CGR Ext</th><td>${item.cgrExt ?? ''}</td></tr>
                            <tr><th>CSQ</th><td>${item.csq ?? ''}</td></tr>
                            <tr><th>CSQ Ext</th><td>${item.csqExt ?? ''}</td></tr>

                            <tr><th>GPS Status</th><td>${item.gpsStatus ?? ''}</td></tr>
                            <tr><th>Satellites</th><td>${item.satellites ?? ''}</td></tr>
                            <tr><th>Battery</th><td>${item.battery ?? ''}</td></tr>

                            <tr><th>N1</th><td>${item.n1 ?? ''}</td></tr>
                            <tr><th>N2</th><td>${item.n2 ?? ''}</td></tr>
                            <tr><th>N3</th><td>${item.n3 ?? ''}</td></tr>
                            <tr><th>N4</th><td>${item.n4 ?? ''}</td></tr>
                            <tr><th>N5</th><td>${item.n5 ?? ''}</td></tr>

                            <tr><th>Z Offset</th><td>${item.zOffset ?? ''}</td></tr>
                            <tr><th>Modem Mode</th><td>${item.modemMode ?? ''}</td></tr>

                            <tr><th>Mode 0</th><td>${item.mode0 ?? ''}</td></tr>
                            <tr><th>Mode 1</th><td>${item.mode1 ?? ''}</td></tr>
                            <tr><th>Mode 2</th><td>${item.mode2 ?? ''}</td></tr>

                            <tr><th>Firmware</th><td>${item.firmware ?? ''}</td></tr>

                        </tbody>
                    </table>

                    <a href="javascript:loadData()" class="btn btn-warning">Return</a>
                </div>
            `;

                $(".modalformection").html(htmlsectionsect);

           
        });
}

function checkshistorydevice(serialNo) {

    $(".modal.fade.createmodalform").modal("show");

    var url = serverURL + "device-status/"+serialNo+"/history?startDate=2025-11-26T15:12:07&endDate=2099-11-26T15:12:07&page=0&size=1000&sort=id,asc";

        controller.getAuthRequest(url, true, function(data, status) {

            var item = data;

            console.log("history data:", item);

            let htmlsectionsect = `
                <div class="ibox-body">
                    <table class="table table-bordered">
                        <tbody>

                            <tr><th>Device ID</th><td>${item.deviceId ?? ''}</td></tr>
                            <tr><th>IP 1 Address</th><td>${item.ip1Address ?? ''}</td></tr>
                            <tr><th>IP 1 Port</th><td>${item.ip1Port ?? ''}</td></tr>
                            <tr><th>IP 1 Mode</th><td>${item.ip1Mode ?? ''}</td></tr>

                            <tr><th>IP 2 Address</th><td>${item.ip2Address ?? ''}</td></tr>
                            <tr><th>IP 2 Port</th><td>${item.ip2Port ?? ''}</td></tr>
                            <tr><th>IP 2 Mode</th><td>${item.ip2Mode ?? ''}</td></tr>

                            <tr><th>CGR</th><td>${item.cgr ?? ''}</td></tr>
                            <tr><th>CGR Ext</th><td>${item.cgrExt ?? ''}</td></tr>
                            <tr><th>CSQ</th><td>${item.csq ?? ''}</td></tr>
                            <tr><th>CSQ Ext</th><td>${item.csqExt ?? ''}</td></tr>

                            <tr><th>GPS Status</th><td>${item.gpsStatus ?? ''}</td></tr>
                            <tr><th>Satellites</th><td>${item.satellites ?? ''}</td></tr>
                            <tr><th>Battery</th><td>${item.battery ?? ''}</td></tr>

                            <tr><th>N1</th><td>${item.n1 ?? ''}</td></tr>
                            <tr><th>N2</th><td>${item.n2 ?? ''}</td></tr>
                            <tr><th>N3</th><td>${item.n3 ?? ''}</td></tr>
                            <tr><th>N4</th><td>${item.n4 ?? ''}</td></tr>
                            <tr><th>N5</th><td>${item.n5 ?? ''}</td></tr>

                            <tr><th>Z Offset</th><td>${item.zOffset ?? ''}</td></tr>
                            <tr><th>Modem Mode</th><td>${item.modemMode ?? ''}</td></tr>

                            <tr><th>Mode 0</th><td>${item.mode0 ?? ''}</td></tr>
                            <tr><th>Mode 1</th><td>${item.mode1 ?? ''}</td></tr>
                            <tr><th>Mode 2</th><td>${item.mode2 ?? ''}</td></tr>

                            <tr><th>Firmware</th><td>${item.firmware ?? ''}</td></tr>

                        </tbody>
                    </table>

                    <a href="javascript:loadData()" class="btn btn-warning">Return</a>
                </div>
            `;

                $(".modalformection").html(htmlsectionsect);

           
        });
}




function checkdevicelogs(serialNo) {


   var url = serverURL + "logs?deviceSn=" + serialNo + "&page=0&size=1000&sort=id,asc";

controller.getAuthRequest(url, true, function(data, status) {

    $(".modal.fade.createmodalform").modal("show");

    var logs = data.content;

    if (!logs || logs.length === 0) {
        $(".modalformection").html("<p>No logs found.</p>");
        return;
    }

    let html = `
        <div class="ibox-body">
            <table id="paginationslist" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>ID</th>
                        <th>Device SN</th>
                        <th>Device ID</th>
                        <th>Event</th>
                        <th>Type</th>
                        <th>Content</th>
                        <th>Result</th>
                        <th>Result Code</th>
                        <th>Timestamp</th>
                        <th>Source</th>
                        <th>Source IP</th>
                        <th>Correlation Key</th>
                        <th>User Name</th>
                    </tr>
                </thead>
                <tbody>
    `;

    logs.forEach((item, index) => {
        html += `
            <tr>
                <td>${index + 1}</td>
                <td>${item.id ?? ''}</td>
                <td>${item.deviceSn ?? ''}</td>
                <td>${item.deviceId ?? ''}</td>
                <td>${item.event ?? ''}</td>
                <td>${item.type ?? ''}</td>
                <td>${item.content ?? ''}</td>
                <td>${item.result ?? ''}</td>
                <td>${item.resultCode ?? ''}</td>
                <td>${item.timestamp ?? ''}</td>
                <td>${item.source ?? ''}</td>
                <td>${item.sourceIp ?? ''}</td>
                <td>${item.correlationKey ?? ''}</td>
                <td>${item.userName ?? ''}</td>
            </tr>
        `;
    });

    html += `
                </tbody>
            </table>

            <a href="javascript:loadData()" class="btn btn-warning">Return</a>
        </div>
    `;

    $(".modalformection").html(html);


    $('#paginationslist').DataTable({
        dom: "Bfrltip",
        aLengthMenu: [
            [5, 10, 20, 25, 50, 75, -1],
            [5, 10, 20, 25, 50, 75, "All"]
        ],
        iDisplayLength: 10,
        responsive: true,
        autoWidth: false
    });


});

}

function unlockdevice(serialNo) {
           var formJson = {
            "deviceSn": serialNo,
            "command": "*269#8,888888"
            }
        var url = serverURL + "devices/command/set";
        controller.allPostRequestDevice(url, formJson, '', function(data, status) {
            if(data.resultCode==0){
                controller.showToastMsg("Device Successfully Unlocked", "#1a5589");
            }else{
                controller.showToastMsg("Failed uncloking device", "#ff6666");

            }
        });
}

function deviceList(){
    var html_v = "";

    var deviceId =  localStorage.getItem("deviceId")
 var url = serverURL + 'vehicles/device/'+deviceId+'?page=0&size=100&sort=vehicleId,asc';
    controller.getAuthRequest(url, true, function(res, status) {

        console.log("data", res.content)
        if(res.content){
            var data = res.content;

            html_v += '<div class="ibox-head">';
            html_v += '<h3 class="ibox-title" style="color:black; font-weight: 800; padding-bottom:4px;">Vehicles</h3>';
            html_v += '</div>';
            html_v += '<div>';
            html_v += '<div id="vehicles"></div>';
            html_v += '</div>';

            var tableHTML = $(".deviceList");
            html_v += '<div class="ibox-body">';
            html_v += "<table class='table table-striped table-bordered table-hover' id='vehiclesstableview' cellspacing='0' width='100%'>";
            html_v += '<thead><tr>';
            html_v += '  <th style="width:5%; text-align:center;"><input type="checkbox" id="selectAll"></th>';
            html_v += '  <th style="width:5%; text-align:center;">#</th>';
            html_v += '  <th>Plate Number</th>';
            html_v += '  <th>Make</th>';
            html_v += '  <th>Model</th>';
            html_v += '  <th>Type</th>';
            html_v += '  <th>Color</th>';
            html_v += '  <th>Year Of Manufacture</th>';
            html_v += '  <th>Driver</th>';
            html_v += '</tr></thead>';
            html_v += '<tbody>';

            data.forEach((item, i) => {
                var drivename= item.driver.firstName + " " + item.driver.lastName +"  Tel: "+ item.driver.phoneNo;
                html_v += `<tr>
                    <td style="text-align:center;">
                        <input type="checkbox" class="row-checkbox" data-id="${item.vehicleId}">
                    </td>

                    <td style="text-align:center;">${i + 1}</td>

                    <td>
                        <a href="javascript:viewRowData(${item.vehicleId})">
                            <p style="color: #1581BF !important" >${item.plateNumber}</p>
                        </a>
                    </td>

                    <td style="text-align:left;">${item.make}</td>

                    <td style="text-align:left;">${item.model}</td>
                    <td style=" text-align:left;">${item.type}</td>
                    <td style=" text-align:left;">${item.color}</td>
                     <td style=" text-align:left;">${item.yearOfManufacture}</td>

                    

                    <td>${drivename}</td>

                   
                </tr>`;
            });

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

            // Initialize DataTable
            $('#vehiclesstableview').DataTable({
                dom: "Bfrltip",
                bJQueryUI: true,
                aLengthMenu: [
                    [5, 10, 20, 25, 50, 75, -1],
                    [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
            $("#selectAll").on("click", function() {
                $(".row-checkbox").prop("checked", this.checked);
            });

        }
       
        

    });
}


function createInsurance(vehicleId) {
    localStorage.setItem("vehicleId", vehicleId)

    // Show the modal
    $(".modal.fade.createreInsurancecordmodal").modal("show");


   

    // Remove previous click handlers to prevent multiple submissions
    $("#createbtninsurance").off("click").on("click", function(event) {
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();

        // Get form values
        var insuranceNumber = $("#insuranceNumber").val();
        var issuer = $("#issuer").val();
        var validFrom = $("#validFrom").val();
        var validTo = $("#validTo").val();
        var description = $("#description").val();
        var type = $("#type").val();
        var amount = $("#amount").val();

        

        // Build JSON
        var formJson = {
            "insuranceNumber": insuranceNumber,
            "issuer": issuer,
            "validFrom": validFrom || "2025-11-25", // fallback if empty
            "validTo": validTo || "2025-11-25",
            "description": description,
            "vehicleId": vehicleId,
            "type": type,
            "amount": amount

        };

        var url = serverURL + "insurances";

        controller.allPostRequest(url, formJson, '', function(data, status) {
            if (data) {
                // Hide modal
                $(".modal.fade.createreInsurancecordmodal").modal("hide");

                // Clear input fields
                $("#insuranceNumber").val('');
                $("#issuer").val('');
                $("#validFrom").val('');
                $("#validTo").val('');
                $("#description").val('');
                $("#type").val('');
                $("#amount").val('');

                // Reload data
                // vehiclepermitslist();
            }
        });
    });
}

function vehicleInsurancelist(){

    var vehicleId =  localStorage.getItem("vehicleId")
 var url = serverURL + 'insurances/vehicle/'+vehicleId+'?page=0&size=10000&sort=insuranceId,asc';
    controller.getAuthRequest(url, true, function(res, status) {

        console.log("data", res.content)
        if(res.content){
            var data = res.content;

           var html_v = "";

            var tableHTML = $(".vehicleInsurancelist");
            html_v += '<div class="ibox-body">';
            html_v += "<table class='table table-striped table-bordered table-hover' id='insurancetableview' cellspacing='0' width='100%'>";
            html_v += '<thead><tr>';
            html_v += '  <th>Insurance Number</th>';
            html_v += '  <th>Valid from</th>';
            html_v += '  <th>Valid To</th>';
            html_v += '  <th>Amount</th>';
            html_v += '</tr></thead>';
            html_v += '<tbody>';

            data.forEach((item, i) => {

                html_v += `<tr>

                    <td>
                        <a>
                            <p style="color: #1581BF !important" >${item.insuranceNumber}</p>
                        </a>
                    </td>

                    <td style="width:200px; text-align:left;">${item.validFrom}</td>

                    <td style="width:200px; text-align:left;">${item.validTo}</td>

                    <td>${item.amount}</td>

                   
                </tr>`;
            });

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

            // Initialize DataTable
            $('#insurancetableview').DataTable({
                dom: "Bfrltip",
                bJQueryUI: true,
                aLengthMenu: [
                    [5, 10, 20, 25, 50, 75, -1],
                    [5, 10, 20, 25, 50, 75, "All"]
                ],
                iDisplayLength: 5,
                scroller: { loadingIndicator: true },
                orderCellsTop: true,
                fixedHeader: true,
                bProcessing: true,
                mark: true,
                responsive: true,
                autoWidth: true,
            });

            
        }
       
        
    });
}


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

    console.log("datas:", datas);
    console.log("Parsed:", data);
    console.log("Device ID:", data.deviceId);



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

    // ROW 1
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Name<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="name" name="name" value="'+(data.name || '')+'" placeholder="Device Name">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Serial Number<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="serialNo" name="serialNo" value="'+(data.serialNo || '')+'" placeholder="Serial Number">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Year of Manufacture<span class="asteric">*</span></label>';
    htmlsection += '    <input type="number" maxlength="4" id="yearOfManufacture" name="yearOfManufacture" value="'+(data.yearOfManufacture || '')+'" placeholder="Year">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 2
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Make<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="make" name="make" value="'+(data.make || '')+'" placeholder="Make">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Type<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="type" name="type" value="'+(data.type || '')+'" placeholder="Type">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Model<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="model" name="model" value="'+(data.model || '')+'" placeholder="Model">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 3
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Manufacturer</label>';
    htmlsection += '    <input type="text" maxlength="50" id="manufacturer" name="manufacturer" value="'+(data.manufacturer || '')+'" placeholder="Manufacturer">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>IMEI</label>';
    htmlsection += '    <input type="text" maxlength="30" id="imei" name="imei" value="'+(data.imei || '')+'" placeholder="IMEI">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>SIM 1 Number</label>';
    htmlsection += '    <input type="text" maxlength="15" id="sim1Number" name="sim1Number" value="'+(data.sim1Number || '')+'" placeholder="SIM 1 Number">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 4
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>SIM 2 Number</label>';
    htmlsection += '    <input type="text" maxlength="15" id="sim2Number" name="sim2Number" value="'+(data.sim2Number || '')+'" placeholder="SIM 2 Number">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Warranty Number</label>';
    htmlsection += '    <input type="text" maxlength="50" id="warrantyNumber" name="warrantyNumber" value="'+(data.warrantyNumber || '')+'" placeholder="Warranty Number">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Warranty Period (Months)</label>';
    htmlsection += '    <input type="number" maxlength="4" id="warrantyPeriodMonths" name="warrantyPeriodMonths" value="'+(data.warrantyPeriodMonths || '')+'" placeholder="Months">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 5
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Firmware Version</label>';
    htmlsection += '    <input type="text" maxlength="50" id="firmwareVersion" name="firmwareVersion" value="'+(data.firmwareVersion || '')+'" placeholder="Firmware Version">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // NOTES
    htmlsection += '<div class="field">';
    htmlsection += '  <label>Notes</label>';
    htmlsection += '  <textarea id="notes" name="notes" placeholder="Notes">'+(data.notes || '')+'</textarea>';
    htmlsection += '</div>';

    // BUTTONS
    htmlsection += '<div class="btns" style="display:flex; gap:10px; margin-top:10px;">';
    htmlsection += '  <button onclick="updateRecord('+data.deviceId+')" type="button" class="ui green right labeled icon button">Save<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></form>';

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

    // LOAD DRIVER LIST (only if driverId exists)
    // if ($('#driverId').length > 0) {
        var option_role = "";
        var url_pp = serverURL + 'users/userList?pageNo=0&pageSize=100';
        controller.getAuthRequest(url_pp, true, function(resp, status) {
            option_role += controller.loadSelect(resp, 'userId', 'firstName', '');
            $('#driverId').html(option_role);
        });
    // }
}





function unassigndevicevicel(id) {
    if (confirm("Are you sure you want to uassign this device?")) {
        var url = serverURL + "devices/"+id+"/unassign";
        controller.allPutRequest(url, '', '', function(data, status) {
            if (data) {
                loadData();
            }
        });
        // 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">';

    // ROW 1
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Name<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="name" name="name" placeholder="Device Name">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Serial Number<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="serialNo" name="serialNo" placeholder="Serial Number">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Year of Manufacture<span class="asteric">*</span></label>';
    htmlsection += '    <input type="number" maxlength="4" id="yearOfManufacture" name="yearOfManufacture" placeholder="Year">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 2
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Make<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="make" name="make" placeholder="Make">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Type<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="type" name="type" placeholder="Type">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Model<span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" maxlength="50" id="model" name="model" placeholder="Model">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 3
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Manufacturer</label>';
    htmlsection += '    <input type="text" maxlength="50" id="manufacturer" name="manufacturer" placeholder="Manufacturer">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>IMEI</label>';
    htmlsection += '    <input type="text" maxlength="30" id="imei" name="imei" placeholder="IMEI">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>SIM 1 Number</label>';
    htmlsection += '    <input type="text" maxlength="15" id="sim1Number" name="sim1Number" placeholder="SIM 1 Number">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 4
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>SIM 2 Number</label>';
    htmlsection += '    <input type="text" maxlength="15" id="sim2Number" name="sim2Number" placeholder="SIM 2 Number">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Warranty Number</label>';
    htmlsection += '    <input type="text" maxlength="50" id="warrantyNumber" name="warrantyNumber" placeholder="Warranty Number">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Warranty Period (Months)</label>';
    htmlsection += '    <input type="number" maxlength="4" id="warrantyPeriodMonths" name="warrantyPeriodMonths" placeholder="Months">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    // ROW 5
    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Firmware Version</label>';
    htmlsection += '    <input type="text" maxlength="50" id="firmwareVersion" name="firmwareVersion" placeholder="Firmware Version">';
    htmlsection += '  </div>';

  
    htmlsection += '</div>';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Notes</label>';
    htmlsection += '    <textarea id="notes" name="notes" placeholder="Notes"></textarea>';
    htmlsection += '  </div>';

    // BUTTONS
    htmlsection += '<div class="btns" style="display:flex; gap:10px; margin-top:10px;">';
    htmlsection += '  <button onclick="createRecord()" type="button" class="ui green right labeled icon button">Save<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></form>';

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

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

mapboxgl.accessToken = "pk.eyJ1IjoiaG9zZWFrb3NrZWkiLCJhIjoiY21paDdkeDRpMDA3bTNkc2FwZGd1dWxoZyJ9.Lp_Nxc6q9-ZnAN0Zr7cWZw";

var deviceMap = null;
var pathLine = null;
var lastMarker = null;
var animInterval = null; // store interval ID

var trackRowData = function(serialNo) {
    $(".crud_section").html("");

    // Clear any previous interval
    if (animInterval) {
        clearInterval(animInterval);
        animInterval = null;
    }

    var url = serverURL + "telemetry/device/" + serialNo + "?page=0&size=1000";

    controller.getAuthRequest(url, true, async function(data, status) {
        var items = data.content;

        let coordinates = items
            .filter(i => i.latitude && i.longitude)
            .map(i => [i.longitude, i.latitude]);

        if (coordinates.length === 0) {
            console.log("No GPS coordinates");
            return;
        }

        // Initialize Mapbox map
        if (!deviceMap) {
            deviceMap = new mapboxgl.Map({
                container: 'crud_section',
                style: 'mapbox://styles/mapbox/streets-v11',
                center: coordinates[0],
                zoom: 10,
                pitch: 45,
                bearing: 0,
                antialias: true
            });

            deviceMap.addControl(new mapboxgl.NavigationControl());
        }

        // Draw path
        if (pathLine) {
            if (deviceMap.getLayer('pathLine')) deviceMap.removeLayer('pathLine');
            if (deviceMap.getSource('pathLine')) deviceMap.removeSource('pathLine');
        }

        deviceMap.on('load', () => {
            if (!deviceMap.getSource('pathLine')) {
                deviceMap.addSource('pathLine', {
                    'type': 'geojson',
                    'data': {
                        'type': 'Feature',
                        'geometry': {
                            'type': 'LineString',
                            'coordinates': coordinates
                        }
                    }
                });

                deviceMap.addLayer({
                    'id': 'pathLine',
                    'type': 'line',
                    'source': 'pathLine',
                    'layout': { 'line-join': 'round', 'line-cap': 'round' },
                    'paint': { 'line-color': '#FF5733', 'line-width': 4 }
                });
            }
        });

        // Fit map bounds
        let bounds = coordinates.reduce((b, coord) => b.extend(coord), new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
        deviceMap.fitBounds(bounds, { padding: 50, maxZoom: 14 });

        // Marker
        if (!lastMarker) {
            lastMarker = new mapboxgl.Marker({
                element: (() => {
                    let el = document.createElement('div');
                    el.style.backgroundImage = 'url(https://cdn-icons-png.flaticon.com/512/1329/1329628.png)';
                    el.style.width = '40px';
                    el.style.height = '40px';
                    el.style.backgroundSize = 'cover';
                    return el;
                })()
            }).setLngLat(coordinates[0]).addTo(deviceMap);
        }

        // Animate
        let step = 0;
        animInterval = setInterval(async () => {
            if (step >= coordinates.length) { 
                clearInterval(animInterval); 
                animInterval = null;
                return; 
            }

            let [lng, lat] = coordinates[step];
            lastMarker.setLngLat([lng, lat]);

            try {
                let res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`);
                let j = await res.json();
                let address = j.display_name || "Unknown location";

                lastMarker.setPopup(new mapboxgl.Popup({ offset: 25 }).setHTML(`
                    <strong>Current Position</strong><br>
                    ${lat.toFixed(6)}, ${lng.toFixed(6)}<br>
                    <b>Device SRN: ${serialNo}  Place:</b> ${address}
                `)).togglePopup();
            } catch (err) {
                lastMarker.setPopup(new mapboxgl.Popup({ offset: 25 }).setHTML(`
                    <strong>Current Position</strong><br>
                    ${lat.toFixed(6)}, ${lng.toFixed(6)}<br>
                    <b>Device SRN: ${serialNo} Place:</b> Not found
                `)).togglePopup();
            }

            step++;
        }, 1200);
    });
};

// Call this when modal/window closes
function stopTracking() {
    if (animInterval) {
        clearInterval(animInterval);
        animInterval = null;
    }
    if (deviceMap) {
        deviceMap.remove(); // remove map and free memory
        deviceMap = null;
        pathLine = null;
        lastMarker = null;
    }
}



// var deviceMap = null;
// var pathLine = null;
// var lastMarker = null;

// var trackRowData = function(serialNo) {
//     $(".crud_section").html("");

//     var url = serverURL + "telemetry/device/" + serialNo + "?page=0&size=100";

//     controller.getAuthRequest(url, true, function(data, status) {

//         var items = data.content;

//         // Extract coordinates
//         let coordinates = items
//             .filter(i => i.latitude && i.longitude)
//             .map(i => [i.latitude, i.longitude]);


//         if (coordinates.length === 0) {
//             console.log("No GPS coordinates");
//             return;
//         }

//         // Initialize map once
//         if (!deviceMap) {
//             deviceMap = L.map('crud_section').setView(coordinates[0], 14);

//             L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
//                 maxZoom: 12
//             }).addTo(deviceMap);
//         }

//         // Draw path
//         if (pathLine) deviceMap.removeLayer(pathLine);
//         pathLine = L.polyline(coordinates, { color: "blue", weight: 4 }).addTo(deviceMap);
//         deviceMap.fitBounds(pathLine.getBounds());

//         // Create marker once
//         if (!lastMarker) {
//             lastMarker = L.marker(coordinates[0], {
//                 icon: L.icon({
//                     iconUrl: 'https://cdn-icons-png.flaticon.com/512/1329/1329628.png',
//                     iconSize: [40, 40],
//                     iconAnchor: [20, 20]
//                 })
//             }).addTo(deviceMap);
//         }

//         // Animate movement
//         let step = 0;
//         let animInterval = setInterval(() => {
//             if (step >= coordinates.length) {
//                 clearInterval(animInterval);
//                 return;
//             }

//             let lat = coordinates[step][0];
//             let lng = coordinates[step][1];

//             lastMarker.setLatLng([lat, lng]);

//             // Reverse geocode for human-readable location
//             fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`)
//                 .then(res => res.json())
//                 .then(res => {
//                     let address = res.display_name || "Unknown location";

//                     lastMarker.bindPopup(`
//                         <strong>Current Position</strong><br>
//                         ${lat.toFixed(6)}, ${lng.toFixed(6)}<br>
//                         <b>Place:</b> ${address}
//                     `).openPopup();
//                 })
//                 .catch(() => {
//                     lastMarker.bindPopup(`
//                         <strong>Current Position</strong><br>
//                         ${lat.toFixed(6)}, ${lng.toFixed(6)}<br>
//                         <b>Place:</b> Not found
//                     `).openPopup();
//                 });

//             step++;
//         }, 1200); // moves every 1.2s
//     });
// };







    //var item = JSON.parse(decodeURIComponent(data));




function viewRowData(data) {

    var item = JSON.parse(decodeURIComponent(data));

    let tableRows = `
        <tr>
            <th>Name</th><td>${item.name ?? ''}</td>
            <th>Serial No</th><td>${item.serialNo ?? ''}</td>
        </tr>

        <tr>
            <th>Make</th><td>${item.make ?? ''}</td>
            <th>Model</th><td>${item.model ?? ''}</td>
        </tr>

        <tr>
            <th>Type</th><td>${item.type ?? ''}</td>
            <th>Manufacturer</th><td>${item.manufacturer ?? ''}</td>
        </tr>

        <tr>
            <th>IMEI</th><td>${item.imei ?? ''}</td>
            <th>SIM 1</th><td>${item.sim1Number ?? ''}</td>
        </tr>

        <tr>
            <th>SIM 2</th><td>${item.sim2Number ?? ''}</td>
            <th>Warranty No</th><td>${item.warrantyNumber ?? ''}</td>
        </tr>

        <tr>
            <th>Warranty Months</th><td>${item.warrantyPeriodMonths ?? ''}</td>
            <th>Firmware Version</th><td>${item.firmwareVersion ?? ''}</td>
        </tr>

        <tr>
            <th>Notes</th><td colspan="3">${item.notes ?? ''}</td>
        </tr>
    `;

    let html = `
        <div class="ibox-head">
            <h3 class="ibox-title" style="color:black; font-weight:800;">Device Details</h3>
        </div>

        <div class="ibox-body">
            <table class="table table-bordered table-striped">
                <tbody>
                    ${tableRows}
                </tbody>
            </table>

            <a href="javascript:loadData()" class="btn btn-warning">Return</a>
        </div>
    `;

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





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

    // --- Required Validation for All Fields ---
    if (!formJson.name) {
        controller.showToastMsg("Name Required", "#ff6666");

    } else if (!formJson.serialNo) {
        controller.showToastMsg("Serial Number Required", "#ff6666");

    } else if (!formJson.yearOfManufacture) {
        controller.showToastMsg("Year of Manufacture Required", "#ff6666");

    } else if (!formJson.make) {
        controller.showToastMsg("Make Required", "#ff6666");

    } else if (!formJson.type) {
        controller.showToastMsg("Type Required", "#ff6666");

    } else if (!formJson.model) {
        controller.showToastMsg("Model Required", "#ff6666");

    } else if (!formJson.manufacturer) {
        controller.showToastMsg("Manufacturer Required", "#ff6666");

    } else if (!formJson.imei) {
        controller.showToastMsg("IMEI Required", "#ff6666");

    } else if (!formJson.sim1Number) {
        controller.showToastMsg("SIM 1 Number Required", "#ff6666");

    } else if (!formJson.sim2Number) {
        controller.showToastMsg("SIM 2 Number Required", "#ff6666");

    } else if (!formJson.warrantyNumber) {
        controller.showToastMsg("Warranty Number Required", "#ff6666");

    } else if (!formJson.warrantyPeriodMonths) {
        controller.showToastMsg("Warranty Period (Months) Required", "#ff6666");

    } else if (!formJson.firmwareVersion) {
        controller.showToastMsg("Firmware Version Required", "#ff6666");

    } else if (!formJson.notes) {
        controller.showToastMsg("Notes Required", "#ff6666");

    } else {
        // --- PASSED VALIDATION ---
        setTimeout(function() {
            $('#nexttostepone').html("Saving & Exit");
            $("#nexttostepone").attr("disabled", false);
        }, 1000);

        $('#nexttostepone').html("Saving... Please Wait!");
        $("#nexttostepone").attr("disabled", true);

        var url = serverURL + "devices";

        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 (!formJson.name) {
        controller.showToastMsg("Name Required", "#ff6666");

    } else if (!formJson.serialNo) {
        controller.showToastMsg("Serial Number Required", "#ff6666");

    } else if (!formJson.yearOfManufacture) {
        controller.showToastMsg("Year of Manufacture Required", "#ff6666");

    } else if (!formJson.make) {
        controller.showToastMsg("Make Required", "#ff6666");

    } else if (!formJson.type) {
        controller.showToastMsg("Type Required", "#ff6666");

    } else if (!formJson.model) {
        controller.showToastMsg("Model Required", "#ff6666");

    } else if (!formJson.manufacturer) {
        controller.showToastMsg("Manufacturer Required", "#ff6666");

    } else if (!formJson.imei) {
        controller.showToastMsg("IMEI Required", "#ff6666");

    } else if (!formJson.sim1Number) {
        controller.showToastMsg("SIM 1 Number Required", "#ff6666");

    } else if (!formJson.sim2Number) {
        controller.showToastMsg("SIM 2 Number Required", "#ff6666");

    } else if (!formJson.warrantyNumber) {
        controller.showToastMsg("Warranty Number Required", "#ff6666");

    } else if (!formJson.warrantyPeriodMonths) {
        controller.showToastMsg("Warranty Period (Months) Required", "#ff6666");

    } else if (!formJson.firmwareVersion) {
        controller.showToastMsg("Firmware Version Required", "#ff6666");

    } else if (!formJson.notes) {
        controller.showToastMsg("Notes Required", "#ff6666");

    } else {
        setTimeout(function() {
            $('#nexttostepone').html("Saving & Exit");
            $("#nexttostepone").attr("disabled", false);
        }, 1000);


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




}


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