{% extends "base.html" %}
{% load static %}

{% block title %}Financial Report{% endblock %}

{% block content %}

<div class="container-fluid page-container">

    <!-- ================= HEADER ================= -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="bi bi-cash-stack"></i> Financial Report</h4>
    </div>

    <!-- ================= FILTERS ================= -->
    <form method="get" class="row g-3 mb-4">

        <div class="col-md-3">
            <select name="range" class="form-select">
                <option value="">Range</option>
                <option value="today" {% if request.GET.range == "today" %}selected{% endif %}>Today</option>
                <option value="week" {% if request.GET.range == "week" %}selected{% endif %}>This Week</option>
                <option value="month" {% if request.GET.range == "month" %}selected{% endif %}>This Month</option>
                <option value="year" {% if request.GET.range == "year" %}selected{% endif %}>This Year</option>
            </select>
        </div>

        <div class="col-md-3">
            <input type="date" name="start_date" value="{{ request.GET.start_date }}" class="form-control">
        </div>

        <div class="col-md-3">
            <input type="date" name="end_date" value="{{ request.GET.end_date }}" class="form-control">
        </div>

        <div class="col-md-3">
            <button class="btn btn-primary w-100">Apply</button>
        </div>

    </form>

    <!-- ================= KPI CARDS ================= -->
    <div class="row g-3 mb-4">

        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6>Total Income</h6>
                    <h4>KES {{ financial.total_income|floatformat:2|default:0 }}</h4>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6>Total Expenses</h6>
                    <h4>KES {{ financial.total_expenses|floatformat:2|default:0 }}</h4>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6>Outstanding Balance</h6>
                    <h4>KES {{ financial.outstanding_balance|floatformat:2|default:0 }}</h4>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6>Net Profit</h6>
                    <h4>KES {{ profit.net_profit|floatformat:2|default:0 }}</h4>
                </div>
            </div>
        </div>

    </div>

    <!-- ================= ARREARS TABLE ================= -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <h6>Arrears Breakdown</h6>

            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>0-7 Days</th>
                        <th>8-30 Days</th>
                        <th>31-60 Days</th>
                        <th>60+ Days</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{{ arrears.range_0_7|default:0 }}</td>
                        <td>{{ arrears.range_8_30|default:0 }}</td>
                        <td>{{ arrears.range_31_60|default:0 }}</td>
                        <td>{{ arrears.range_60_plus|default:0 }}</td>
                    </tr>
                </tbody>
            </table>

        </div>
    </div>

    <!-- ================= EXPENSE TABLE ================= -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <h6>Expense Breakdown</h6>

            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Category</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody>
                    {% for item in expenses %}
                    <tr>
                        <td>{{ item.category|default:"Other" }}</td>
                        <td>KES {{ item.total|floatformat:2|default:0 }}</td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="2" class="text-center text-muted">
                            No expense data available
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>

        </div>
    </div>

    <!-- ================= CHARTS ================= -->
    <div class="row g-4">

        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-body" style="height: 350px;">
                    <h6>Income vs Expenses</h6>
                    <canvas id="incomeChart"></canvas>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-body" style="height: 350px;">
                    <h6>Expense Distribution</h6>
                    <canvas id="expenseChart"></canvas>
                </div>
            </div>
        </div>

    </div>

</div>

<!-- ================= CHART JS ================= -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
let incomeChart, expenseChart;

function safeFetch(url, callback) {
    fetch(url)
        .then(res => res.json())
        .then(data => callback(data))
        .catch(err => console.error("Chart error:", err));
}

// Income vs Expense
safeFetch("{% url 'chart_income_expense' %}", function(data) {

    const labels = data.labels || [];
    const income = data.income || [];
    const expenses = data.expenses || [];

    if (incomeChart) incomeChart.destroy();

    incomeChart = new Chart(document.getElementById('incomeChart'), {
        type: 'line',
        data: {
            labels,
            datasets: [
                { label: 'Income', data: income, borderWidth: 2 },
                { label: 'Expenses', data: expenses, borderWidth: 2 }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
});

// Expense Breakdown
safeFetch("{% url 'chart_expenses' %}", function(data) {

    const labels = data.labels || [];
    const values = data.data || [];

    if (expenseChart) expenseChart.destroy();

    expenseChart = new Chart(document.getElementById('expenseChart'), {
        type: 'pie',
        data: {
            labels,
            datasets: [{ data: values }]
        },
        options: {
            responsive: true
        }
    });
});
</script>

{% endblock %}