"use strict";
$("#fleet_id").change(function () {
    var fleet_id = $('#fleet_id').val();
    var baseurl = $('#baseurl').val();
    var url = baseurl + '/ajax/vehicle/list/' + fleet_id;

    $.ajax({
        method: "GET",
        url: url,
        data: { fleet_id: fleet_id },
        success: function (data) {
            var data = JSON.parse(data);

            $("#vehicle_id").empty();
            $("#vehicle_id").append('<option value ="" >None</option>');

            $.each(data, function (key, value) {
                var selectOption = `<option value="${value.id}" data-cname="${value.company}">${value.reg_no}</option>`;
                $("#vehicle_id").append(selectOption);
            });

            $("#vehicle_id").trigger('change');
        },
        beforeSend: () => bdtaskIlmCommonJs.elemLoader.show('#vehicle-id-wrapper', 25, true),
        complete: () => bdtaskIlmCommonJs.elemLoader.hide('#vehicle-id-wrapper')
    });
});

"use strict";
$("#tripLocation").change(function () {
    console.log('pawan vishwkarma');
    var tripid = $('#tripLocation').val();
    var baseurl = $('#baseurl').val();
    var url = baseurl + '/ajax/vehicle/list/' + fleet_id;
});
function remove(picid) {

    var deleteid = picid;
    var baseurl = $('#baseurl').val();

    var url = baseurl + '/ajax/vehicle/pic/delete';

    // var csrfName = $("#csrf" + picid).attr('name'); // CSRF Token name
    // var csrfHash = $("#csrf" + picid).val(); // CSRF hash

    // var datadel = { 
    //   [csrfName]: csrfHash, 
    //   picid: deleteid, 

    // }; 
    var datadel = {

        picid: deleteid,

    };


    $.ajax({
        method: "POST",
        url: url,
        dataType: "JSON",
        data: datadel,
        success: function (response) {
            $("#" + picid).remove();
        }
    });

}
function removefleetImage(picid) {

    var deleteid = picid;
    var baseurl = $('#baseurl').val();

    var url = baseurl + '/ajax/fleet/pic/delete';

    // var csrfName = $("#csrf" + picid).attr('name'); // CSRF Token name
    // var csrfHash = $("#csrf" + picid).val(); // CSRF hash

    // var datadel = { 
    //   [csrfName]: csrfHash, 
    //   picid: deleteid, 

    // }; 
    var datadel = {

        picid: deleteid,

    };


    $.ajax({
        method: "POST",
        url: url,
        dataType: "JSON",
        data: datadel,
        success: function (response) {
            $("#" + picid).remove();
        }
    });

}

"use strict";
$("#login_email").focusout(function () {
    var $env = $(this),
        $eloaderTarget = $env.parent(),
        email = $env.val(),
        ajaxUrl = `${bdtaskIlmCommonJs.BASE_URL}/ajax/passanger/${email}/email`;

    if (email != null && email != "") {
        bdtaskIlmCommonJs.elemLoader.show($eloaderTarget, 25, false);

        $.get(ajaxUrl, {}, function (result) {
            if (result.response == 200) {
                var userdetail = JSON.parse(result.data);

                // Fill user data
                $("#last_name").val(userdetail.last_name);
                $("#first_name").val(userdetail.first_name + " " + userdetail.last_name);
                $("#login_mobile").val(userdetail.login_mobile);
                $("#login_email").val(userdetail.login_email);
                $("#id_type").val(userdetail.id_type);
                $("#id_number").val(userdetail.id_number);
                $("#country_id").val(userdetail.country_id);
                $("#city").val(userdetail.city);
                $("#zip_code").val(userdetail.zip_code);
                // $("#address").val(userdetail.address);

                setTimeout(() => {
                    $('#submit-booking').focus();
                    bdtaskIlmCommonJs.elemLoader.hide($eloaderTarget);
                }, 500);
            } else {
                if (result.response == 401) {
                    alert(result.data);
                    $("#login_email").val('');
                }

                bdtaskIlmCommonJs.elemLoader.hide($eloaderTarget);
            }
        }, "JSON");
    }
});

