<script>




    function calculate_final_amount(update = 'no') {
        if (update == 'no') {
            var actual_freight = $("#act_freight").val();
            var dehari_check = $(document).find('.dehari_check:checked').val();
            var dehari = $("#dehari").val() == '' ? 0 : $("#dehari").val();
            var fine = $("#fine").val() == '' ? 0 : $("#fine").val();
        }
        if (update == 'yes') {
            var dehari = $(document).find("#u_dehari").val() == '' ? 0 : $(document).find("#u_dehari").val();
            var dehari_check = $(document).find('.u_dehari_check:checked').val();
            var fine = $(document).find("#u_fine").val() == '' ? 0 : $(document).find("#u_fine").val();
            var actual_freight = $(document).find("#u_act_freight").val();
        }
        if (actual_freight != '') {
            if (dehari_check != 'driver') {
                dehari = 0;
            }
            var value = (parseFloat(actual_freight) + parseFloat(dehari)) - parseFloat(fine);
            $("#final_amount").val(value.toFixed(2));
            if (update == 'yes') {

                $(document).find("#u_final_amount").val(value.toFixed(2));
            }

        } else {
            $("#final_amount").val('');
            $(document).find("#u_final_amount").val('');

        }

    }

    function commission_receiving_change(update = 'no') {
        var value = $(document).find('input[name="commission_receiving"]:checked').val();
        if (value != '') {
            if (update == 'yes') {
                $(document).find('#u_hidden_commission_receiving').val(value);
            }
            $('#hidden_commission_receiving').val(value);
        } else {
            $('#hidden_commission_receiving').val('');
            $(document).find('#u_hidden_commission_receiving').val('');
        }
    }

    function cancel_trip_detail_update_form(trip_id) {
        show_trip_detail_modal(trip_id);
    }

    function total_amount(){

    }



    function feright_change(update = 'no') {

        var actual_freight = 0;
        if (update == 'yes') {
            var commission_receiving = $('#u_hidden_commission_receiving').val();
            var b_freight = $(document).find("#u_b_freight").val();
            var commission = $(document).find("#u_commission").val();
        } else {
            var b_freight = $(document).find("#b_freight").val();
            var commission = $("#commission").val();
            var commission_receiving = $('#hidden_commission_receiving').val();

        }
        if (b_freight != '' && commission != '' && commission_receiving != '') {
            if (commission_receiving != 'cash') {
                commission = parseFloat(0);
            }
            actual_freight = parseFloat(b_freight) - parseFloat(commission);
        } else {
            actual_freight = 0;
        }
        if (update == 'yes') {
            $(document).find("#u_act_freight").val(actual_freight.toFixed(2));
            calculate_final_amount('yes');
        } else {
            $("#act_freight").val(actual_freight.toFixed(2));
            calculate_final_amount();
        }
    }

    // function itemRate(){

    //     var item_weight = parseFloat($("#item_weight").val());
    //     var b_freight = parseFloat($("#b_freight").val());
    //     // Calculate unit rate if freight value and item weight are valid

    // }
    function ReachAmount(update = 'no'){
        var b_freight = parseFloat(update === 'yes'
        ? $(document).find("#u_b_freight").val()
        : $("#b_freight").val()) || 0;
        console.log(b_freight);

        var advance_amount = parseFloat(update === 'yes'
        ? $(document).find("#u_advance_amount").val()
        : $("#advance_amount").val()) || 0;

        var reach_amount = (b_freight - advance_amount).toFixed(2);
        if (update === 'yes') {
            $(document).find("#u_remainder_amount").val(reach_amount);
        } else {
            $("#remainder_amount").val(reach_amount);
        }

    }

    function itemRate(update = 'no') {
    // Get references based on update mode
    var item_weight = parseFloat(update === 'yes'
        ? $(document).find("#u_item_weight").val()
        : $("#item_weight").val()) || 0;

    var b_freight = parseFloat(update === 'yes'
        ? $(document).find("#u_b_freight").val()
        : $("#b_freight").val()) || 0;

    var unit_rate = parseFloat(update === 'yes'
        ? $(document).find("#u_unit_rate").val()
        : $("#unit_rate").val()) || 0;

    // Calculate unit rate if freight and weight are valid
    if (b_freight > 0 && item_weight > 0) {
        unit_rate = (b_freight / item_weight).toFixed(2); // Format to two decimal places

        if (update === 'yes') {
            $(document).find("#u_unit_rate").val(unit_rate);
        } else {
            $("#unit_rate").val(unit_rate);
        }

        calAmount(update); // Call calAmount after b_freight is updated
        return;
    }

    // Calculate freight value if unit rate and weight are valid
    var value = 0; // Initialize freight value
    unit_rate = parseFloat(update === 'yes'
        ? $(document).find("#u_unit_rate").val()
        : $("#unit_rate").val()) || 0;

    if (item_weight > 0 && unit_rate > 0) {
        value = (unit_rate * item_weight).toFixed(2); // Format to two decimal places

        if (update === 'yes') {
            $(document).find("#u_b_freight").val(value);
            feright_change('yes');
        } else {
            $("#b_freight").val(value);
            feright_change();
        }

        calAmount(update); // Call calAmount after b_freight is updated
    } else {
        // Clear fields if inputs are invalid
        if (update === 'yes') {
            $(document).find("#u_b_freight").val('');
            $(document).find("#u_act_freight").val('');
        } else {
            $("#b_freight").val('');
            $("#act_freight").val('');
        }

        calAmount(update); // Ensure calAmount is called in all cases
    }
}



 function calAmount(update = 'no') {
    // Parsing input values
    var bility_commission = parseFloat(update === 'yes'
        ? $(document).find("#u_bility_commission").val()
        : $("#bility_commission").val()) || 0;

        var broker_point = parseFloat(update === 'yes'
        ? $(document).find("#u_broker_point").val()
        : $("#broker_point").val()) || 0;

        var commission_party = parseFloat(update === 'yes'
        ? $(document).find("#u_commission_party").val()
        : $("#commission_party").val()) || 0;

        var fine = parseFloat(update === 'yes'
        ? $(document).find("#u_fine").val()
        : $("#fine").val()) || 0;

        var dehari = parseFloat(update === 'yes'
        ? $(document).find("#u_dehari").val()
        : $("#dehari").val()) || 0;

        var labor = parseFloat(update === 'yes'
        ? $(document).find("#u_labor").val()
        : $("#labor").val()) || 0;

        var excise_expenditure = parseFloat(update === 'yes'
        ? $(document).find("#u_excise_expenditure").val()
        : $("#excise_expenditure").val()) || 0;

        var b_freight = parseFloat(update === 'yes'
        ? $(document).find("#u_b_freight").val()
        : $("#b_freight").val()) || 0;



    // var bility_commission = parseFloat($("#bility_commission").val()) || 0;
    // var broker_point = parseFloat($("#broker_point").val()) || 0;
    // var commission_party = parseFloat($("#commission_party").val()) || 0;
    // var fine = parseFloat($("#fine").val()) || 0;

    // var dehari = parseFloat($("#dehari").val()) || 0;
    // var labor = parseFloat($("#labor").val()) || 0;
    // var excise_expenditure = parseFloat($("#excise_expenditure").val()) || 0;
    // var b_freight = parseFloat($("#b_freight").val()) || 0;

    // Base calculations

    // console.log(allRowsVisible);
    var t1 = bility_commission + broker_point + commission_party + fine;
    var t2 = dehari + labor + excise_expenditure;

    // Adjust calculation based on visibility
    var value = allRowsVisible ? t2 + b_freight - t1 : t2 - t1;
    // console.log(value);

    // Formatting the result
    value = value.toFixed(2);

    // Updating the result in the UI


    if (update === 'yes') {
             $("#u_final_amount").val(value);

        } else {
            $("#final_amount").val(value);
        }
}

