<script>


function p_pump_payable_change(update = 'no') {
    var amount = $(document).find("#pump_payalbe_p :selected").data('amount');
        var id = $(document).find("#pump_payalbe_p :selected").data('id');
        var vehicleId = $(document).find("#pump_payalbe_p :selected").data('vehicle-id');
        var tripId = $(document).find("#pump_payalbe_p :selected").data('trip-id');

        $(document).find("#brokerAdvance_id_hidden").val(id);
        $(document).find("#vehicle_id_hidden").val(vehicleId);
        $(document).find("#trip_id_hidden").val(tripId);
        $(document).find("#payable_hidden_total_amount").val(amount);
        $(document).find("#amount").val(amount);
    }




    $(document).ready(function () {
    // Function to get and log selected party and vehicle IDs
    function getVehicleAndParty() {
        // Get selected party ID and name
        var partyId = $('#party').val();
        var partyName = $('#party option:selected').text();

        // Get selected vehicle ID and name
        // var vehicleId = $('#trip').val();
        // var vehicleName = $('#trip option:selected').text();

        // Log the selected values
        console.log('Party ID:', partyId, 'Party Name:', partyName);
        // console.log('Vehicle ID:', vehicleId, 'Vehicle Name:', vehicleName);

        // Example AJAX call to send data to the server
        $.ajax({
                url: "{{ route('get_broker_advance_amount') }}",
                type: "POST",
                data: {
                    'party_id': partyId,

                },
                headers: {
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                success: function (response) {
                    console.log(response);
                    $(document).find("#broker_advance_dev").html(response);
                    setTimeout(() => {
                        $(document).find("#pump_payalbe_p").select2();

                    }, 500);
                }
            });
            // $(document).find("#payable_party_type").val(table);
    }

    // Trigger function on dropdown change
    $('#party').change(function () {
        getVehicleAndParty();
    });
});

function payment_type_change(type, update = 'no') {


if(type=='in-account'){
    $("#bank_dev").html('');
    var dataId = $(this).find(':selected').data('id');

$.ajax({
        url: "{{ route('get_banks') }}",
        type: "POST",
        headers: {
            "X-CSRF-TOKEN": "{{ csrf_token() }}"
        },
        data: {
            params:'get_workshop',
            req:'payment_vouchers' // Ensure `get_workshop` is a valid variable or replace with actual value
        },
        success: function (data) {
            $("#workshop_div").html(data);
            setTimeout(() => {
                    $(document).find("#select_account").select2({
                        tags: true
                    });
                }, 200);
        }
    });
return false;
}

if (type == 'cash') {
    $("#bank_dev").html('');
    $("#workshop_div").html('');

    $(document).find("#u_bank_dev").html('');
} else {

    $("#workshop_div").html('');
    $.ajax({
        url: "{{ route('get_banks') }}",
        type: "POST",
        headers: {
            "X-CSRF-TOKEN": "{{ csrf_token() }}"
        },
        success: function (data) {
            if (update == 'yes') {
                $(document).find("#u_bank_dev").html(data);
                setTimeout(() => {
                    $(document).find("#all_bank").select2();
                }, 200);
            } else {
                $("#bank_dev").html(data);
                setTimeout(() => {
                    $(document).find("#all_bank").select2({
                        tags: true
                    });
                }, 200);
            }
        }
    });
}
}


$("#add_broker_advance_form").on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('broker_advance_store') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: new FormData(this),
            beforeSend: function () {
                $(".error").text('');
                $("#submit_btn").text('Processing....');
                $("#submit_btn").prop('disabled', true);
            },
            success: function (data) {
                $("#submit_btn").text('محفوظ');
                $("#submit_btn").prop('disabled', false);
                if (data.success) {
                    alertify.success("Broker Advance Created Successfully!");
                    location.reload();
                    clear_fields();
                    setTimeout(() => {
                        document.getElementById('date').focus();
                    }, 400);
                } else {
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (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]);
                    });
                }
                $('#date').focus();

            }
        });
    });


    var driver_table = $("#driver_table").DataTable({
    processing: true,
    serverSide: true,
    ajax: "{{ route('broker_advance_index') }}",
    columns: [{
            name: "DT_RowIndex",
            data: "DT_RowIndex"
        },
        {
            name: "date",
            data: "date"
        },
        {
            name: "sender", // This is now the correct sender column
            data: "sender"
        },
        {
            name: "amount_sender", // Amount for sender (deducted)
            data: "amount_sender"
        },
        {
            name: "receiver", // This is the receiver column
            data: "receiver"
        },
        {
            name: "amount_receiver", // Amount for receiver (added)
            data: "amount_receiver"
        },
        {
            name: "action",
            data: "action",
            orderable: false,
        },
    ]
});




function clear_fields() {
        $("#add_receipt_form")[0].reset();
        $(".error").text('');
        $("#bank_dev").html('');
        $("#workshop_div").html('');

    }


    $(document).on('click', '.broker_advance_edit', function () {
        var edit_id = $(this).data('id');
        var url = "{{ route('broker_advance_edit', ':id') }}";
        url = url.replace(':id', edit_id);
        $.ajax({
            url: url,
            type: "GET",
            success: function (resonpse) {
                // console.log(resonpse);
                $("#editBrokerAdvanceData").html(resonpse);
                $("#editBrokerAdvanceModal").modal('toggle');
                setTimeout(() => {
                    $(document).find('#u_date').focus();
                    $(document).find('#u_broker').select2();
                    $(document).find('#all_bank').select2();

                }, 500);
            }
        });
    });


    $(document).on('submit', "#update_broker_advance_form", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('broker_advance_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');
                $("#update_btn").prop('disabled', false);
                if (data.success) {
                    location.reload();
                    $("#editVoucherModal").modal('hide');
                    alertify.success("Broker Advance Update Successfully!");
                    setTimeout(() => {
                        document.getElementById('date').focus();
                    }, 300);
                } else {
                    alertify.error("Something Went Wrong!");
                }
            },
            error: function (error) {
                $("#update_btn").text('Update');
                $("#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]);
                    });
                }
                setTimeout(() => {
                    $(document).find('#u_date').focus();
                    $(document).find('#u_broker').select2();
                    $(document).find('#all_bank').select2();

                }, 500);
            }
        });
    });


    $(document).on('click', '.delete_broker_advance', function () {
        var del_id = $(this).data('id');
        var url = "{{ route('delete_broker_advance', ':id') }}";
        url = url.replace(':id', del_id);
        if (confirm('Are You Sure To Delete The Broker Advance?')) {
            $.ajax({
                url: url,
                type: "GET",
                success: function (response) {
                    if (response.success) {
                        location.reload();
                        alertify.success("Broker Advance Deleted Successfully!");
                        setTimeout(() => {
                            document.getElementById('date').focus();
                        }, 300);
                    } else {
                        alertify.error("Something Went Wrong!");
                    }
                }
            });
        } else {
            return false;
        }
    });

</script>
