{% extends 'base.html' %}
{% load humanize %}

{% block title %}Advanced Analytics Dashboard - HAVEN GRAZURI INVESTMENT LIMITED{% endblock %}

{% block content %}
<div class="mb-8">
    <div class="flex justify-between items-center">
        <div>
            <h2 class="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
                Advanced Analytics Dashboard
            </h2>
            <p class="text-gray-600 mt-1">Comprehensive analytics with custom filtering and PDF generation</p>
        </div>
        <div class="flex space-x-3">
            <a href="{% url 'loans:loans' %}"
                class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                <span>←</span>
                Back to Dashboard
            </a>
        </div>
    </div>
</div>

<!-- Analytics Filters -->
<div class="bg-white shadow rounded-lg p-6 mb-8">
    <h3 class="text-lg font-medium text-gray-900 mb-4">Custom Analytics Filters</h3>
    <form id="analyticsForm" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div>
            <label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
            <input type="date" id="start_date" name="start_date"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
        </div>

        <div>
            <label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
            <input type="date" id="end_date" name="end_date"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
        </div>

        <div>
            <label for="borrower_id" class="block text-sm font-medium text-gray-700">Specific Client</label>
            <select id="borrower_id" name="borrower_id"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                <option value="">All Clients</option>
                {% for borrower in borrowers %}
                <option value="{{ borrower.id }}">{{ borrower.get_full_name }}</option>
                {% endfor %}
            </select>
        </div>

        <div>
            <label for="loan_product_id" class="block text-sm font-medium text-gray-700">Loan Product</label>
            <select id="loan_product_id" name="loan_product_id"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary">
                <option value="">All Products</option>
                {% for product in loan_products %}
                <option value="{{ product.id }}">{{ product.name }}</option>
                {% endfor %}
            </select>
        </div>

        <div class="md:col-span-2 lg:col-span-4 flex space-x-3">
            <button type="button" onclick="generateCustomPDF()"
                class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-dark">
                <span>📄</span>
                Generate Custom PDF Report
            </button>
            <button type="button" onclick="resetFilters()"
                class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                <span>↶</span>
                Reset Filters
            </button>
        </div>
    </form>
</div>

<!-- Quick Analytics Overview -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
    <!-- Loans Analytics -->
    <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>📈</span>
                </div>
                <div class="ml-5 w-0 flex-1">
                    <dl>
                        <dt class="text-sm font-medium text-gray-500 truncate">Total Active Loans</dt>
                        <dd class="text-lg font-medium text-gray-900">{{loan_stats.basic_metrics.active_loans.current|default:0|intcomma }}</dd>
                    </dl>
                </div>
            </div>
        </div>
        <div class="bg-gray-50 px-5 py-3">
            <div class="text-sm">
                <a href="{% url 'loans:filtered_loans' %}?status=active"
                    class="font-medium text-primary hover:text-primary-dark">
                    View active loans
                </a>
            </div>
        </div>
    </div>

    <!-- Clients Analytics -->
    <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>👥</span>
                </div>
                <div class="ml-5 w-0 flex-1">
                    <dl>
                        <dt class="text-sm font-medium text-gray-500 truncate">Active Clients</dt>
                        <dd class="text-lg font-medium text-gray-900">{{client_stats.basic_metrics.active_clients.current|default:0|intcomma }}</dd>
                    </dl>
                </div>
            </div>
        </div>
        <div class="bg-gray-50 px-5 py-3">
            <div class="text-sm">
                <a href="{% url 'users:filtered_clients' %}?status=active"
                    class="font-medium text-primary hover:text-primary-dark">
                    View active clients
                </a>
            </div>
        </div>
    </div>

    <!-- Payments Analytics -->
    <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>💵</span>
                </div>
                <div class="ml-5 w-0 flex-1">
                    <dl>
                        <dt class="text-sm font-medium text-gray-500 truncate">Total Transactions</dt>
                        <dd class="text-lg font-medium text-gray-900">{{payment_stats.basic_metrics.total_transactions.current|default:0|intcomma }}</dd>
                            
                    </dl>
                </div>
            </div>
        </div>
        <div class="bg-gray-50 px-5 py-3">
            <div class="text-sm">
                <a href="{% url 'payments:transactions' %}" class="font-medium text-primary hover:text-primary-dark">
                    View all transactions
                </a>
            </div>
        </div>
    </div>

    <!-- Portfolio Value -->
    <div class="bg-white overflow-hidden shadow rounded-lg">
        <div class="p-5">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>📊</span>
                </div>
                <div class="ml-5 w-0 flex-1">
                    <dl>
                        <dt class="text-sm font-medium text-gray-500 truncate">Portfolio Value</dt>
                        <dd class="text-lg font-medium text-gray-900">KES {{loan_stats.basic_metrics.total_disbursed.current|default:0|floatformat:0|intcomma }}</dd>
                            
                    </dl>
                </div>
            </div>
        </div>
        <div class="bg-gray-50 px-5 py-3">
            <div class="text-sm">
                <a href="{% url 'reports:portfolio_details' %}"
                    class="font-medium text-primary hover:text-primary-dark">
                    View portfolio details
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Dashboard Type Selection -->
<div class="bg-white shadow rounded-lg p-6 mb-8">
    <h3 class="text-lg font-medium text-gray-900 mb-4">Generate Dashboard Reports</h3>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <button onclick="generateDashboardPDF('loans')"
            class="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
            <span>💵</span>
            Loans Dashboard PDF
        </button>

        <button onclick="generateDashboardPDF('clients')"
            class="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
            <span>👥</span>
            Clients Dashboard PDF
        </button>

        <button onclick="generateDashboardPDF('payments')"
            class="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
            <span>💳</span>
            Payments Dashboard PDF
        </button>

        <button onclick="generateDashboardPDF('reports')"
            class="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
            <span>📊</span>
            Reports Dashboard PDF
        </button>

        <button onclick="generateDashboardPDF('portfolio')"
            class="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
            <span>📊</span>
            Portfolio Dashboard PDF
        </button>
    </div>