"use strict";
$("#login_mobile").focusout(function () {

    var mobile = $("#login_mobile").val();
    var type = "mobile";
    var userdetail = null;

    if (mobile == "") {

        return false;
    }
    var baseurl = $('#baseurl').val();
    var url = baseurl + '/ajax/passanger/' + mobile + '/' + type;

    $.ajax({
        method: "GET",
        url: url,
        dataType: "JSON",

        success: function (result) {

            if (result.response == 200) {

                var userdetail = JSON.parse(result.data);

                // Fill user data
                $("#last_name").val(userdetail.last_name);
                $("#first_name").val(userdetail.first_name + " " +userdetail.last_name);
                $("#login_mobile").val(userdetail.login_mobile);
                $("#login_email").val(userdetail.login_email);
                $("#id_type").val(userdetail.id_type);
                $("#id_number").val(userdetail.id_number);
                $("#country_id").val(userdetail.country_id);
                $("#city").val(userdetail.city);
                $("#zip_code").val(userdetail.zip_code);
                // $("#address").val(userdetail.address);
                return false;

            }


            if (result.response == 204) {

            }


        }

    });



});





"use strict";
$("#couponcode").focusout(function () {

    var code = $("#coupon").val();
    var journetydate = $("#journeydate").val();
    var subtripid = $("#subtripId").val();
    var validation = null;


    var baseurl = $('#baseurl').val();
    var url = baseurl + '/ajax/coupon/' + code + '/' + subtripid + '/' + journetydate;

    $.ajax({
        method: "GET",
        url: url,
        dataType: "JSON",

        success: function (result) {

            if (result.response == 200) {

                console.log(result.discount);

                var successmessage = result.status;
                $("#couponmessage").html(successmessage);
                $("#couponmessage").css("color", "green");


                var discount = result.discount;
                var discount_type = result.discount_type;
                var oldtotal = $("#oldgrandtotal").val();
                if(discount_type == 2){
                    discount = (oldtotal*parseFloat(discount))/100;
                }
                discount = parseFloat(discount)
                if (discount == 0) {
                    $("#grandtotal").val(oldtotal);
                    $("#partialpay").val(oldtotal);
                } else {
                    var newgrandtotal = parseFloat(oldtotal) - discount;
                    if(newgrandtotal < 0){
                        newgrandtotal = 0;
                        discount = parseFloat(oldtotal);
                    }

                    $("#grandtotal").val(newgrandtotal);
                    $("#partialpay").val(newgrandtotal);
                    $("#discount").val(discount);
                    $("#coupon").attr('readonly', true);
                    $("#discount").attr('readonly', true);
                }

                validation = JSON.parse(result.data);
                console.log(validation);
            }

            if (result.response == 204) {
                console.log(result.message);
                var errormessage = result.message;
                $("#coupon").val('');
                $("#couponmessage").html(errormessage);
                $("#couponmessage").css("color", "red");
                validation = JSON.parse(result.data);
                console.log(validation);
            }
        }
    });
});

"use strict";

$(document).ready(function () {
    var companyField = $("#company_id");
    // Trigger AJAX on change (for dropdown selection)
    companyField.change(function () {
        fetchTrips(companyField.val());
    });
    // Trigger AJAX on page load if the company field is hidden
    if (companyField.is(':hidden')) {
        fetchTrips(companyField.val());
    }
});

/* REPORT MENU SELECT BOX AJAX */
"use strict";
$(document).ready(function () {
    
    var companyField = $("#r_company_id");
    var hiddencompanyField = $("#r_company_id");
    companyField.change(function () {
        fetchCompanyTrips(companyField.val());
    });
    // Trigger AJAX for hidden field (when role_id = 7)
    if (hiddencompanyField.val()) {
        fetchCompanyTrips(hiddencompanyField.val());
    }
});

