@extends('layouts.admin')

@section('title', 'Bank Transactions')

@section('page-title', 'Bank Transactions')

@section('breadcrumbs')
    <a href="{{ route('admin.banking.overview') }}" class="hover:text-primary">Banking Overview</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Transactions</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Bank Transactions</h1>
        <select id="per-page-select" class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
            <option value="10">10 / page</option>
            <option value="25" selected>25 / page</option>
            <option value="50">50 / page</option>
            <option value="100">100 / page</option>
        </select>
    </div>

    <!-- Filters -->
    <div class="flex flex-col sm:flex-row gap-4 mb-4">
        <input type="text" id="search-input" placeholder="Search transactions..." class="flex-1 max-w-md h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
        <select id="account-filter" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
            <option value="">All Accounts</option>
            @foreach($bankAccounts as $account)
                <option value="{{ $account->id }}">{{ $account->bank_name }} - {{ $account->account_name }}</option>
            @endforeach
        </select>
        <input type="date" id="date-from" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-1 focus:ring-primary">
        <input type="date" id="date-to" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-1 focus:ring-primary">
        <button type="button" id="apply-filters" class="px-4 py-2 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600 transition-colors">
            Apply
        </button>
        <button type="button" id="clear-filters" class="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
            Clear
        </button>
    </div>

    <!-- Export (uses same filters as the table) -->
    <div class="flex flex-wrap items-center gap-2 mb-4" role="toolbar" aria-label="Export transactions">
        <button type="button" id="export-bank-txn-pdf" class="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold rounded-lg border border-gray-200 bg-white text-gray-800 hover:bg-gray-50 hover:border-gray-300 transition-colors shadow-sm">
            <span class="material-symbols-outlined text-[20px] text-red-600">picture_as_pdf</span>
            Export PDF
        </button>
        <button type="button" id="export-bank-txn-csv" class="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold rounded-lg border border-gray-200 bg-white text-gray-800 hover:bg-gray-50 hover:border-gray-300 transition-colors shadow-sm">
            <span class="material-symbols-outlined text-[20px] text-emerald-600">table_rows</span>
            Export CSV
        </button>
    </div>

    <!-- Report summary (all rows matching filters, not only this page) -->
    <div id="txn-summary" class="mb-4 hidden grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div class="bg-white rounded-xl border border-gray-200 p-4 shadow-sm">
            <p class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Total in (credits)</p>
            <p id="summary-credit" class="text-lg font-bold text-emerald-700 tabular-nums mt-1">—</p>
        </div>
        <div class="bg-white rounded-xl border border-gray-200 p-4 shadow-sm">
            <p class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Total out (debits)</p>
            <p id="summary-debit" class="text-lg font-bold text-rose-700 tabular-nums mt-1">—</p>
        </div>
        <div class="bg-white rounded-xl border border-gray-200 p-4 shadow-sm">
            <p class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Net</p>
            <p id="summary-net" class="text-lg font-bold text-gray-900 tabular-nums mt-1">—</p>
            <p id="summary-note" class="text-xs text-gray-500 mt-2"></p>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Date</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Bank Account</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Description</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Source</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Type</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">Amount</th>
                    </tr>
                </thead>
                <tbody id="transactions-tbody" class="divide-y divide-gray-100">
                    <tr>
                        <td colspan="7" class="py-12 px-6 text-center text-gray-500">
                            <div class="flex flex-col items-center">
                                <svg class="animate-spin h-8 w-8 text-primary mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                                <p>Loading transactions...</p>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div id="pagination-container" class="px-6 py-4 border-t border-gray-200 hidden">
            <!-- Pagination will be inserted here -->
        </div>
    </div>
</div>

@push('scripts')
<script>
let currentPage = 1;
let perPage = 25;
let searchTimeout;
let abortController = null;

// Format currency
function formatCurrency(amount, currency = 'USD') {
    const formatted = parseFloat(amount || 0).toFixed(2);
    return currency + ' ' + formatted;
}

// Format date
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}

