@extends('layouts.admin')

@section('title', 'Accounting Report')

@section('page-title', 'Accounting Report')

@section('breadcrumbs')
    <a href="#" class="hover:text-primary">Reports</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Accounting Report</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Tabs -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6">
        <div class="border-b border-gray-200">
            <nav class="flex -mb-px">
                <button onclick="showTab('income')" id="tab-income" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-primary text-primary transition-colors">Income</button>
                <button onclick="showTab('expense')" id="tab-expense" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-primary transition-colors">Expense</button>
            </nav>
        </div>
    </div>

    <!-- Income Tab Content -->
    <div id="content-income" class="tab-content">
        <!-- Stats -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <p class="text-sm text-gray-500">Total Income</p>
                <p class="text-2xl font-bold text-green-600 mt-1" data-stat="total-income">{{ number_format($totalIncome ?? 0, 2) }}</p>
            </div>
        </div>

        <!-- Filter and Export -->
        <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
            <div class="flex flex-wrap gap-3">
                <input type="date" id="income-date-from" value="{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                <input type="date" id="income-date-to" value="{{ $dateTo ?? now()->format('Y-m-d') }}" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                <input type="text" id="income-search" placeholder="Search..." class="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/20 focus:border-primary">
                <button onclick="applyIncomeFilters()" class="px-4 h-10 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium">Filter</button>
                <button onclick="clearIncomeFilters()" class="px-4 h-10 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors text-sm font-medium">Clear</button>
            </div>
            <div class="flex gap-2">
                <button onclick="exportIncomeCsv()" class="flex items-center gap-2 px-4 h-10 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm font-medium">
                    <span class="material-symbols-outlined text-lg">description</span>
                    Export CSV
                </button>
                <button onclick="exportIncomePdf()" class="flex items-center gap-2 px-4 h-10 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium">
                    <span class="material-symbols-outlined text-lg">picture_as_pdf</span>
                    Export PDF
                </button>
            </div>
        </div>

        <!-- 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">
                    <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">Description</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Category</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">Amount</th>
                        </tr>
                    </thead>
                    <tbody id="income-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="5" 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 income data...</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Expense Tab Content -->
    <div id="content-expense" class="tab-content hidden">
        <!-- Stats -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <p class="text-sm text-gray-500">Total Expenses</p>
                <p class="text-2xl font-bold text-red-600 mt-1" data-stat="total-expenses">{{ number_format($totalExpenses ?? 0, 2) }}</p>
            </div>
        </div>

        <!-- Filter and Export -->
        <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
            <div class="flex flex-wrap gap-3">
                <input type="date" id="expense-date-from" value="{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                <input type="date" id="expense-date-to" value="{{ $dateTo ?? now()->format('Y-m-d') }}" class="h-10 px-4 rounded-lg border border-gray-200 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                <input type="text" id="expense-search" placeholder="Search..." class="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/20 focus:border-primary">
                <button onclick="applyExpenseFilters()" class="px-4 h-10 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-medium">Filter</button>
                <button onclick="clearExpenseFilters()" class="px-4 h-10 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors text-sm font-medium">Clear</button>
            </div>
            <div class="flex gap-2">
                <button onclick="exportExpenseCsv()" class="flex items-center gap-2 px-4 h-10 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm font-medium">
                    <span class="material-symbols-outlined text-lg">description</span>
                    Export CSV
                </button>
                <button onclick="exportExpensePdf()" class="flex items-center gap-2 px-4 h-10 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium">
                    <span class="material-symbols-outlined text-lg">picture_as_pdf</span>
                    Export PDF
                </button>
            </div>
        </div>

        <!-- 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">
                    <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">Description</th>
                            <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Category</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">Amount</th>
                        </tr>
                    </thead>
                    <tbody id="expense-tbody" class="divide-y divide-gray-100">
                        <tr>
                            <td colspan="5" 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 expense data...</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    let incomeFilters = {
        date_from: '{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}',
        date_to: '{{ $dateTo ?? now()->format('Y-m-d') }}',
        search: ''
    };

    let expenseFilters = {
        date_from: '{{ $dateFrom ?? now()->startOfMonth()->format('Y-m-d') }}',
        date_to: '{{ $dateTo ?? now()->format('Y-m-d') }}',
        search: ''
    };

    let incomeSearchTimeout;
    let expenseSearchTimeout;

    function showTab(tabName) {
        document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
        document.querySelectorAll('.tab-btn').forEach(el => {
            el.classList.remove('border-primary', 'text-primary');
            el.classList.add('border-transparent', 'text-gray-500');
        });
        document.getElementById('content-' + tabName).classList.remove('hidden');
        const activeTab = document.getElementById('tab-' + tabName);
        activeTab.classList.remove('border-transparent', 'text-gray-500');
        activeTab.classList.add('border-primary', 'text-primary');
        
        if (tabName === 'income') {
            loadIncomeData();
        } else if (tabName === 'expense') {
            loadExpenseData();
        }
    }

    // Income functions
    function applyIncomeFilters() {
        incomeFilters.date_from = document.getElementById('income-date-from').value;
        incomeFilters.date_to = document.getElementById('income-date-to').value;
        incomeFilters.search = document.getElementById('income-search').value.trim();
        loadIncomeData();
    }

    function clearIncomeFilters() {
        const startOfMonth = new Date();
        startOfMonth.setDate(1);
        document.getElementById('income-date-from').value = startOfMonth.toISOString().split('T')[0];
        document.getElementById('income-date-to').value = new Date().toISOString().split('T')[0];
        document.getElementById('income-search').value = '';
        applyIncomeFilters();
    }

    function loadIncomeData() {
        const tbody = document.getElementById('income-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="5" 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 income data...</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            date_from: incomeFilters.date_from,
            date_to: incomeFilters.date_to,
            search: incomeFilters.search
        });

        fetch('{{ route("admin.reports.accounting.income.api") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderIncomeData(data.data);
                document.querySelector('[data-stat="total-income"]').textContent = parseFloat(data.totalIncome || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
        })
        .catch(error => {
            console.error('Error:', error);
            tbody.innerHTML = '<tr><td colspan="5" class="py-12 px-6 text-center text-red-500">Error loading income data</td></tr>';
        });
    }

    function renderIncomeData(incomes) {
        const tbody = document.getElementById('income-tbody');
        if (incomes.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block">trending_up</span><p>No income data available</p></td></tr>';
            return;
        }

        let html = '';
        incomes.forEach((income, index) => {
            html += `
                <tr class="hover:bg-gray-50/50 transition-colors">
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${index + 1}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${income.description}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${income.category}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white whitespace-nowrap">${income.income_date}</td>
                    <td class="py-4 px-6 text-sm font-medium text-gray-900 bg-white text-right tabular-nums">${income.amount}</td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function exportIncomeCsv() {
        const params = new URLSearchParams({
            date_from: incomeFilters.date_from,
            date_to: incomeFilters.date_to,
            search: incomeFilters.search
        });
        window.location.href = '{{ route("admin.reports.accounting.income.export.csv") }}?' + params.toString();
    }

    function exportIncomePdf() {
        const params = new URLSearchParams({
            date_from: incomeFilters.date_from,
            date_to: incomeFilters.date_to,
            search: incomeFilters.search
        });
        window.location.href = '{{ route("admin.reports.accounting.income.export.pdf") }}?' + params.toString();
    }

    // Expense functions
    function applyExpenseFilters() {
        expenseFilters.date_from = document.getElementById('expense-date-from').value;
        expenseFilters.date_to = document.getElementById('expense-date-to').value;
        expenseFilters.search = document.getElementById('expense-search').value.trim();
        loadExpenseData();
    }

    function clearExpenseFilters() {
        const startOfMonth = new Date();
        startOfMonth.setDate(1);
        document.getElementById('expense-date-from').value = startOfMonth.toISOString().split('T')[0];
        document.getElementById('expense-date-to').value = new Date().toISOString().split('T')[0];
        document.getElementById('expense-search').value = '';
        applyExpenseFilters();
    }

    function loadExpenseData() {
        const tbody = document.getElementById('expense-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="5" 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 expense data...</p>
                    </div>
                </td>
            </tr>
        `;

        const params = new URLSearchParams({
            date_from: expenseFilters.date_from,
            date_to: expenseFilters.date_to,
            search: expenseFilters.search
        });

        fetch('{{ route("admin.reports.accounting.expense.api") }}?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderExpenseData(data.data);
                document.querySelector('[data-stat="total-expenses"]').textContent = parseFloat(data.totalExpenses || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
        })
        .catch(error => {
            console.error('Error:', error);
            tbody.innerHTML = '<tr><td colspan="5" class="py-12 px-6 text-center text-red-500">Error loading expense data</td></tr>';
        });
    }

    function renderExpenseData(expenses) {
        const tbody = document.getElementById('expense-tbody');
        if (expenses.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block">trending_down</span><p>No expense data available</p></td></tr>';
            return;
        }

        let html = '';
        expenses.forEach((expense, index) => {
            html += `
                <tr class="hover:bg-gray-50/50 transition-colors">
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${index + 1}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${expense.description}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white">${expense.category}</td>
                    <td class="py-4 px-6 text-sm text-gray-900 bg-white whitespace-nowrap">${expense.expense_date}</td>
                    <td class="py-4 px-6 text-sm font-medium text-gray-900 bg-white text-right tabular-nums">${expense.amount}</td>
                </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function exportExpenseCsv() {
        const params = new URLSearchParams({
            date_from: expenseFilters.date_from,
            date_to: expenseFilters.date_to,
            search: expenseFilters.search
        });
        window.location.href = '{{ route("admin.reports.accounting.expense.export.csv") }}?' + params.toString();
    }

    function exportExpensePdf() {
        const params = new URLSearchParams({
            date_from: expenseFilters.date_from,
            date_to: expenseFilters.date_to,
            search: expenseFilters.search
        });
        window.location.href = '{{ route("admin.reports.accounting.expense.export.pdf") }}?' + params.toString();
    }

    // Event listeners
    document.getElementById('income-search').addEventListener('input', function() {
        clearTimeout(incomeSearchTimeout);
        incomeSearchTimeout = setTimeout(() => applyIncomeFilters(), 500);
    });

    document.getElementById('expense-search').addEventListener('input', function() {
        clearTimeout(expenseSearchTimeout);
        expenseSearchTimeout = setTimeout(() => applyExpenseFilters(), 500);
    });

    // Auto-refresh every 30 seconds
    setInterval(() => {
        if (!document.getElementById('content-income').classList.contains('hidden')) {
            loadIncomeData();
        }
        if (!document.getElementById('content-expense').classList.contains('hidden')) {
            loadExpenseData();
        }
    }, 30000);

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