function fetchTrips(company_id) {
    var baseurl = $('#baseurl').val();
    var url = baseurl + 'get/maintrip/' + company_id;

    $.ajax({
        method: "GET",
        url: url,
        data: { company_id: company_id },
        success: function (data) {
            $("#trip_id").empty(); // Clear previous options
            //$("#trip_id").append('<option value="" >Select</option>');
            $("#trip_id").append('<option value="all">All</option>');

            if (data.data !== '"all"') {
                var tripData = JSON.parse(data.data); // Parsing JSON data

                $.each(tripData, function (key, value) {
                    $("#trip_id").append(
                        `<option value="${value.tripid}">
                            ${value.pickup_location_name} - ${value.drop_location_name} 
                            (${value.start_time} - ${value.end_time})
                        </option>`
                    );
                });
            }
        },
        error: function (xhr, status, error) {
            console.error("Error fetching data:", error);
        }
    });
}

function fetchCompanyTrips(company_id) {
    var baseurl = $('#baseurl').val();
    var url = baseurl + 'get/maintrip/' + company_id;
    
    var r_trip_id = $('#r_trip_id').val();
    var r_subtrip_id = $('#r_subtrip_id').val();

    $.ajax({
        method: "GET",
        url: url,
        data: { company_id: company_id },
        success: function (data) {

            
            $("#r_trip_id").empty(); // Clear previous options
            var tripselected = "";
            if(r_subtrip_id == "all"){
                tripselected = "selected";
            }
            $("#r_trip_id").append('<option '+tripselected+' value="all">All</option>');
            if(data.maintrips){
                var maintrips = data.maintrips;
                $.each(maintrips, function (key, value) {
                    tripselected = "";
                    if(r_subtrip_id == value.tripid){
                        tripselected = "selected";
                    }
                    $("#r_trip_id").append(
                        `<option ${tripselected} value="${value.tripid}">
                            ${value.pickup_location_name} - ${value.drop_location_name} 
                            (${value.start_time} - ${value.end_time})
                        </option>`
                    );
                });
            }

            $("#r_subtrip_id").empty();
            $("#r_subtrip_id").append('<option value="all">All</option>');
            
            if(data.subtrips){
                var subtrips = data.subtrips;
                $.each(subtrips, function (key, value) {
                    $("#r_subtrip_id").append(
                        '<option value="' + value.subtripsid + '">' + value.pickup_location_name + '-' + value.drop_location_name +
                        '</option>');
                });
            }
        },
        error: function (xhr, status, error) {
            $("#r_trip_id").empty(); // Clear previous options
            $("#r_trip_id").append('<option value="all">All</option>');
            $("#r_subtrip_id").empty();
            $("#r_subtrip_id").append('<option value="all">All</option>');
        }
    });
}

// "use strict";
// $("#company_id").change(function () {
//     var company_id = $('#company_id').val();
//     var baseurl = $('#baseurl').val();
//     var url = baseurl + '/get/maintrip/' + company_id;
//     $.ajax({
//         method: "GET",
//         url: url,
//         data: { company_id: company_id },
//         success: function (data) {  
//             $("#trip_id").empty(); // Clear previous options
//             $("#trip_id").append('<option value ="" >Select</option>');
//             $("#trip_id").append('<option value="all">All</option>');          

//             // if (data.data == '"all"') {
//             //     $("#trip_id").empty();
//             //     $("#trip_id").append('<option value="all">All</option>');

//             // }
            
//             if (data.data !== '"all"') {
//                 var tripData = JSON.parse(data.data); // Parsing JSON data

//                 $.each(tripData, function (key, value) {
//                     $("#trip_id").append(
//                         `<option value="${value.tripid}">
//                             ${value.pickup_location_name} - ${value.drop_location_name} 
//                             (${value.start_time} - ${value.end_time})
//                         </option>`
//                     );
//                 });
//             }
//         },
//         error: function (xhr, status, error) {
//             console.error("Error fetching data:", error);
//         }
//     });
// });



