@extends('layout.app')
@section('content')

<div class="card">
    <div class="card-body">
        <h4 class="">Transaction Information</h4>
        <hr>

        <!-- Total Transaction Summary -->
        <div class="row mb-3">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-0">Total Turnover</h6>
                                <h3 class="mb-0 mt-2">{{ number_format($totalDeposits + $totalWithdrawals, 2) }} TK</h3>
                            </div>
                            <div>
                                <i class="fa fa-list fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-0">Total Deposits</h6>
                                <h3 class="mb-0 mt-2">{{ number_format($totalDeposits, 2) }} TK</h3>
                            </div>
                            <div>
                                <i class="fa fa-arrow-down fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-0">Total Withdrawals</h6>
                                <h3 class="mb-0 mt-2">{{ number_format($totalWithdrawals, 2) }} TK</h3>
                            </div>
                            <div>
                                <i class="fa fa-arrow-up fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card {{ $netBalance >= 0 ? 'bg-info' : 'bg-warning' }} text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-0">Net Balance</h6>
                                <h3 class="mb-0 mt-2">{{ number_format($netBalance, 2) }} TK</h3>
                            </div>
                            <div>
                                <i class="fa fa-balance-scale fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <hr>

        <form method="GET" action="{{ route('bank.index') }}" class="mb-3">
            <div class="form-row">
                <div class="col-md-4 mb-2">
                    <div class="input-group">
                        <select name="filter_by" class="custom-select" style="max-width: 45%;">
                            <option value="" {{ request('filter_by') == '' ? 'selected' : '' }}>All</option>
                            <option value="account_name" {{ request('filter_by') == 'account_name' ? 'selected' : '' }}>Account Name</option>
                            <option value="account_no" {{ request('filter_by') == 'account_no' ? 'selected' : '' }}>Account No</option>
                            <option value="bank_name" {{ request('filter_by') == 'bank_name' ? 'selected' : '' }}>Bank Name</option>
                            <option value="branch_name" {{ request('filter_by') == 'branch_name' ? 'selected' : '' }}>Branch Name</option>
                            <option value="description" {{ request('filter_by') == 'description' ? 'selected' : '' }}>Description</option>
                            <option value="by" {{ request('filter_by') == 'by' ? 'selected' : '' }}>Deposit/Withdraw By</option>
                            <option value="check_no" {{ request('filter_by') == 'check_no' ? 'selected' : '' }}>Check No</option>
                        </select>
                        <input type="text" name="search" class="form-control" placeholder="Search"
                            value="{{ request('search') }}">
                    </div>
                </div>
                <div class="col-md-3 mb-2">
                    <input type="date" name="date_from" class="form-control" placeholder="From date"
                        value="{{ request('date_from') }}">
                </div>
                <div class="col-md-3 mb-2">
                    <input type="date" name="date_to" class="form-control" placeholder="To date"
                        value="{{ request('date_to') }}">
                </div>
                <div class="col-md-2 mb-2 d-flex justify-content-end">
                    <button type="submit" class="btn btn-primary btn-sm mr-1" title="Search">
                        <i class="fa fa-search"></i>
                    </button>
                    <a href="{{ route('bank.index') }}" class="btn btn-secondary btn-sm mr-1" title="Reset">
                        <i class="fa fa-times"></i>
                    </a>
                    <a href="{{ route('bank.export.excel', request()->query()) }}" class="btn btn-success btn-sm mr-1" title="Download Excel">
                        <i class="fa fa-file-excel"></i>
                    </a>
                    <a href="{{ route('bank.export.pdf', request()->query()) }}" class="btn btn-danger btn-sm" title="Download PDF">
                        <i class="fa fa-file-pdf"></i>
                    </a>
                </div>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Date</th>
                        <th scope="col">Account Name</th>
                        <th scope="col">Account No</th>
                        <th scope="col">Check No</th>
                        <th scope="col">Bank Name</th>
                        <th scope="col">Branch Name</th>
                        <th scope="col">Discription</th>
                        <th scope="col">Deposit/Withdraw By</th>
                        <th scope="col">Diposit Amount(TK)</th>
                        <th scope="col">Withdraw Amount(TK)</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($bank_transfar as $transfar)
                        <tr>
                            <th>{{ $loop->iteration }}</th>
                            <th>{{ $transfar->created_at->format('d-m-Y') }}</th>
                            <td>{{ $transfar->bank->account_name ?? 'N/A' }}</td>
                            <td>{{ $transfar->bank->account_no ?? 'N/A' }}</td>
                            <td>{{ $transfar->check_no ?? '-' }}</td>
                            <td>{{ $transfar->bank->bank_name ?? 'N/A' }}</td>
                            <td>{{ $transfar->bank->branch_name ?? 'N/A' }}</td>
                            <td>{{ $transfar->description ?? '-' }}</td>
                            <td>{{ $transfar->by ?? '-' }}</td>
                            <td>{{ $transfar->diposit_amount ?? '0.00' }}</td>
                            <td>{{ $transfar->withdraw_amount ?? '0.00' }}</td>
                            <td class="text-center">
                                <div class="btn-group" role="group" aria-label="Basic example">
                                    {{-- @if ($transfar->status == 0)
                                        <a href="{{ route('bank.approve', $transfar->id) }}" class="btn btn-warning btn-sm">Disapproved</a>
                                    @else
                                        <button type="button" class="btn btn-success btn-sm">Approved</button>
                                    @endif --}}

                                    <button type="button"
                                            class="btn btn-outline-primary btn-sm mr-1"
                                            title="Edit"
                                            onclick="openEditTransactionModal({{ $transfar->id }})">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <form action="{{ route('bank.delete', $transfar->id) }}" method="POST" style="display:inline-block;">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" onclick="return confirm('Are you sure you want to delete this item?')" class="btn btn-outline-danger btn-sm" title="Delete">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
            {{ $bank_transfar->links() }}
        </div>
    </div>