</div>

<!-- Performance Metrics -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Loan Performance -->
    <div class="bg-white shadow rounded-lg p-6">
        <h3 class="text-lg font-medium text-gray-900 mb-4">Loan Performance Metrics</h3>
        <div class="space-y-4">
            <div class="flex justify-between items-center">
                <span class="text-sm font-medium text-gray-500">Collection Rate</span>
                <span class="text-sm font-medium text-gray-900">{{loan_stats.performance_metrics.collection_rate.current|default:0|floatformat:1 }}%</span>
            </div>
            <div class="flex justify-between items-center">
                <span class="text-sm font-medium text-gray-500">Default Rate</span>
                <span class="text-sm font-medium text-gray-900">{{loan_stats.performance_metrics.default_rate.current|default:0|floatformat:1 }}%</span>
            </div>
            <div class="flex justify-between items-center">
                <span class="text-sm font-medium text-gray-500">On-Time Payment Rate</span>
                <span class="text-sm font-medium text-gray-900">{{loan_stats.performance_metrics.on_time_payment_rate.current|default:0|floatformat:1 }}%</span>
            </div>
        </div>
    </div>

    <!-- Client Metrics -->
    <div class="bg-white shadow rounded-lg p-6">
        <h3 class="text-lg font-medium text-gray-900 mb-4">Client Metrics</h3>
        <div class="space-y-4">
            <div class="flex justify-between items-center">
                <span class="text-sm font-medium text-gray-500">Total Clients</span>
                <span class="text-sm font-medium text-gray-900">{{client_stats.basic_metrics.total_clients.current|default:0|intcomma }}</span>
            </div>
            <div class="flex justify-between items-center">
                <span class="text-sm font-medium text-gray-500">Clients with Loans</span>
                <span class="text-sm font-medium text-gray-900">{{client_stats.basic_metrics.clients_with_loans.current|default:0|intcomma }}</span>
            </div>
            <div class="flex justify-between items-center">
                <span class="text-sm font-medium text-gray-500">Loan Uptake Rate</span>
                <span class="text-sm font-medium text-gray-900">{{client_stats.performance_metrics.loan_uptake_rate|default:0|floatformat:1 }}%</span>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // PDF Generation Functions
    function generateDashboardPDF(dashboardType) {
        const button = event.target.closest('button');
        const originalText = button.innerHTML;

        // Show loading state
        button.innerHTML = '<span>⟳</span>Generating PDF...';
        button.disabled = true;

        // Determine the correct URL based on dashboard type
        let pdfUrl;
        switch (dashboardType) {
            case 'loans':
                pdfUrl = '{% url "loans:generate_loans_dashboard_pdf" %}';
                break;
            case 'clients':
                pdfUrl = '{% url "loans:generate_clients_dashboard_pdf" %}';
                break;
            case 'payments':
                pdfUrl = '{% url "loans:generate_payments_dashboard_pdf" %}';
                break;
            case 'reports':
                pdfUrl = '{% url "loans:generate_reports_dashboard_pdf" %}';
                break;
            case 'portfolio':
                pdfUrl = '{% url "loans:generate_portfolio_dashboard_pdf" %}';
                break;
            default:
                pdfUrl = '{% url "loans:generate_loans_dashboard_pdf" %}';
        }

        // Create a temporary link to download the PDF
        const link = document.createElement('a');
        link.href = pdfUrl;
        link.download = `${dashboardType}_dashboard_report_${new Date().toISOString().slice(0, 10)}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // Reset button after a delay
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 3000);
    }

    function generateCustomPDF() {
        const button = event.target.closest('button');
        const originalText = button.innerHTML;

        // Show loading state
        button.innerHTML = '<span>⟳</span>Generating Custom PDF...';
        button.disabled = true;

        // Get form data
        const formData = new FormData(document.getElementById('analyticsForm'));
        const params = new URLSearchParams(formData);

        // Create URL with parameters
        const pdfUrl = '{% url "loans:generate_custom_analytics_pdf" %}?' + params.toString();

        // Create a temporary link to download the PDF
        const link = document.createElement('a');
        link.href = pdfUrl;
        link.download = `custom_analytics_report_${new Date().toISOString().slice(0, 10)}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // Reset button after a delay
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 3000);
    }

    function resetFilters() {
        document.getElementById('analyticsForm').reset();
    }

    // Set default dates (last 30 days)
    document.addEventListener('DOMContentLoaded', function () {
        const today = new Date();
        const thirtyDaysAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000));

        document.getElementById('end_date').value = today.toISOString().split('T')[0];
        document.getElementById('start_date').value = thirtyDaysAgo.toISOString().split('T')[0];
    });
</script>
{% endblock %}