"use strict";
$("#trip_id").change(function () {

    var maintrip_id = $('#trip_id').val();
    console.log("Trip ID selected:", maintrip_id);
    var baseurl = $('#baseurl').val();
    var url = baseurl + '/get/subtrip/' + maintrip_id;
    console.log(maintrip_id);
    $.ajax({
        method: "GET",
        url: url,
        data: { maintrip_id: maintrip_id },
        success: function (data) {
            $("#subtrip_id").empty();
            $("#subtrip_id").append('<option value="all">All</option>');
            console.log("select");
            if (data.data == '"all"') {
                $("#subtrip_id").empty();
                $("#subtrip_id").append('<option value ="" >Select</option>');
                $("#subtrip_id").append('<option value="all">All</option>');

            }


            else {
                var subtipdata = JSON.parse(data.data);
                $("#subtrip_id").empty();
                $("#subtrip_id").append('<option value ="" >Select</option>');
                $("#subtrip_id").append('<option value ="all" >All</option>');

                $.each(subtipdata, function (key, value) {
                    $("#subtrip_id").append('<option value="' + value.subtripsid + '">' + value.pickup_location_name + '-' + value.drop_location_name +
                        '</option>');
                });
            }

        }

    });


});

"use strict";
$("#r_trip_id").change(function () {

    var maintrip_id = $('#r_trip_id').val();
    var company_id = $('#r_company_id').val();
    
    var baseurl = $('#baseurl').val();
    var url = baseurl + 'get/company/subtrip';
    $.ajax({
        method: "GET",
        url: url,
        data: { maintrip_id: maintrip_id, company_id: company_id },
        success: function (data) {
            
            $("#r_subtrip_id").empty();
            $("#r_subtrip_id").append('<option value="all">All</option>');
            console.log(data.subtrips, "data.subtrips");
            if(data.subtrips){
                var subtipdata = data.subtrips;
                $.each(subtipdata, function (key, value) {
                    console.log(value.subtripsid + value.pickup_location_name, "data.subtrips");
                    $("#r_subtrip_id").append('<option value="' + value.subtripsid + '">' + value.pickup_location_name + '-' + value.drop_location_name +
                        '</option>');
                }); 
            }
        }

    });


});

"use strict";

$(document).ready(function () {
    var companyField = $("#company_id_for_agent");
    var hiddenCompanyField = $("#company_id");

    // Trigger AJAX on dropdown change
    companyField.change(function () {
        fetchAgents(companyField.val());
    });

    // Trigger AJAX for hidden field (when role_id = 7)
    if (hiddenCompanyField.val()) {
        fetchAgents(hiddenCompanyField.val());
    }
});

function fetchAgents(company_id) {
    var baseurl = $('#baseurl').val();
    var url = baseurl + '/get/agentlist/' + company_id;

    $.ajax({
        method: "GET",
        url: url,
        success: function (data) {
            $("#agent_id").empty();
            $("#agent_id").append('<option value="all">All</option>');

            if (data.data !== '"all"') {
                var agentData = JSON.parse(data.data);

                $.each(agentData, function (key, value) {
                    $("#agent_id").append(
                        `<option value="${value.agent_id}">
                            ${value.first_name} ${value.last_name}
                        </option>`
                    );
                });
            }
        },
        error: function (xhr, status, error) {
            console.error("Error fetching agent data:", error);
        }
    });
}

// "use strict";
// $("#company_id_for_agent").change(function () {
//     var company_id = $('#company_id_for_agent').val();
//     var baseurl = $('#baseurl').val();
//     var url = baseurl + '/get/agentlist/' + company_id;

//     $.ajax({
//         method: "GET",
//         url: url,
//         success: function (data) {
//             $("#agent_id").empty();
//             $("#agent_id").append('<option value="all">All</option>');

