@extends('layouts.admin')

@section('content')
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Expense Report</h5>
                    <button type="button" class="btn btn-danger btn-sm" onclick="window.print()">
                        <i class="fas fa-print me-1"></i> Print
                    </button>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-4 no-print">
                        <div class="col-md-4">
                            <label class="form-label">Start Date</label>
                            <input type="date" id="start_date" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">End Date</label>
                            <input type="date" id="end_date" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Category</label>
                            <select id="category_id" class="form-select">
                                <option value="">All Categories</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card bg-danger text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Total Expenses</h6>
                                    <h2 class="mb-0" id="total_expenses">$0.00</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-info text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Average Monthly Expense</h6>
                                    <h2 class="mb-0" id="avg_monthly">$0.00</h2>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-body">
                            <canvas id="expenseChart" height="300"></canvas>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Category</th>
                                    <th>Description</th>
                                    <th>Reference</th>
                                    <th class="text-end">Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody id="expense_data">
                                <tr>
                                    <td colspan="6" class="text-center">Select date range to view expense data</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    let expenseChart;

    function loadExpenseData() {
        const startDate = $('#start_date').val();
        const endDate = $('#end_date').val();
        const categoryId = $('#category_id').val();

        if (!startDate || !endDate) return;

        $.ajax({
            url: '{{ route("admin.reports.expenses.data") }}',
            data: { start_date: startDate, end_date: endDate, category_id: categoryId },
            success: function(response) {
                updateDashboardCards(response);
                updateExpenseChart(response);
                updateExpenseTable(response.expenses);
            }
        });
    }

    function updateDashboardCards(data) {
        const totalExpenses = data.expenses.reduce((sum, expense) => 
            sum + parseFloat(expense.amount), 0);
        
        $('#total_expenses').text('$' + totalExpenses.toFixed(2));
        $('#avg_monthly').text('$' + data.average_monthly.toFixed(2));
    }

    function updateExpenseChart(data) {
        const ctx = document.getElementById('expenseChart').getContext('2d');
        
        if (expenseChart) {
            expenseChart.destroy();
        }

        expenseChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.chart_data.labels,
                datasets: [{
                    label: 'Expenses by Category',
                    data: data.chart_data.values,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.5)',
                        'rgba(54, 162, 235, 0.5)',
                        'rgba(255, 206, 86, 0.5)',
                        'rgba(75, 192, 192, 0.5)',
                        'rgba(153, 102, 255, 0.5)'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Expenses by Category'
                    }
                }
            }
        });
    }

    function updateExpenseTable(expenses) {
    let html = '';
    let totalAmount = 0;
    
    expenses.forEach(expense => {
        const amount = parseFloat(expense.amount);
        totalAmount += amount;
        
        html += `
            <tr>
                <td>${expense.date}</td>
                <td>${expense.category}</td>
                <td>${expense.description}</td>
                <td>${expense.reference}</td>
                <td class="text-end">$${amount.toFixed(2)}</td>
                <td>
                    <span class="badge bg-${expense.status === 'paid' ? 'success' : 'warning'}">
                        ${expense.status}
                    </span>
                </td>
            </tr>
        `;
    });

    // Add total row
    html += `
        <tr class="fw-bold bg-light">
            <td colspan="4" class="text-end">Total</td>
            <td class="text-end">$${totalAmount.toFixed(2)}</td>
            <td></td>
        </tr>
    `;

    $('#expense_data').html(html || '<tr><td colspan="6" class="text-center">No data found</td></tr>');
}

    $('#start_date, #end_date, #category_id').on('change', loadExpenseData);
});
</script>
@endsection