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 + "vehicles?page=0&size=100&sort=vehicleId,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.content;
            console.log("vehicles:", data);

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

            var tableHTML = $(".crud_section");
            html += '<div class="ibox-body">';
            html += "<table class='table table-striped table-bordered table-hover' id='vehicletableview' 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>Plate Number</th>';
            html += '  <th>Make</th>';
            html += '  <th>Model</th>';
            html += '  <th>Type</th>';
            html += '  <th>Color</th>';
            html += '  <th>Year Of Manufacture</th>';
            html += '  <th>Driver</th>';
            html += '  <th style="width:10%; text-align:center">Actions</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            data.forEach((item, i) => {
                var drivename= item.driver.firstName + " " + item.driver.lastName +"  Tel: "+ item.driver.phoneNo;
                html += `<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('${encodeURIComponent(JSON.stringify(item))}')">
                            <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>

                    <td class="time" style="width:15%; text-align:center">
                        <div class="dropdown">
                            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" style="font-size: 14px !important">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" 
                                 href="javascript:createpermits(${item.vehicleId})" >
                                Permits
                                </a>


                                 <a class="dropdown-item" 
                                 href="javascript:createInsurance(${item.vehicleId})" >
                                Insurance
                                </a>
                                

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

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

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

            // Initialize DataTable
            $('#vehicletableview').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 editRowData(res) {
    var data = JSON.parse(decodeURIComponent(res));

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

    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Plate Number <span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" id="plateNumber" name="plateNumber" value="'+data.plateNumber+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Make <span class="asteric">*</span></label>';
    htmlsection += '    <input type="text" id="make" name="make" value="'+data.make+'">';
    htmlsection += '  </div>';

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

    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Model</label>';
    htmlsection += '    <input type="text" id="model" name="model" value="'+data.model+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Color</label>';
    htmlsection += '    <input type="text" id="color" name="color" value="'+data.color+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Engine Number</label>';
    htmlsection += '    <input type="text" id="engineNumber" name="engineNumber" value="'+data.engineNumber+'">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Chassis Number</label>';
    htmlsection += '    <input type="text" id="chassisNumber" name="chassisNumber" value="'+data.chassisNumber+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Mileage (Km)</label>';
    htmlsection += '    <input type="number" id="mileageKm" name="mileageKm" value="'+data.mileageKm+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Year of Manufacture</label>';
    htmlsection += '    <input type="number" id="yearOfManufacture" name="yearOfManufacture" value="'+data.yearOfManufacture+'">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Tare Weight (Kg)</label>';
    htmlsection += '    <input type="number" id="tareWeightKg" name="tareWeightKg" value="'+data.tareWeightKg+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Gross Weight (Kg)</label>';
    htmlsection += '    <input type="number" id="grossWeightKg" name="grossWeightKg" value="'+data.grossWeightKg+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Speed Limit (Kmh)</label>';
    htmlsection += '    <input type="number" id="speedLimitKmh" name="speedLimitKmh" value="'+data.speedLimitKmh+'">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

    htmlsection += '<div class="three fields">';
    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Fuel Capacity (Litres)</label>';
    htmlsection += '    <input type="number" id="fuelCapacityLitres" name="fuelCapacityLitres" value="'+data.fuelCapacityLitres+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Engine Size (CC)</label>';
    htmlsection += '    <input type="number" id="engineSizeCc" name="engineSizeCc" value="'+data.engineSizeCc+'">';
    htmlsection += '  </div>';

    htmlsection += '  <div class="field">';
    htmlsection += '    <label>Fuel Type</label>';
    htmlsection += '    <input type="text" id="fuelType" name="fuelType" value="'+data.fuelType+'">';
    htmlsection += '  </div>';
    htmlsection += '</div>';

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

    htmlsection += '<div class="btns" style="display:flex; gap:10px; margin-top:10px;">';
    htmlsection += '  <button onclick="updateRecordsData('+data.vehicleId+')" 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></form>';

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

    // Load drivers
    var option_role = "";
    var url_pp = serverURL + 'users/userList?pageNo=0&pageSize=100';
    controller.getAuthRequest(url_pp, true, function(data, status) {
        option_role += controller.loadSelect(data, 'userId', 'firstName', '');
        $('#driverId').html(option_role);
    });
}





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>Plate Number<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="plateNumber" name="plateNumber" placeholder="Plate Number">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Make<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" 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="30" id="type" name="type" placeholder="type">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Model <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="30" id="model" name="model" placeholder="model">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Color<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="30" id="color" name="color" placeholder="Color">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Engine Number<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="30" id="engineNumber" name="engineNumber" placeholder="engineNumber">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Chassis Number<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="13" id="chassisNumber" name="chassisNumber" placeholder="chassisNumber">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Mileage (Km) <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="mileageKm" name="mileageKm" placeholder="mileage Km">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Year Of Manufacture <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="yearOfManufacture" name="yearOfManufacture" placeholder="year Of Manufacture">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Tatal Weight Kg<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="13" id="tareWeightKg" name="tareWeightKg" placeholder="tareWeightKg">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Gross Weight <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="grossWeightKg" name="grossWeightKg" placeholder="grossWeightKg">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Speed Limit Kmh <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="speedLimitKmh" name="speedLimitKmh" placeholder="speed Limit Kmh">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Fuel Capacity Litres Kg<span class="asteric">*</span></label>';
    htmlsection += '        <input type="text"  maxlength="13" id="fuelCapacityLitres" name="fuelCapacityLitres" placeholder="fuelCapacityLitres">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Engine Size <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="engineSizeCc" name="engineSizeCc" placeholder="engineSizeCc">';
    htmlsection += '      </div>';
    htmlsection += '      <div class="field">';
    htmlsection += '        <label>Fuel Type <span class="asteric">*</span></label>';
    htmlsection += '        <input type="text" maxlength="15" id="fuelType" name="fuelType" placeholder="fuelType">';
    htmlsection += '      </div>';
    htmlsection += '    </div>';

    htmlsection += '    <div class="three fields">';
    htmlsection += '<div class="field">';
    htmlsection += '    <label>Roles</label>';
    htmlsection += '    <select id="driverId" name="driverId" 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 + 'users/userList?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, 'userId', 'firstName', '');
        $('#driverId').html(option_role);
    });

   


}







function viewRowData(data) {

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

    var driverText = "";
    if (jsondata.driver) {
        driverText = `${jsondata.driver.firstName} ${jsondata.driver.lastName} - Tel: ${jsondata.driver.phoneNo}`;
    }

    let tableRows = `
        <tr>
            <th>Plate Number</th><td>${jsondata.plateNumber || ''}</td>
            <th>Make</th><td>${jsondata.make || ''}</td>
        </tr>
        <tr>
            <th>Model</th><td>${jsondata.model || ''}</td>
            <th>Type</th><td>${jsondata.type || ''}</td>
        </tr>
        <tr>
            <th>Color</th><td>${jsondata.color || ''}</td>
            <th>Year of Manufacture</th><td>${jsondata.yearOfManufacture || ''}</td>
        </tr>
        <tr>
            <th>Engine Number</th><td>${jsondata.engineNumber || ''}</td>
            <th>Chassis Number</th><td>${jsondata.chassisNumber || ''}</td>
        </tr>
        <tr>
            <th>Mileage (Km)</th><td>${jsondata.mileageKm || ''}</td>
            <th>Tare Weight (Kg)</th><td>${jsondata.tareWeightKg || ''}</td>
        </tr>
        <tr>
            <th>Gross Weight (Kg)</th><td>${jsondata.grossWeightKg || ''}</td>
            <th>Speed Limit (Kmh)</th><td>${jsondata.speedLimitKmh || ''}</td>
        </tr>
        <tr>
            <th>Fuel Capacity (Litres)</th><td>${jsondata.fuelCapacityLitres || ''}</td>
            <th>Engine Size (CC)</th><td>${jsondata.engineSizeCc || ''}</td>
        </tr>
        <tr>
            <th>Fuel Type</th><td>${jsondata.fuelType || ''}</td>
            <th>Driver</th><td>${driverText || ''}</td>
        </tr>
    `;

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

            <h3 style="font-weight:800; margin-bottom:20px;">Vehicle 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);
}






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

  
    // --- Required Validation for All Fields ---
    if (!formJson.plateNumber) {
        controller.showToastMsg("Plate Number 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.color) {
        controller.showToastMsg("Color Required", "#ff6666");

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

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

    } else if (!formJson.mileageKm) {
        controller.showToastMsg("Mileage (Km) Required", "#ff6666");

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

    } else if (!formJson.tareWeightKg) {
        controller.showToastMsg("Tare Weight (Kg) Required", "#ff6666");

    } else if (!formJson.grossWeightKg) {
        controller.showToastMsg("Gross Weight (Kg) Required", "#ff6666");

    } else if (!formJson.speedLimitKmh) {
        controller.showToastMsg("Speed Limit (Km/h) Required", "#ff6666");

    } else if (!formJson.fuelCapacityLitres) {
        controller.showToastMsg("Fuel Capacity (Litres) Required", "#ff6666");

    } else if (!formJson.engineSizeCc) {
        controller.showToastMsg("Engine Size (CC) Required", "#ff6666");

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

    } else if (!formJson.driverId) {
        controller.showToastMsg("Driver ID 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 + "vehicles";
        controller.allPostRequest(url, formJson, '', function(data, status) {
            if (data) {
                $('#nexttostepone').html("Save & Proceed");
                $("#nexttostepone").attr("disabled", false);
                isEdit = false;
                loadData();
            }
        });
    }
}





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

    console.log("formJson:", formJson);
 if (!formJson.plateNumber) {
        controller.showToastMsg("Plate Number 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.color) {
        controller.showToastMsg("Color Required", "#ff6666");

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

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

    } else if (!formJson.mileageKm) {
        controller.showToastMsg("Mileage (Km) Required", "#ff6666");

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

    } else if (!formJson.tareWeightKg) {
        controller.showToastMsg("Tare Weight (Kg) Required", "#ff6666");

    } else if (!formJson.grossWeightKg) {
        controller.showToastMsg("Gross Weight (Kg) Required", "#ff6666");

    } else if (!formJson.speedLimitKmh) {
        controller.showToastMsg("Speed Limit (Km/h) Required", "#ff6666");

    } else if (!formJson.fuelCapacityLitres) {
        controller.showToastMsg("Fuel Capacity (Litres) Required", "#ff6666");

    } else if (!formJson.engineSizeCc) {
        controller.showToastMsg("Engine Size (CC) Required", "#ff6666");

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

    } else if (!formJson.driverId) {
        controller.showToastMsg("Driver ID Required", "#ff6666");

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


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




}


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

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

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


   

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

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

        // Build JSON
        var formJson = {
            "permitNumber": permitNumber,
            "issuer": issuer,
            "validFrom": validFrom || "2025-11-25", // fallback if empty
            "validTo": validTo || "2025-11-25",
            "description": description,
            "vehicleId": vehicleId
        };

        var url = serverURL + "permits";

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

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

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

    var vehicleId =  localStorage.getItem("vehicleId")
 var url = serverURL + 'permits/vehicle/'+vehicleId+'?page=0&size=10000&sort=permitId,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 = $(".vehiclepermitslist");
            html_v += '<div class="ibox-body">';
            html_v += "<table class='table table-striped table-bordered table-hover' id='permitstableview' cellspacing='0' width='100%'>";
            html_v += '<thead><tr>';
            html_v += '  <th>Permit Number</th>';
            html_v += '  <th>Valid from</th>';
            html_v += '  <th>Valid To</th>';
            html_v += '  <th>Vehicle</th>';
            html_v += '</tr></thead>';
            html_v += '<tbody>';

            data.forEach((item, i) => {
                var vehicle= item.vehicle.plateNumber + " " + item.vehicle.model;

                html_v += `<tr>

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

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

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

                    <td>${vehicle}</td>

                   
                </tr>`;
            });

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

            // Initialize DataTable
            $('#permitstableview').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 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,
            });

            
        }
       
        

    });
}