@extends('layout.app')
@section('content')
    <div class="card">
        <div class="card-body">
            <div class="row">
                <div class="col-md-12">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4 class="mb-0">{{ $page_title ?? 'View Bank Account Information' }}</h4>
                        <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addBankModal">
                            <i class="fas fa-plus"></i> Add Bank
                        </button>
                    </div>
                    <hr>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="thead-dark">
                                <tr>
                                    <th scope="col">sl.</th>
                                    <th scope="col">Account Name</th>
                                    <th scope="col">Account No</th>
                                    <th scope="col">Bank Name</th>
                                    <th scope="col">Branch Name</th>
                                    <th scope="col">Opening Balance</th>
                                    <th scope="col">Balance</th>
                                    <th scope="col">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($bankings as $banking)
                                    <tr>
                                        <th>{{ $loop->index + 1 }}</th>
                                        <td>{{ $banking->account_name }}</td>
                                        <td>{{ $banking->account_no }}</td>
                                        <td>{{ $banking->bank_name }}</td>
                                        <td>{{ $banking->branch_name }}</td>
                                        <td>{{ $banking->opening_balance  }}</td>
                                        <td>{{ $banking->balance  }}</td>
                                        <td>
                                            <div role="group" aria-label="Bank actions">
                                                @if ($banking->action == 0)
                                                    <a href="{{ route('banking.approve', $banking->id) }}"
                                                       class="btn btn-outline-warning btn-sm mr-1"
                                                       title="Approve Account"
                                                       data-toggle="tooltip"
                                                       data-placement="top">
                                                        <i class="fas fa-times-circle"></i>
                                                    </a>
                                                @else
                                                    <button type="button"
                                                            class="btn btn-outline-success btn-sm mr-1"
                                                            disabled
                                                            title="Account Approved"
                                                            data-toggle="tooltip"
                                                            data-placement="top">
                                                        <i class="fas fa-check-circle"></i>
                                                    </button>
                                                @endif

                                                <button type="button"
                                                        class="btn btn-outline-primary btn-sm mr-1"
                                                        title="Edit Account"
                                                        data-toggle="tooltip"
                                                        data-placement="top"
                                                        onclick="openEditModal({{ $banking->id }})">
                                                    <i class="fas fa-edit"></i>
                                                </button>

                                                <button type="button"
                                                        class="btn btn-outline-success btn-sm mr-1"
                                                        title="Deposit Money"
                                                        data-toggle="tooltip"
                                                        data-placement="top"
                                                        onclick="openDepositModal({{ $banking->id }})">
                                                    <i class="fas fa-arrow-down"></i>
                                                </button>

                                                <button type="button"
                                                        class="btn btn-outline-warning btn-sm mr-1"
                                                        title="Withdraw Money"
                                                        data-toggle="tooltip"
                                                        data-placement="top"
                                                        onclick="openWithdrawModal({{ $banking->id }}, {{ $banking->balance }})">
                                                    <i class="fas fa-arrow-up"></i>
                                                </button>

                                                <form action="{{ route('banking.destroy', $banking->id) }}"
                                                      method="POST"
                                                      class="d-inline"
                                                      onsubmit="return confirm('Are you sure you want to delete this bank account?');">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit"
                                                            class="btn btn-outline-danger btn-sm"
                                                            title="Delete Account"
                                                            data-toggle="tooltip"
                                                            data-placement="top">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                        {{ $bankings->links() }}
                    </div>

                </div>
            </div>

        </div>
    </div>

    <!-- Add Bank Modal -->
    <div class="modal fade" id="addBankModal" tabindex="-1" role="dialog" aria-labelledby="addBankModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addBankModalLabel">
                        <i class="fas fa-university"></i> Add New Bank Account
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="addBankForm" action="{{ route('banking.store') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="account_name">Account's Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('account_name') is-invalid @enderror"
                                           name="account_name" id="account_name" placeholder="Account's Name"
                                           value="{{ old('account_name') }}" required>
                                    @error('account_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="account_no">Account No <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('account_no') is-invalid @enderror"
                                           name="account_no" id="account_no" placeholder="Account No"
                                           value="{{ old('account_no') }}" required>
                                    @error('account_no')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="bank_name">Bank Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('bank_name') is-invalid @enderror"
                                           name="bank_name" id="bank_name" placeholder="Bank Name"
                                           value="{{ old('bank_name') }}" required>
                                    @error('bank_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="branch_name">Branch Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('branch_name') is-invalid @enderror"
                                           name="branch_name" id="branch_name" placeholder="Branch Name"
                                           value="{{ old('branch_name') }}" required>
                                    @error('branch_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="status">Status <span class="text-danger">*</span></label>
                                    <select name="status" id="status" class="form-control @error('status') is-invalid @enderror" required>
                                        <option value="">Select Status</option>
                                        <option value="1" {{ old('status') == '1' ? 'selected' : '' }}>Active</option>
                                        <option value="0" {{ old('status') == '0' ? 'selected' : '' }}>Inactive</option>
                                    </select>
                                    @error('status')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="opening_balance">Opening Balance <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" class="form-control @error('opening_balance') is-invalid @enderror"
                                           name="opening_balance" id="opening_balance" placeholder="Opening Balance"
                                           value="{{ old('opening_balance') }}" required>
                                    @error('opening_balance')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Submit
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Bank Modal -->
    <div class="modal fade" id="editBankModal" tabindex="-1" role="dialog" aria-labelledby="editBankModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editBankModalLabel">
                        <i class="fas fa-edit"></i> Edit Bank Account
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="editBankForm" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_account_name">Account's Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('account_name') is-invalid @enderror"
                                           name="account_name" id="edit_account_name" placeholder="Account's Name"
                                           value="{{ old('account_name') }}" required>
                                    @error('account_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_account_no">Account No <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('account_no') is-invalid @enderror"
                                           name="account_no" id="edit_account_no" placeholder="Account No"
                                           value="{{ old('account_no') }}" required>
                                    @error('account_no')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_bank_name">Bank Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('bank_name') is-invalid @enderror"
                                           name="bank_name" id="edit_bank_name" placeholder="Bank Name"
                                           value="{{ old('bank_name') }}" required>
                                    @error('bank_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_branch_name">Branch Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('branch_name') is-invalid @enderror"
                                           name="branch_name" id="edit_branch_name" placeholder="Branch Name"
                                           value="{{ old('branch_name') }}" required>
                                    @error('branch_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_status">Status <span class="text-danger">*</span></label>
                                    <select name="status" id="edit_status" class="form-control @error('status') is-invalid @enderror" required>
                                        <option value="">Select Status</option>
                                        <option value="1">Active</option>
                                        <option value="0">Inactive</option>
                                    </select>
                                    @error('status')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_opening_balance">Opening Balance <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" class="form-control @error('opening_balance') is-invalid @enderror"
                                           name="opening_balance" id="edit_opening_balance" placeholder="Opening Balance"
                                           value="{{ old('opening_balance') }}" required>
                                    @error('opening_balance')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Deposit Money Modal -->
    <div class="modal fade" id="depositModal" tabindex="-1" role="dialog" aria-labelledby="depositModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="depositModalLabel">
                        <i class="fas fa-arrow-down"></i> Deposit Money
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="depositForm" action="{{ route('bank.store.diposit') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="deposit_account_id">Bank Account <span class="text-danger">*</span></label>
                                    <select name="account_id" id="deposit_account_id" class="form-control @error('account_id') is-invalid @enderror" required>
                                        <option value="">Select Bank Account</option>
                                        @foreach ($active_bank_accounts as $bank_account)
                                            <option value="{{ $bank_account->id }}">{{ $bank_account->account_name }} -- {{ $bank_account->bank_name }}</option>
                                        @endforeach
                                    </select>
                                    @error('account_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="deposit_amount">Amount <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" class="form-control @error('diposit_amount') is-invalid @enderror"
                                           name="diposit_amount" id="deposit_amount" placeholder="Amount"
                                           value="{{ old('diposit_amount') }}" required>
                                    @error('diposit_amount')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="deposit_by">Deposit By <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('by') is-invalid @enderror"
                                           name="by" id="deposit_by" placeholder="Deposit By"
                                           value="{{ old('by') }}" required>
                                    @error('by')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="deposit_description">Description</label>
                                    <textarea class="form-control @error('description') is-invalid @enderror"
                                              name="description" id="deposit_description" rows="4" placeholder="Description">{{ old('description') }}</textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save"></i> Submit
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Withdraw Money Modal -->
    <div class="modal fade" id="withdrawModal" tabindex="-1" role="dialog" aria-labelledby="withdrawModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="withdrawModalLabel">
                        <i class="fas fa-arrow-up"></i> Withdraw Money
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="withdrawForm" action="{{ route('bank.store.withdraw') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="withdraw_account_id">Bank Account <span class="text-danger">*</span></label>
                                    <select name="account_id" id="withdraw_account_id" class="form-control @error('account_id') is-invalid @enderror" required>
                                        <option value="">Select Bank Account</option>
                                        @foreach ($active_bank_accounts as $bank_account)
                                            <option value="{{ $bank_account->id }}">{{ $bank_account->account_name }} -- {{ $bank_account->bank_name }}</option>
                                        @endforeach
                                    </select>
                                    @error('account_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="withdraw_check_no">Check No</label>
                                    <input type="text" class="form-control @error('check_no') is-invalid @enderror"
                                           name="check_no" id="withdraw_check_no" placeholder="Check No"
                                           value="{{ old('check_no') }}">
                                    @error('check_no')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="withdraw_amount">Amount <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" class="form-control @error('withdraw_amount') is-invalid @enderror"
                                           name="withdraw_amount" id="withdraw_amount" placeholder="Amount"
                                           value="{{ old('withdraw_amount') }}" required>
                                    @error('withdraw_amount')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="form-text text-muted">
                                        Available Balance: <span id="available_balance" class="font-weight-bold text-success">0.00</span>
                                    </small>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="withdraw_by">Withdraw By <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('by') is-invalid @enderror"
                                           name="by" id="withdraw_by" placeholder="Withdraw By"
                                           value="{{ old('by') }}" required>
                                    @error('by')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="withdraw_description">Description</label>
                                    <textarea class="form-control @error('description') is-invalid @enderror"
                                              name="description" id="withdraw_description" rows="4" placeholder="Description">{{ old('description') }}</textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-warning">
                            <i class="fas fa-save"></i> Submit
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('js')
<script>
    // Base URLs for banking routes
    var bankingBaseUrl = '{{ url("admin/banking") }}';

    // Store account balances for quick access
    var accountBalances = {
        @foreach ($bankings as $banking)
        {{ $banking->id }}: {{ $banking->balance }},
        @endforeach
    };

    $(function () {
        $('[data-toggle="tooltip"]').tooltip();

        // Reset form when modal is closed
        $('#addBankModal').on('hidden.bs.modal', function () {
            $('#addBankForm')[0].reset();
            $('#addBankForm .is-invalid').removeClass('is-invalid');
            $('#addBankForm .invalid-feedback').remove();
        });

        // Reset edit form when modal is closed
        $('#editBankModal').on('hidden.bs.modal', function () {
            $('#editBankForm')[0].reset();
            $('#editBankForm .is-invalid').removeClass('is-invalid');
            $('#editBankForm .invalid-feedback').remove();
        });

        // Reset deposit form when modal is closed
        $('#depositModal').on('hidden.bs.modal', function () {
            $('#depositForm')[0].reset();
            $('#depositForm .is-invalid').removeClass('is-invalid');
            $('#depositForm .invalid-feedback').remove();
        });

        // Reset withdraw form when modal is closed
        $('#withdrawModal').on('hidden.bs.modal', function () {
            $('#withdrawForm')[0].reset();
            $('#withdrawForm .is-invalid').removeClass('is-invalid');
            $('#withdrawForm .invalid-feedback').remove();
            $('#available_balance').text('0.00');
        });

        // Handle form submission via AJAX for better UX
        $('#addBankForm').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var formData = form.serialize();
            var submitBtn = form.find('button[type="submit"]');
            var originalText = submitBtn.html();

            // Disable submit button
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                success: function(response) {
                    // Close modal
                    $('#addBankModal').modal('hide');
                    // Reload page to show new bank
                    location.reload();
                },
                error: function(xhr) {
                    // Re-enable submit button
                    submitBtn.prop('disabled', false).html(originalText);

                    if (xhr.status === 422) {
                        // Handle validation errors
                        var errors = xhr.responseJSON.errors;
                        form.find('.is-invalid').removeClass('is-invalid');
                        form.find('.invalid-feedback').remove();

                        $.each(errors, function(key, value) {
                            var input = form.find('[name="' + key + '"]');
                            input.addClass('is-invalid');
                            input.after('<div class="invalid-feedback">' + value[0] + '</div>');
                        });
                    } else {
                        alert('An error occurred. Please try again.');
                    }
                }
            });
        });

        // Handle edit form submission via AJAX
        $('#editBankForm').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var formData = form.serialize();
            var submitBtn = form.find('button[type="submit"]');
            var originalText = submitBtn.html();

            // Disable submit button
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Updating...');

            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                success: function(response) {
                    // Close modal
                    $('#editBankModal').modal('hide');
                    // Reload page to show updated bank
                    location.reload();
                },
                error: function(xhr) {
                    // Re-enable submit button
                    submitBtn.prop('disabled', false).html(originalText);

                    if (xhr.status === 422) {
                        // Handle validation errors
                        var errors = xhr.responseJSON.errors;
                        form.find('.is-invalid').removeClass('is-invalid');
                        form.find('.invalid-feedback').remove();

                        $.each(errors, function(key, value) {
                            var input = form.find('[name="' + key + '"]');
                            input.addClass('is-invalid');
                            input.after('<div class="invalid-feedback">' + value[0] + '</div>');
                        });
                    } else {
                        alert('An error occurred. Please try again.');
                    }
                }
            });
        });

        // Handle deposit form submission via AJAX
        $('#depositForm').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var formData = form.serialize();
            var submitBtn = form.find('button[type="submit"]');
            var originalText = submitBtn.html();

            // Disable submit button
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                success: function(response) {
                    // Close modal
                    $('#depositModal').modal('hide');
                    // Reload page to show updated balance
                    location.reload();
                },
                error: function(xhr) {
                    // Re-enable submit button
                    submitBtn.prop('disabled', false).html(originalText);

                    if (xhr.status === 422) {
                        // Handle validation errors
                        var errors = xhr.responseJSON.errors;
                        form.find('.is-invalid').removeClass('is-invalid');
                        form.find('.invalid-feedback').remove();

                        $.each(errors, function(key, value) {
                            var input = form.find('[name="' + key + '"]');
                            input.addClass('is-invalid');
                            input.after('<div class="invalid-feedback">' + value[0] + '</div>');
                        });
                    } else {
                        alert('An error occurred. Please try again.');
                    }
                }
            });
        });

        // Handle withdraw form submission via AJAX
        $('#withdrawForm').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var formData = form.serialize();
            var submitBtn = form.find('button[type="submit"]');
            var originalText = submitBtn.html();

            // Disable submit button
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                success: function(response) {
                    // Close modal
                    $('#withdrawModal').modal('hide');
                    // Reload page to show updated balance
                    location.reload();
                },
                error: function(xhr) {
                    // Re-enable submit button
                    submitBtn.prop('disabled', false).html(originalText);

                    if (xhr.status === 422) {
                        // Handle validation errors
                        var errors = xhr.responseJSON.errors;
                        form.find('.is-invalid').removeClass('is-invalid');
                        form.find('.invalid-feedback').remove();

                        $.each(errors, function(key, value) {
                            var input = form.find('[name="' + key + '"]');
                            input.addClass('is-invalid');
                            input.after('<div class="invalid-feedback">' + value[0] + '</div>');
                        });
                    } else if (xhr.status === 400) {
                        // Handle balance validation error
                        var errorMessage = xhr.responseJSON.message || 'Withdraw Amount is greater than Balance';
                        alert(errorMessage);
                    } else {
                        alert('An error occurred. Please try again.');
                    }
                }
            });
        });

        // Update available balance when account is selected
        $('#withdraw_account_id').on('change', function() {
            var accountId = $(this).val();
            if (accountId && accountBalances[accountId] !== undefined) {
                $('#available_balance').text(parseFloat(accountBalances[accountId]).toFixed(2));
            } else {
                $('#available_balance').text('0.00');
            }
        });
    });

    // Function to open deposit modal
    function openDepositModal(bankingId) {
        // Show modal
        $('#depositModal').modal('show');

        // Set the selected bank account
        $('#deposit_account_id').val(bankingId);
    }

    // Function to open withdraw modal
    function openWithdrawModal(bankingId, balance) {
        // Show modal
        $('#withdrawModal').modal('show');

        // Set the selected bank account
        $('#withdraw_account_id').val(bankingId);

        // Display available balance
        $('#available_balance').text(parseFloat(balance).toFixed(2));
    }

    // Function to open edit modal and fetch banking data
    function openEditModal(bankingId) {
        // Show loading state
        $('#editBankModal').modal('show');
        $('#editBankForm button[type="submit"]').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Loading...');

        // Fetch banking data
        $.ajax({
            url: bankingBaseUrl + '/' + bankingId + '/edit',
            type: 'GET',
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            success: function(response) {
                // Populate form fields
                $('#edit_account_name').val(response.account_name);
                $('#edit_account_no').val(response.account_no);
                $('#edit_bank_name').val(response.bank_name);
                $('#edit_branch_name').val(response.branch_name);
                $('#edit_status').val(response.status);
                $('#edit_opening_balance').val(response.opening_balance);

                // Set form action
                $('#editBankForm').attr('action', bankingBaseUrl + '/' + bankingId);

                // Re-enable submit button
                $('#editBankForm button[type="submit"]').prop('disabled', false).html('<i class="fas fa-save"></i> Update');
            },
            error: function(xhr) {
                $('#editBankModal').modal('hide');
                alert('Failed to load bank account data. Please try again.');
            }
        });
    }
</script>
@endpush