//             if (data.data !== '"all"') {
//                 var agentData = JSON.parse(data.data);

//                 $.each(agentData, function (key, value) {
//                     $("#agent_id").append(
//                         `<option value="${value.agentid}">
//                             ${value.first_name} ${value.last_name}
//                         </option>`
//                     );
//                 });
//             }
//         },
//         error: function (xhr, status, error) {
//             console.error("Error fetching data:", error);
//         }
//     });
// });

"use strict";
$("#lngid").change(function () {

    var lang_id = $('#lngid').val();
    var baseurl = $('#baseurl').val();
    var url = baseurl + '/get/lang/code/' + lang_id;

    $.ajax({
        method: "GET",
        url: url,
        data: { lang_id: lang_id },
        success: function (data) {


            var getData = JSON.parse(data)
            console.log(getData)
            $("#language_code").val("");
            $("#language_code").val(getData.lngcode);

            $("#name").val("");
            $("#name").val(getData.name);

        }

    });


});


"use strict";
$('#company').on('change', function () {
    var companyIds = $(this).val();
    var baseurl = $('#baseurl').val();
    var url = baseurl + 'modules/backend/coupons/getTripsByCompany';

    $.ajax({
        method: "GET",
        url: url,
        data: { companyIds: companyIds },
        success: function (response) {
            var tripContainer = $('#tripContainer');
            var selectedSubTrips = JSON.parse($('#selectedSubTrips').val() || '[]');

            tripContainer.empty();

            if (response.success) {
                $.each(response.data, function (index, tripVal) {
                    const tripCheckbox = $(`
                        <div class="trip-group">
                            <label>
                                <input type="checkbox" class="main-trip"
                                       data-trip-id="${tripVal.id}"
                                       name="main_trips[]"
                                       value="${tripVal.id}">
                                ${tripVal.picklocation} -- ${tripVal.droplocation} ( ${tripVal.id} )
                            </label>
                        </div>
                    `);

                    const subTripContainer = $('<div class="subtrip-container" style="margin-left: 20px;"></div>');

                    let anySubTripChecked = false; // Track if at least one sub-trip is checked

                    $.each(tripVal.children, function (i, subTripVal) {
                        const isChecked = selectedSubTrips.includes(subTripVal.id.toString()) ? 'checked' : '';

                        if (isChecked) {
                            anySubTripChecked = true;
                        }

                        subTripContainer.append(`
                            <label>
                                <input type="checkbox" class="sub-trip"
                                       data-parent-id="${tripVal.id}"
                                       name="subtrips[${tripVal.id}][]"
                                       value="${subTripVal.id}"
                                       ${isChecked}>
                                ${subTripVal.picklocation} -- ${subTripVal.droplocation}
                            </label><br>
                        `);
                    });

                    tripCheckbox.find('.main-trip').prop('checked', anySubTripChecked);

                    tripCheckbox.appendTo(tripContainer);
                    tripContainer.append(subTripContainer);
                });

                // === Checkbox Synchronization Logic ===
                $(document).on('change', '.main-trip', function () {
                    const tripId = $(this).data('trip-id');
                    const isChecked = $(this).prop('checked');
                    $(`.sub-trip[data-parent-id="${tripId}"]`).prop('checked', isChecked);
                });

                $(document).on('change', '.sub-trip', function () {
                    const tripId = $(this).data('parent-id');
                    const anySubChecked = $(`.sub-trip[data-parent-id="${tripId}"]:checked`).length > 0;
                    $(`.main-trip[data-trip-id="${tripId}"]`).prop('checked', anySubChecked);
                });
            } else {
                tripContainer.append('<div>No trips found</div>');
            }
        },
        error: function () {
            alert('Failed to fetch trip data. Please try again.');
        }
    });
});

