<script>
    $("#party").select2();

    function party_change() {
        var party = $("#party").val();
    }


    function update_payment_account_id() {
        var party = $("#party").val();
        var table = $("#party").find(':selected').data('table');
        var paymentType = $('input[name="payment_type"]:checked').val();

        $("#party_table").val(table);

        if (paymentType === 'cash') {
            $('#payment_account_id').val(1); // ← Adjust as per your cash account ID
        } else if (paymentType === 'bank' && table === 'bank') {
            $('#payment_account_id').val(party); // ← Bank selected as party → use that bank's ID
        } else if (paymentType === 'bank') {
            // If not selecting bank as party, then user should select bank separately from a dropdown
            var bank_id = $("#all_bank").val(); // assuming this dropdown shows all banks
            $('#payment_account_id').val(bank_id);
        } else {
            $('#payment_account_id').val('');
        }

        console.log("payment_account_id =>", $('#payment_account_id').val());
    }
    $(document).on('change', '#party', function () {
        var table = $(this).find(':selected').data('table');
        $('#party_table').val(table);
    });

    $(document).on('change', '#party_table', function () {
        var table = $(this).val();
        var $party = $('#party');

        $party.empty(); // clear previous options

        if (table === 'cash') {
            $party.append('<option value="1" selected>کیش</option>');
            $party.prop('disabled', true); // disable selection for cash
        } else {
            $party.prop('disabled', false); // enable for others

            $.ajax({
                url: "/get-parties/" + table,
                type: "GET",
                success: function (response) {
                    $party.append('<option value="">منتخب کریں</option>');
                    $.each(response, function (index, party) {
                        $party.append(`<option value="${party.id}" data-table="${table}">${party.name || party.vehicle_no}</option>`);
                    });
                }
            });
        }

        update_payment_account_id(); // always update payment account
    });

    $(document).on('change', '#party', update_payment_account_id);

    $(document).on('change', 'input[name="payment_type"]', function () {
        update_payment_account_id();
    });

    $(document).on('change', '#u_party', function () {
        var party = $(this).val();
        var table = $(this).find(':selected').data('table');
        $("#party_table").val(table);
    });

    $(document).on('keypress', '.change_focus', function (e) {
        var next_id = $(this).data('id');
        if (e.which === 13) {
            e.preventDefault();
            document.getElementById(next_id).focus();
        }
    });

    $(document).on('change', '#select_account', function (e) {
        var account_category = $(this).find(':selected').data('id');
        $('#sender_party').attr('value', account_category);
    });

    $(document).on('change', '#all_bank', function (e) {
        var account_category = $(this).find(':selected').data('id');
        $('#sender_party').attr('value', account_category);
    });

    function payment_type_change(type, update = 'no')
    {
        if (type == 'in-account') {
            $("#bank_dev").html('');
            $.ajax({
                url: "{{ route('get_banks') }}",
                type: "POST",
                headers: { "X-CSRF-TOKEN": "{{ csrf_token() }}" },
                data: {
                    params: 'get_workshop',
                    req: 'payment_vouchers'
                },
                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);
                    }
                }
            });
        }

        update_payment_account_id(); // ← auto update hidden field
     }

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

    var driver_table = $("#driver_table").DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('payment_index') }}",
        columns: [
            { name: "DT_RowIndex", data: "DT_RowIndex", title: "#" },
            { name: "date", data: "date", title: "تاریخ" },
            { name: "payment_type", data: "payment_type", title: "ادائیگی کی قسم" },
            { name: "party", data: "party", title: "پارٹی" },
            { name: "amount", data: "amount", title: "رقم" },
            { name: "description", data: "description", title: "تفصیل" },
            { name: "action", data: "action", orderable: false, searchable: false, title: "عمل" }
        ]
    });

    $("#add_receipt_form").on('submit', function (e) {
        e.preventDefault();

        // ✅ Hidden fields ko manually set karo
        var selectedParty = $('#party').find(':selected');
        var table = selectedParty.data('table') || '';
        $('#party_table').val(table);

        update_payment_account_id(); // ← make sure this sets payment_account_id correctly

        let selectedBank = $("#all_bank").find(':selected');
        if (selectedBank.length && selectedBank.data('id')) {
            $('#sender_party').val(selectedBank.data('id'));
        }

        // ✅ FormData banany se pehle sari values set honi chahiye
        var formData = new FormData(this);

        $.ajax({
            url: "{{ route('payment_store') }}",
            type: "POST",
            contentType: false,
            processData: false,
            data: formData,
            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) {
                    driver_table.ajax.reload();
                    clear_fields();
                    alertify.success("Receipt Voucher Created Successfully!");
                    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();
            }
        });
    });

    $(document).on('click', '.edit_payment_voucher', function () {
        var edit_id = $(this).data('id');
        var url = "{{ route('payment_edit', ':id') }}".replace(':id', edit_id);
        $.ajax({
            url: url,
            type: "GET",
            success: function (resonpse) {
                $("#editVoucherData").html(resonpse);
                $("#editVoucherModal").modal('toggle');
                setTimeout(() => {
                    $('#u_date').focus();
                    $('#u_party').select2();
                    $('#all_bank').select2();
                }, 500);
            }
        });
    });

    $(document).on('submit', "#update_voucher_form", function (e) {
        e.preventDefault();
        $.ajax({
            url: "{{ route('payment_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) {
                    driver_table.ajax.reload();
                    $("#editVoucherModal").modal('hide');
                    alertify.success("Voucher Updated Successfully!");
                    setTimeout(() => {
                        document.getElementById('date').focus();
                    }, 300);
                } 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]);
                    });
                }
                setTimeout(() => {
                    $('#u_date').focus();
                    $('#u_party').select2();
                    $('#all_bank').select2();
                }, 500);
            }
        });
    });

    $(document).on('click', '.delete_voucher', function () {
        var del_id = $(this).data('id');
        var url = "{{ route('payment_delete', ':id') }}".replace(':id', del_id);
        if (confirm('Are You Sure To Delete The Payment Voucher?')) {
            $.ajax({
                url: url,
                type: "GET",
                success: function (response) {
                    if (response.success) {
                        driver_table.ajax.reload();
                        alertify.success("Voucher Deleted Successfully!");
                    } else {
                        alertify.error("Something Went Wrong!");
                    }
                }
            });
        }
    });
</script>