//  function itemRate(update = 'no') {
//     // Get references based on update mode
//     var item_weight = parseFloat(update === 'yes'
//         ? $(document).find("#u_item_weight").val()
//         : $("#item_weight").val()) || 0;

//     var b_freight = parseFloat(update === 'yes'
//         ? $(document).find("#u_b_freight").val()
//         : $("#b_freight").val()) || 0;

//     var unit_rate = 0; // Initialize unit rate

//     // Calculate unit rate if freight and weight are valid
//     if (b_freight > 0 && item_weight > 0) {
//         unit_rate = (b_freight / item_weight).toFixed(2); // Format to two decimal places

//         if (update === 'yes') {
//             $(document).find("#u_unit_rate").val(unit_rate);
//         } else {
//             $("#unit_rate").val(unit_rate);
//         }

//         return;
//     }


//     // Calculate freight value if unit rate and weight are valid
//     var value = 0; // Initialize freight value
//     unit_rate = parseFloat(update === 'yes'
//         ? $(document).find("#u_unit_rate").val()
//         : $("#unit_rate").val()) || 0;

//     if (item_weight > 0 && unit_rate > 0) {
//         value = (unit_rate * item_weight).toFixed(2); // Format to two decimal places

//         if (update === 'yes') {
//             $(document).find("#u_b_freight").val(value);
//             feright_change('yes');
//         } else {
//             $("#b_freight").val(value);
//             feright_change();
//         }
//     } else {
//         // Clear fields if inputs are invalid
//         if (update === 'yes') {
//             $(document).find("#u_b_freight").val('');
//             $(document).find("#u_act_freight").val('');
//         } else {
//             $("#b_freight").val('');
//             $("#act_freight").val('');
//         }
//     }
// }