// Load transactions
function loadTransactions() {
    // Cancel previous request if any
    if (abortController) {
        abortController.abort();
    }
    abortController = new AbortController();

    const search = document.getElementById('search-input').value.trim();
    const accountId = document.getElementById('account-filter').value;
    const dateFrom = document.getElementById('date-from').value;
    const dateTo = document.getElementById('date-to').value;

    // Show loading state
    const tbody = document.getElementById('transactions-tbody');
    tbody.innerHTML = `
        <tr>
            <td colspan="7" class="py-12 px-6 text-center text-gray-500">
                <div class="flex flex-col items-center">
                    <svg class="animate-spin h-8 w-8 text-primary mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p>Loading transactions...</p>
                </div>
            </td>
        </tr>
    `;

    // Build query params
    const params = new URLSearchParams({
        page: currentPage,
        per_page: perPage,
    });

    if (search) params.append('search', search);
    if (accountId) params.append('bank_account_id', accountId);
    if (dateFrom) params.append('date_from', dateFrom);
    if (dateTo) params.append('date_to', dateTo);

    fetch('{{ route("admin.banking.transactions.api") }}?' + params.toString(), {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        signal: abortController.signal,
        credentials: 'same-origin'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Request failed');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            renderSummary(data.summary);
            renderTransactions(data.transactions);
            renderPagination(data.pagination);
        } else {
            showError(data.message || 'Error loading transactions');
        }
    })
    .catch(error => {
        if (error.name !== 'AbortError') {
            console.error('Error:', error);
            showError('Error loading transactions');
        }
    });
}

function renderSummary(summary) {
    const box = document.getElementById('txn-summary');
    if (!box || !summary) {
        return;
    }
    box.classList.remove('hidden');
    const cur = summary.currency_hint || 'USD';
    document.getElementById('summary-credit').textContent = formatCurrency(summary.total_credit, cur);
    document.getElementById('summary-debit').textContent = formatCurrency(summary.total_debit, cur);
    document.getElementById('summary-net').textContent = formatCurrency(summary.net, cur);
    const noteEl = document.getElementById('summary-note');
    if (noteEl) {
        noteEl.textContent = summary.note || '';
    }
}