/* 07-06-2025 - REPORT MENU SELECT BOX AJAX */
"use strict";
$(document).ready(function () {
    
    var companyField = $("#report_company_id");
    var hiddencompanyField = $("#report_company_id");
    companyField.change(function () {
        getTripsByCompanyIds(companyField.val());
    });
    // Trigger AJAX for hidden field (when role_id = 7)
    if (hiddencompanyField.val()) {
        getTripsByCompanyIds(hiddencompanyField.val());
    }
});

function getTripsByCompanyIds(companyIds)
{
    var baseurl = $('#baseurl').val();
    var url = baseurl + 'ajax/getTripsByCompany';

    $.ajax({
        method: "GET",
        url: url,
        data: { companyIds: companyIds },
        success: function (response) {
            var tripContainer = $('#tripContainer');
            var selectedSubTrips = JSON.parse($('#selectedSubTrips').val() || '[]');

            tripContainer.empty();

            if (response.success) {
                $.each(response.data, function (index, tripVal) {
                    const tripCheckbox = $(`
                        <div class="trip-group">
                            <label>
                                <input type="checkbox" class="main-trip"
                                       data-trip-id="${tripVal.id}"
                                       name="main_trips[]"
                                       value="${tripVal.id}">
                                ${tripVal.picklocation} -- ${tripVal.droplocation} ( ${tripVal.id} )
                            </label>
                        </div>
                    `);

                    const subTripContainer = $('<div class="subtrip-container" style="margin-left: 20px;"></div>');

                    let anySubTripChecked = false; // Track if at least one sub-trip is checked

                    $.each(tripVal.children, function (i, subTripVal) {
                        const isChecked = selectedSubTrips.includes(subTripVal.id.toString()) ? 'checked' : '';

                        if (isChecked) {
                            anySubTripChecked = true;
                        }

                        subTripContainer.append(`
                            <label>
                                <input type="checkbox" class="sub-trip"
                                       data-parent-id="${tripVal.id}"
                                       name="subtrips[${tripVal.id}][]"
                                       value="${subTripVal.id}"
                                       ${isChecked}>
                                ${subTripVal.picklocation} -- ${subTripVal.droplocation}
                            </label><br>
                        `);
                    });

                    tripCheckbox.find('.main-trip').prop('checked', anySubTripChecked);

                    tripCheckbox.appendTo(tripContainer);
                    tripContainer.append(subTripContainer);
                });

                // === Checkbox Synchronization Logic ===
                $(document).on('change', '.main-trip', function () {
                    const tripId = $(this).data('trip-id');
                    const isChecked = $(this).prop('checked');
                    $(`.sub-trip[data-parent-id="${tripId}"]`).prop('checked', isChecked);
                });

                $(document).on('change', '.sub-trip', function () {
                    const tripId = $(this).data('parent-id');
                    const anySubChecked = $(`.sub-trip[data-parent-id="${tripId}"]:checked`).length > 0;
                    $(`.main-trip[data-trip-id="${tripId}"]`).prop('checked', anySubChecked);
                });
            } else {
                tripContainer.append('<div>No trips found</div>');
            }
        },
        error: function () {
            alert('Failed to fetch trip data. Please try again.');
        }
    });
}

$(document).on('change focusout', '.mobile_valid_check', function () {
    const $this = $(this);
    const mobile = $this.val().trim();
    
    // Pattern: Starts with 0 and followed by exactly 10 digits (Total 11)
    const pattern = /^0\d{10}$/;

    // Remove existing error message if any
    $this.next('.mobile-error-msg').remove();

    if (mobile !== "" && !pattern.test(mobile)) {
        $this.css("border", "2px solid #dc3545"); // Bootstrap danger color
        $this.after('<small class="mobile-error-msg text-danger d-block mt-1">Mobile number must start with 0 and be exactly 11 digits.</small>');
        
        // Optionally keep the focus if needed, but non-blocking is better
    } else if (mobile !== "") {
        $this.css("border", "1px solid #198754"); // Bootstrap success color
    } else {
        $this.css("border", "");
    }
});