</div>

<!-- Edit Deposit Transaction Modal -->
<div class="modal fade" id="editDepositModal" tabindex="-1" role="dialog" aria-labelledby="editDepositModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editDepositModalLabel">
                    <i class="fas fa-edit"></i> Edit Deposit Transaction
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="editDepositForm" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="edit_deposit_account_id">Bank Account <span class="text-danger">*</span></label>
                                <select name="account_id" id="edit_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="edit_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="edit_deposit_amount" placeholder="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="edit_deposit_by">Deposit By <span class="text-danger">*</span></label>
                                <input type="text" class="form-control @error('by') is-invalid @enderror"
                                       name="by" id="edit_deposit_by" placeholder="Deposit 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="edit_deposit_description">Description</label>
                                <textarea class="form-control @error('description') is-invalid @enderror"
                                          name="description" id="edit_deposit_description" rows="4" placeholder="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-primary">
                        <i class="fas fa-save"></i> Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Withdraw Transaction Modal -->
<div class="modal fade" id="editWithdrawModal" tabindex="-1" role="dialog" aria-labelledby="editWithdrawModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editWithdrawModalLabel">
                    <i class="fas fa-edit"></i> Edit Withdraw Transaction
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="editWithdrawForm" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="edit_withdraw_account_id">Bank Account <span class="text-danger">*</span></label>
                                <select name="account_id" id="edit_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="edit_withdraw_check_no">Check No</label>
                                <input type="text" class="form-control @error('check_no') is-invalid @enderror"
                                       name="check_no" id="edit_withdraw_check_no" placeholder="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="edit_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="edit_withdraw_amount" placeholder="Amount"
                                       required>
                                @error('withdraw_amount')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="edit_withdraw_by">Withdraw By <span class="text-danger">*</span></label>
                                <input type="text" class="form-control @error('by') is-invalid @enderror"
                                       name="by" id="edit_withdraw_by" placeholder="Withdraw 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="edit_withdraw_description">Description</label>
                                <textarea class="form-control @error('description') is-invalid @enderror"
                                          name="description" id="edit_withdraw_description" rows="4" placeholder="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> Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('js')
<script>
    var bankTransfarBaseUrl = '{{ url("admin/bank/transfar") }}';

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

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

        // Handle deposit edit form submission via AJAX
        $('#editDepositForm').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
                    $('#editDepositModal').modal('hide');
                    // Reload page to show updated data
                    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 edit form submission via AJAX
        $('#editWithdrawForm').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
                    $('#editWithdrawModal').modal('hide');
                    // Reload page to show updated data
                    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.');
                    }
                }
            });
        });
    });

    // Function to open edit transaction modal
    function openEditTransactionModal(transactionId) {
        // Fetch transaction data
        $.ajax({
            url: bankTransfarBaseUrl + '/' + transactionId + '/edit',
            type: 'GET',
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            beforeSend: function() {
                // Show loading indicator if needed
            },
            success: function(response) {
                if (response.type === 'deposit') {
                    // Populate deposit form
                    $('#edit_deposit_account_id').val(response.account_id);
                    $('#edit_deposit_amount').val(response.diposit_amount);
                    $('#edit_deposit_by').val(response.by);
                    $('#edit_deposit_description').val(response.description || '');

                    // Set form action
                    $('#editDepositForm').attr('action', bankTransfarBaseUrl + '/' + response.id + '/dipositupdate');

                    // Show deposit modal
                    $('#editDepositModal').modal('show');
                } else {
                    // Populate withdraw form
                    $('#edit_withdraw_account_id').val(response.account_id);
                    $('#edit_withdraw_check_no').val(response.check_no || '');
                    $('#edit_withdraw_amount').val(response.withdraw_amount);
                    $('#edit_withdraw_by').val(response.by);
                    $('#edit_withdraw_description').val(response.description || '');

                    // Set form action
                    $('#editWithdrawForm').attr('action', bankTransfarBaseUrl + '/' + response.id + '/withdrawupdate');

                    // Show withdraw modal
                    $('#editWithdrawModal').modal('show');
                }
            },
            error: function(xhr) {
                alert('Failed to load transaction data. Please try again.');
            }
        });
    }
</script>
@endpush