// Render transactions
function renderTransactions(transactions) {
    const tbody = document.getElementById('transactions-tbody');

    if (transactions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="py-12 px-6 text-center text-gray-500">
                    <span class="material-symbols-outlined text-4xl mb-2 block">receipt_long</span>
                    <p>No transactions found</p>
                </td>
            </tr>
        `;
        return;
    }

    let html = '';
    transactions.forEach((transaction, index) => {
        const rowNumber = (currentPage - 1) * perPage + index + 1;
        const typeClass = transaction.type === 'credit'
            ? 'bg-emerald-600 text-white border-emerald-700 shadow-sm ring-1 ring-emerald-500/40'
            : 'bg-red-600 text-white border-red-700 shadow-sm ring-1 ring-red-500/50';
        const typeIcon = transaction.type === 'credit' ? 'south_west' : 'north_east';
        const typeLabel = transaction.type === 'credit' ? 'Credit' : 'Debit';

        html += `
            <tr class="hover:bg-gray-50/50 transition-colors group">
                <td class="py-4 px-6 text-sm text-gray-600">${rowNumber}</td>
                <td class="py-4 px-6 text-sm text-gray-600 whitespace-nowrap">${formatDate(transaction.transaction_date)}</td>
                <td class="py-4 px-6 text-sm text-gray-600">
                    ${transaction.bank_account_name || '-'}
                </td>
                <td class="py-4 px-6 text-sm text-gray-900">
                    <div class="font-medium">${transaction.description || '-'}</div>
                    ${transaction.reference_number ? `<div class="text-xs text-gray-500 mt-1">Ref: ${transaction.reference_number}</div>` : ''}
                    ${transaction.related_party ? `<div class="text-xs text-gray-500">${transaction.related_party}</div>` : ''}
                </td>
                <td class="py-4 px-6 text-sm text-gray-700">
                    <span class="text-xs font-medium text-gray-600">${transaction.source_label || '-'}</span>
                </td>
                <td class="py-4 px-6">
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold border ${typeClass}">
                        <span class="material-symbols-outlined text-[15px] leading-none">${typeIcon}</span>
                        ${typeLabel}
                    </span>
                </td>
                <td class="py-4 px-6 text-sm font-medium text-gray-900 text-right tabular-nums">
                    ${formatCurrency(transaction.amount, transaction.currency || 'USD')}
                </td>
            </tr>
        `;
    });

    tbody.innerHTML = html;
}

// Render pagination
function renderPagination(pagination) {
    const container = document.getElementById('pagination-container');
    
    if (!pagination || pagination.last_page <= 1) {
        container.classList.add('hidden');
        return;
    }

    container.classList.remove('hidden');

    let html = '<div class="flex flex-col sm:flex-row items-center justify-between gap-4">';
    html += `<p class="text-sm text-gray-500">
        Showing <span class="font-medium text-gray-900">${((pagination.current_page - 1) * pagination.per_page) + 1}</span> 
        to <span class="font-medium text-gray-900">${Math.min(pagination.current_page * pagination.per_page, pagination.total)}</span> 
        of <span class="font-medium text-gray-900">${pagination.total}</span> entries
    </p>`;

    html += '<div class="flex items-center gap-1">';

    // Previous button
    if (pagination.current_page > 1) {
        html += `<button onclick="goToPage(${pagination.current_page - 1})" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 transition-colors">
            <
        </button>`;
    } else {
        html += `<button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
            <
        </button>`;
    }

    // Page numbers
    const startPage = Math.max(1, pagination.current_page - 1);
    const endPage = Math.min(pagination.last_page, pagination.current_page + 1);

    if (startPage > 1) {
        html += `<button onclick="goToPage(1)" class="size-8 text-sm font-medium rounded text-gray-600 hover:bg-gray-50 flex items-center justify-center">1</button>`;
        if (startPage > 2) {
            html += `<span class="px-2 text-gray-400">...</span>`;
        }
    }

    for (let page = startPage; page <= endPage; page++) {
        const isActive = page === pagination.current_page;
        html += `<button onclick="goToPage(${page})" class="size-8 text-sm font-medium rounded ${isActive ? 'bg-primary text-white' : 'text-gray-600 hover:bg-gray-50'} flex items-center justify-center">
            ${page}
        </button>`;
    }

    if (endPage < pagination.last_page) {
        if (endPage < pagination.last_page - 1) {
            html += `<span class="px-2 text-gray-400">...</span>`;
        }
        html += `<button onclick="goToPage(${pagination.last_page})" class="size-8 text-sm font-medium rounded text-gray-600 hover:bg-gray-50 flex items-center justify-center">
            ${pagination.last_page}
        </button>`;
    }

    // Next button
    if (pagination.current_page < pagination.last_page) {
        html += `<button onclick="goToPage(${pagination.current_page + 1})" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 transition-colors">
            >
        </button>`;
    } else {
        html += `<button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
            >
        </button>`;
    }

    html += '</div></div>';
    container.innerHTML = html;
}

// Go to page
function goToPage(page) {
    currentPage = page;
    loadTransactions();
}

// Show error
function showError(message) {
    const sum = document.getElementById('txn-summary');
    if (sum) sum.classList.add('hidden');
    const tbody = document.getElementById('transactions-tbody');
    tbody.innerHTML = `
        <tr>
            <td colspan="7" class="py-12 px-6 text-center text-red-500">
                <span class="material-symbols-outlined text-4xl mb-2 block">error</span>
                <p>${message}</p>
            </td>
        </tr>
    `;
}

// Event listeners
document.getElementById('search-input').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    currentPage = 1;
    searchTimeout = setTimeout(() => loadTransactions(), 500);
});

document.getElementById('account-filter').addEventListener('change', function() {
    currentPage = 1;
    loadTransactions();
});

document.getElementById('date-from').addEventListener('change', function() {
    currentPage = 1;
    loadTransactions();
});

document.getElementById('date-to').addEventListener('change', function() {
    currentPage = 1;
    loadTransactions();
});

document.getElementById('per-page-select').addEventListener('change', function() {
    perPage = parseInt(this.value);
    currentPage = 1;
    loadTransactions();
});

document.getElementById('clear-filters').addEventListener('click', function() {
    document.getElementById('search-input').value = '';
    document.getElementById('account-filter').value = '';
    document.getElementById('date-from').value = '';
    document.getElementById('date-to').value = '';
    currentPage = 1;
    loadTransactions();
});

document.getElementById('apply-filters').addEventListener('click', function() {
    currentPage = 1;
    loadTransactions();
});

const bankTxnExportPdfUrl = @json(route('admin.banking.transactions.export.pdf'));
const bankTxnExportCsvUrl = @json(route('admin.banking.transactions.export.csv'));

function bankTransactionsExportUrl(base) {
    const params = new URLSearchParams();
    const search = document.getElementById('search-input').value.trim();
    const accountId = document.getElementById('account-filter').value;
    const dateFrom = document.getElementById('date-from').value;
    const dateTo = document.getElementById('date-to').value;
    if (search) params.append('search', search);
    if (accountId) params.append('bank_account_id', accountId);
    if (dateFrom) params.append('date_from', dateFrom);
    if (dateTo) params.append('date_to', dateTo);
    const q = params.toString();
    return q ? base + (base.indexOf('?') >= 0 ? '&' : '?') + q : base;
}

document.getElementById('export-bank-txn-pdf').addEventListener('click', function () {
    window.location.href = bankTransactionsExportUrl(bankTxnExportPdfUrl);
});
document.getElementById('export-bank-txn-csv').addEventListener('click', function () {
    window.location.href = bankTransactionsExportUrl(bankTxnExportCsvUrl);
});

// Load transactions on page load
document.addEventListener('DOMContentLoaded', function() {
    loadTransactions();
});
</script>
@endpush
@endsection
