<script>
    $(document).ready(function () {
        $(".report_select").select2();
        $("#closed_trip").select2();

    });

    function checkbox_change(report, value) {
        if (report == 'year') {
            var type = 'yearly';
        }
        if (report == 'month') {
            var type = 'monthly';
        }
        if (value == 'is_detail' && $("#" + type + "_is_detail").is(":checked")) {
            $("#" + type + "_is_ranking").attr('checked', false);
        }
        if (value == 'is_ranking' && $("#" + type + "_is_ranking").is(":checked")) {
            $("#" + type + "_is_detail").attr('checked', false);
        }
    }

    function add_new_trip() {
        $(document).find("#addTripModal").modal('toggle');
        setTimeout(() => {
            $("#vehicle").select2();
            $(".report_select").select2();
        }, 300);
    }

    // below code with move the focus of input to
    // next input filed by pressing enter key
    $(document).on('keypress', '.change_focus', function (e) {
        var next_id = $(this).data('id');
        if (e.which === 13) {
            e.preventDefault();
            document.getElementById(next_id).focus();
        }
    });

    function clear_fields() {

        $("#add_trip_form")[0].reset();
        $(".error").text('');
        $("#vehicle").select2();
    }

    function payment_method_change(method) {

        if (method == 'bank' || method == 'on_account') {
            var trip_id = $("#u_trip_id").val();
            $.ajax({
                url: "{{ route('payment_method_change_for_trip') }}",
                type: "POST",
                headers: {
                    'X-CSRF-TOKEN': "{{ csrf_token() }}",
                },
                data: {
                    method: method,
                    trip_id: trip_id
                },
                beforeSend: function () {

                },
                success: function (data) {
                    $("#payment_method_dev").html(data);
                    setTimeout(() => {
                        $(document).find("#bank_select").select2({
                            tags: true
                        });
                        $(document).find("#u_brokers").select2();

                    }, 200);
                },
                error: function (error) {

                }
            });
        }
    }





    //////// not use this function in trip ////////////////////////////////  yes not work in trip
    function get_meter_reading(update = 'no') {
        if (update == 'yes') {
            var vehicle = $(document).find("#u_vehicle").val();

        } else {
            var vehicle = $("#vehicle").val();

        }
        $.ajax({
            url: "{{ route('get_vehicle_reading') }}",
            type: "POST",
            data: {
                vehicle_id: vehicle
            },
            headers: {
                "X-CSRF-TOKEN": "{{ csrf_token() }}"
            },
            success: function (resonpse) {
                // console.log(resonpse);
                if (update == 'yes') {

                    $(document).find("#u_reading_start").val(resonpse.reading);
                    $(document).find("#u_start_date").val(resonpse.date);
                    $(document).find("#u_hidden_start_date").val(resonpse.date);
                } else {

                    $(document).find("#reading_start").val(resonpse.reading);
                    $(document).find("#start_date").val(resonpse.date);
                    $(document).find("#hidden_start_date").val(resonpse.date);
                }

            }
        });
    }

    var trip_table = $("#trip_table").DataTable({
        "iDisplayLength": 10,
        processing: true,
        serverSide: true,
      /*  scrollY: 50,
        deferRender: true,
        scroller: true,*/
        ajax: "{{ route('trip_index') }}",
        columns: [{
            name: "action",
            data: "action",
            orderable: false,
        },
            {
                name: "id",
                data: "id"
            },
            {
                name: "start_date",
                data: "start_date",

            },
            {
                name: "vehicle",
                data: "vehicle",
                searchable: true,
            },
        ]
    });

    $(document).on('change', '#received_from_id', function () {
        var table = $(this).find(":selected").data('table');
        $(document).find('#received_party_table').val(table);
    });
    $(document).on('click', '.show_adjustments', function () {
        var trip_id = $(this).data('id');
        var url = "{{ route('show_adjustments') }}";
        // url = url.replace(':id', trip_id);
        $.ajax({
            url: url,
            type: "POST",
            data: {
                trip_id: trip_id
            },
            headers: {
                "X-CSRF-TOKEN": "{{ csrf_token() }}"
            },
            success: function (resonpse) {
                // console.log(resonpse);
                $("#addTripAdvanceData").html(resonpse);
                $("#addTripAdvanceModal").modal('toggle');
                setTimeout(() => {
                    $(document).find('#received_amount').focus();
                }, 500);
            }
        });
    });
    $(document).on('submit', "#add_adjustments_form", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('show_adjustments_store') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: new FormData(this),
            beforeSend: function () {
                $(".error").text('');
                $(document).find("#add_adjustment_btn").text('Processing....');
                $(document).find("#add_adjustment_btn").prop('disabled', true);
            },
            success: function (data) {
                $(document).find("#add_adjustment_btn").text('محفوظ');
                $(document).find("#add_adjustment_btn").prop('disabled', false);
                if (data.success) {
                    $(document).find("#addTripAdvanceModal").modal('toggle');
                    alertify.success("Adjustments Added To Trip Successfully!");
                    window.location.reload();
                } else {
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (error) {
                $(document).find("#add_adjustment_btn").text('محفوظ');
                $(document).find("#add_adjustment_btn").prop('disabled', false);
                if ('errors' in error.responseJSON) {
                    $(".r_error").text('');
                    $.each(error.responseJSON.errors, (index, value) => {
                        $(document).find("#" + index + "_error").text(value[0]);
                    });
                }
                setTimeout(() => {
                    $(document).find('#received_amount').focus();
                }, 500);
            }
        });
    });
    $(document).on('click', '.close_trip', function () {
        var trip_id = $(this).data('id');
        // console.log(trip_id);
        var url = "{{ route('close_trip') }}";
        // 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) {
                // console.log(response);
                $(document).find("#addTripAdvanceData").html(response);
                $(document).find("#addTripAdvanceModal").modal('toggle');
                setTimeout(() => {
                    $(document).find('#start_meter_reading').focus();
                }, 500);
            }
        });
    });
    $(document).on('click', '.update_close_trip', function () {
        var trip_id = $(this).data('id');
        // console.log(trip_id);
        var url = "{{ route('update_close_trip') }}";
        // 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) {
                // console.log(response);
                $(document).find("#addTripAdvanceData").html(response);
                $(document).find("#addTripAdvanceModal").modal('toggle');
                setTimeout(() => {
                    $(document).find('#start_meter_reading').focus();
                }, 500);
            }
        });
    });
    $(document).on('submit', "#closeTripForm", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('close_trip_store') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: new FormData(this),
            beforeSend: function () {
                $(document).find(".r_error").text('');
                $(document).find("#closeTripSubmit").text('Processing....');
                $(document).find("#closeTripSubmit").prop('disabled', true);
            },
            success: function (data) {
                $(document).find(".r_error").text('');
                $(document).find("#closeTripSubmit").text('کلوز ٹرپ');
                $(document).find("#closeTripSubmit").prop('disabled', false);
                if (data.success) {
                    alertify.success("Trip Closed Successfully!");
                    $(document).find("#addTripAdvanceModal").modal('toggle');
                    window.location.reload();
                } else {
                    $(document).find("#older_slip_date_error").text(data.message);
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (error) {
                $(document).find("#closeTripSubmit").text('کلوز ٹرپ');
                $(document).find("#closeTripSubmit").prop('disabled', false);
                if ('errors' in error.responseJSON) {
                    $(document).find(".r_error").text('');
                    $.each(error.responseJSON.errors, (index, value) => {
                        $(document).find("#" + index + "_error").text(value[0]);
                    });
                }
                setTimeout(() => {
                    $(document).find('#start_meter_reading').focus();
                }, 500);
            }
        });
    });
    $(document).on('submit', "#monthly_trip_report_form", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('monthly_vehicle_profit_report') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: new FormData(this),
            beforeSend: function () {
                $(document).find(".r_error").text('');
                $(document).find("#monthly_vehicle_profit_report_btn").text('Processing....');
                $(document).find("#monthly_vehicle_profit_report_btn").prop('disabled', true);
                $(document).find("#profit_report_dev").html('');
            },
            success: function (data) {
                $(document).find(".r_error").text('');
                $(document).find("#monthly_vehicle_profit_report_btn").text('رپورٹ');
                $(document).find("#monthly_vehicle_profit_report_btn").prop('disabled', false);
                alertify.success("Successfully!");
                if (data.success == false) {
                    if (data.type == 'ranking_detail') {
                        var url = "{{ route('detailed_vehicle_profit_ranking_report',[':id',":from",":to"]) }}"

                    } else {
                        var url = "{{ route('detailed_monthly_vehicle_profit_report',[':id',":from",":to"]) }}"

                    }
                    url = url.replace(':id', data.vehicle_id);
                    url = url.replace(':from', data.from);
                    url = url.replace(':to', data.to);
                    window.open(url, "_blank")
                } else {
                    $(document).find("#profit_report_dev").html(data);
                }

            },
            error: function (error) {
                $(document).find("#profit_report_dev").html('');

                $(document).find("#monthly_vehicle_profit_report_btn").text('رپورٹ');
                $(document).find("#monthly_vehicle_profit_report_btn").prop('disabled', false);
            }
        });
    });
    $(document).on('submit', "#yearly_trip_report_form", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('yearly_vehicle_profit_report') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: new FormData(this),
            beforeSend: function () {
                $(document).find(".r_error").text('');
                $(document).find("#yearly_vehicle_profit_report_btn").text('Processing....');
                $(document).find("#yearly_vehicle_profit_report_btn").prop('disabled', true);
                $(document).find("#profit_report_dev").html('');
            },
            success: function (data) {
                alertify.success("Successfully!");
                $(document).find(".r_error").text('');
                $(document).find("#yearly_vehicle_profit_report_btn").text('رپورٹ');
                $(document).find("#yearly_vehicle_profit_report_btn").prop('disabled', false);
                if (data.success == false) {
                    if (data.type == 'ranking_detail') {
                        var url = "{{ route('yearly_vehicle_profit_ranking_report',[':id',":from",":to"]) }}"

                    } else {
                        var url = "{{ route('detailed_monthly_vehicle_profit_report',[':id',":from",":to"]) }}"

                    }
                    url = url.replace(':id', data.vehicle_id);
                    url = url.replace(':from', data.from);
                    url = url.replace(':to', data.to);
                    window.open(url, "_blank")
                } else {
                    $(document).find("#profit_report_dev").html(data);
                }
            },
            error: function (error) {
                $(document).find("#profit_report_dev").html('');

                $(document).find("#yearly_vehicle_profit_report_btn").text('رپورٹ');
                $(document).find("#yearly_vehicle_profit_report_btn").prop('disabled', false);
            }
        });
    });
    $("#add_trip_form").on('submit', function (e) {
    e.preventDefault();

    console.log("Submit button clicked");
    const startTime = performance.now();

    const formData = new FormData(this);
    console.log("FormData created", performance.now() - startTime);

    $.ajax({
        url: "{{ route('trip_store') }}",
        type: "POST",
        contentType: false,
        processData: false,
        data: formData,
        beforeSend: function () {
            console.log("AJAX request initiated");
            $(".error").text('');
            $("#submit_btn").text('Processing....');
            $("#submit_btn").prop('disabled', true);
        },
        success: function (data) {
            console.log("AJAX success", performance.now() - startTime);
            $("#submit_btn").text('شروع کریں');
            $("#submit_btn").prop('disabled', false);
            if (data.success) {
                $("#addTripModal").modal('toggle');
                trip_table.ajax.reload();
                clear_fields();
                alertify.success("Trip Stored Successfully!");
            } else {
                $("#start_date_error").text(data.message);
                alertify.error("Something Went Wrong!");
            }
        },
        error: function (error) {
            console.log("AJAX error", error);
            $("#submit_btn").text('شروع کریں');
            $("#submit_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', function () {
        var edit_id = $(this).data('id');
        var url = "{{ route('trip_edit', ':id') }}";
        url = url.replace(':id', edit_id);
        $.ajax({
            url: url,
            type: "GET",
            success: function (resonpse) {
                // console.log(resonpse);
                $("#addTripAdvanceData").html(resonpse);
                $("#addTripAdvanceModal").modal('toggle');
            }
        });
    });
    $(document).on('submit', "#udpate_trip_form", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('trip_update') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: new FormData(this),
            beforeSend: function () {
                $("#update_btn").text('Processing....');
                $("#update_btn").prop('disabled', true);
            },
            success: function (data) {
                $("#update_btn").text('اپڈیٹ');
                $("#update_btn").prop('disabled', false);
                if (data.success) {
                    trip_table.ajax.reload();
                    $("#addTripAdvanceModal").modal('hide');
                    setTimeout(() => {
                        $(document).find('#vehicle').html(data.view).select2();
                    }, 200)
                    alertify.success("Trip Updated Successfully!");

                } else {
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (error) {
                $("#update_btn").text('اپڈیٹ');
                $("#update_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', function () {
        var del_id = $(this).data('id');
        var url = "{{ route('trip_delete', ':id') }}";
        url = url.replace(':id', del_id);
        if (confirm(
            'Are You Sure To Delete The Trip? It will delete all records of this trip which will not be recovered'
        )) {
            $.ajax({
                url: url,
                type: "GET",
                success: function (response) {
                    if (response.success) {
                        trip_table.ajax.reload();
                        alertify.success("Trip Deleted Successfully!");
                    } else {
                        alertify.error("Something Went Wrong!");
                    }
                }
            });
        } else {
            return false;
        }
    });
</script>
