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

{% block title %}Reports Dashboard{% endblock %}

{% block content %}

<div class="container-fluid">

    <!-- ================= HEADER ================= -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="bi bi-bar-chart"></i> Reports Dashboard</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="">Select 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 Filters</button>
        </div>

    </form>

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

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

        <div class="col-md-3">
            <div class="card shadow-sm border-0">
                <div class="card-body">
                    <h6>Occupancy Rate</h6>
                    <h4>{{ occupancy.occupancy_rate|floatformat:0|default:0 }}%</h4>
                </div>
            </div>
        </div>

    </div>

    <!-- ================= SECOND ROW KPIs ================= -->
    <div class="row g-3 mb-4">

        <div class="col-md-4">
            <div class="card shadow-sm border-0">
                <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-4">
            <div class="card shadow-sm border-0">
                <div class="card-body">
                    <h6>Active Tenants</h6>
                    <h4>{{ active_tenants|default:0 }}</h4>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card shadow-sm border-0">
                <div class="card-body">
                    <h6>Overdue Rent</h6>
                    <h4>KES {{ arrears.total_arrears|floatformat:2|default:0 }}</h4>
                </div>
            </div>
        </div>

    </div>

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

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

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

    </div>

</div>

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

<script>
let incomeChartInstance = null;
let expenseChartInstance = null;

// ================= SAFE FETCH =================
function safeFetch(url, callback) {
    fetch(url)
        .then(res => res.json())
        .then(data => callback(data))
        .catch(err => {
            console.error("Chart load 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 (incomeChartInstance) {
        incomeChartInstance.destroy();
    }

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

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

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

    if (expenseChartInstance) {
        expenseChartInstance.destroy();
    }

    expenseChartInstance = new Chart(document.getElementById('expenseChart'), {
        type: 'pie',
        data: {
            labels: labels,
            datasets: [{
                data: values
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
});

</script>

{% endblock %}