//  function calAmount() {
//     // Parsing input values
//     var bility_commission = parseFloat($("#bility_commission").val()) || 0;
//     var broker_point = parseFloat($("#broker_point").val()) || 0;
//     var commission_party = parseFloat($("#commission_party").val()) || 0;
//     var fine = parseFloat($("#fine").val()) || 0;

//     var dehari = parseFloat($("#dehari").val()) || 0;
//     var labor = parseFloat($("#labor").val()) || 0;
//     var excise_expenditure = parseFloat($("#excise_expenditure").val()) || 0;
//     var b_freight = parseFloat($("#b_freight").val()) || 0; // Moved outside the conditional

//     // Base calculations
//     var t1 = bility_commission + broker_point + commission_party + fine;
//     var t2 = dehari + labor + excise_expenditure;

//     // Adjust calculation based on visibility
//     var value = allRowsVisible ? t2 + b_freight - t1 : t2 - t1;
//     // console.log(value);

//     // Formatting the result
//     value = value.toFixed(2);

//     // Updating the result in the UI
//     $("#final_amount").val(value);
// }





    function get_city_histroy() {
        var from_city = $('#from_city_id').val();
        var to_city = $('#to_city_id').val();
        var trip_id = $(document).find('#details_trip_id').val();
        if (from_city != '' && to_city != '') {
            $.ajax({
                url: "{{ route('get_trip_history_city_wise') }}",
                type: "POST",
                headers: {
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                data: {
                    to_city: to_city,
                    from_city: from_city,
                    trip_id: trip_id,
                },
                success: function (data) {
                    $("#history_div").html(data);
                }
            });
        } else {
            $("#history_div").html('');

        }
    }

    $(document).ready(function () {
        setTimeout(() => {
            $(document).find('#from_city_id').focus();
        }, 600);
    });


    $(document).on('click', '.show_trip_detail_modal', function () {
        var trip_id = $(this).data('id');

        show_trip_detail_modal(trip_id);
    });

    function show_trip_detail_modal(trip_id) {
        var url = "{{ route('trip_detail_index', ':id') }}";
        url = url.replace(':id', trip_id);
        $.ajax({
            url: url,
            type: "POST",
            data: {
                trip_id: trip_id
            },
            headers: {
                "X-CSRF-TOKEN": "{{ csrf_token() }}"
            },
            success: function (response) {

                $(document).find("#addTripAdvanceData").html('');
                $(document).find("#addTripAdvanceData").html(response);
                $(document).find("#addTripAdvanceModal").modal('show');
                setTimeout(() => {
                    // $(document).find('#from_city_id').select2();
                    // $(document).find('#to_city_id').select2();
                }, 600);
            }
        });
    }

    $(document).on('submit', "#add_trip_details_form_abc", function (e) {
        e.preventDefault();
        var csrfToken = "{{ csrf_token() }}"

        var formData = new FormData(this);

        // Append the value of allRowsVisible to the form data
        formData.append('allRowsVisible', allRowsVisible);

        $.ajax({
            url: "{{ route('trip_detail_store') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: formData,

            beforeSend: function () {
                $(".error").text('');
                $("#trip_detail_sumbit_btn").text('Processing....');
                $("#trip_detail_sumbit_btn").prop('disabled', true);
            },
            success: function (data) {
                $("#trip_detail_sumbit_btn").text('مخفوظ');
                $("#trip_detail_sumbit_btn").prop('disabled', false);
                if (data.success) {
                    // $(document).find("#addTripAdvanceModal").modal('toggle');
                    $(document).find("#trip_detail_modal_table").html(data.view);
                    alertify.success("Trip Details Stored Successfully!");
                    $("#add_trip_details_form_abc")[0].reset();
                    setTimeout(() => {
                        $(".error").text('');
                        //     $(document).find('#from_city_id').select2();
                        //     $(document).find('#to_city_id').select2();
                    }, 500);
                } else {
                    $("#date_error").text(data.message);
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (error) {
                console.log(error);
                $("#trip_detail_sumbit_btn").text('مخفوظ');
                $("#trip_detail_sumbit_btn").prop('disabled', false);
                if ('errors' in error.responseJSON) {
                    $(".error").text('');
                    $.each(error.responseJSON.errors, (index, value) => {
                        $("#" + index + "_error").text(value[0]);
                    });
                }
            }
        });
    });
    $(document).on('click', '.edit_trip_detail', function () {
        var edit_id = $(this).data('id');
        var url = "{{ route('trip_detail_edit', ':id') }}";
        url = url.replace(':id', edit_id);
        $.ajax({
            url: url,
            type: "GET",
            success: function (resonpse) {
                // console.log(resonpse);
                $(document).find("#trip_detail_modal_body").html(resonpse);
            }
        });
    });
    $(document).on('submit', "#udpate_trip_detail_form", function (e) {
        e.preventDefault();
        var formData = new FormData(this);

        formData.append('allRowsVisible', allRowsVisible);

        $.ajax({
            url: "{{ route('trip_detail_update') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: formData,
            beforeSend: function () {
                $("#trip_detail_sumbit_btn").text('Processing....');
                $("#trip_detail_sumbit_btn").prop('disabled', true);
            },
            success: function (data) {
                $("#trip_detail_sumbit_btn").text('اپڈیٹ');
                $("#trip_detail_sumbit_btn").prop('disabled', false);
                if (data.success) {
                    show_trip_detail_modal(data.trip_id);
                    alertify.success("Trip Detail Updated Successfully!");
                    window.location.reload();
                } else {
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (error) {
                $("#trip_detail_sumbit_btn").text('اپڈیٹ');
                $("#trip_detail_sumbit_btn").prop('disabled', false);
                if ('errors' in error.responseJSON) {
                    $(".u_error").text('');
                    $.each(error.responseJSON.errors, (index, value) => {
                        $("#u_" + index + "_error").text(value[0]);
                    });
                }
            }
        });
    });
    $(document).on('click', '.delete_trip_detail', function () {
        var del_id = $(this).data('id');
        var url = "{{ route('trip_detail_delete', ':id') }}";
        url = url.replace(':id', del_id);
        if (confirm('Are You Sure To Delete The Trip Detail?')) {
            $.ajax({
                url: url,
                type: "GET",
                success: function (response) {
                    if (response.success) {
                        // trip_detail_table.ajax.reload();
                        alertify.success("Trip Detail Deleted Successfully!");
                    } else {
                        alertify.error("Something Went Wrong!");
                    }
                }
            });
        } else {
            return false;
        }
    });
</script>
