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

{% block title %}M-Pesa Dashboard{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">M-Pesa Payment Dashboard</h1>
                <div>
                    <a href="{% url 'payments:sasapay_dashboard' %}" class="btn btn-outline-info">
                        💳 SasaPay &amp; SMS
                    </a>
                    <a href="{% url 'payments:configuration' %}" class="btn btn-outline-primary">
                        <span>⚙️</span> Configuration
                    </a>
                    <a href="{% url 'payments:test_payment' %}" class="btn btn-outline-success">
                        <i class="fas fa-flask"></i> Test Payment
                    </a>
                    <button onclick="generateDashboardPDF('payments')" class="btn btn-primary">
                        <span>📄</span> Generate PDF Report
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <a href="{% url 'payments:transactions' %}" class="text-decoration-none">
                <div class="card border-left-primary shadow h-100 py-2 hover-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                    Total Transactions
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    {{ stats.total_transactions|intcomma }}
                                </div>
                            </div>
                            <div class="col-auto">
                                <span>💳</span>
                            </div>
                        </div>
                    </div>
                </div>
            </a>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <a href="{% url 'payments:transactions' %}?date=today" class="text-decoration-none">
                <div class="card border-left-success shadow h-100 py-2 hover-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                    Today's Amount
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    KES {{ stats.total_amount_today|floatformat:2|intcomma }}
                                </div>
                            </div>
                            <div class="col-auto">
                                <span>💵</span>
                            </div>
                        </div>
                    </div>
                </div>
            </a>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <a href="{% url 'payments:transactions' %}?status=processed" class="text-decoration-none">
                <div class="card border-left-info shadow h-100 py-2 hover-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                    Success Rate
                                </div>
                                <div class="row no-gutters align-items-center">
                                    <div class="col-auto">
                                        <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">
                                            {{ stats.success_rate }}%
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="progress progress-sm mr-2">
                                            <div class="progress-bar bg-info" role="progressbar"
                                                 style="width: {{ stats.success_rate }}%"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-auto">
                                <span>📈</span>
                            </div>
                        </div>
                    </div>
                </div>
            </a>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <a href="{% url 'payments:transactions' %}?status=pending,failed" class="text-decoration-none">
                <div class="card border-left-warning shadow h-100 py-2 hover-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                    Pending/Failed
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    {{ stats.pending_transactions|add:stats.failed_transactions|intcomma }}
                                </div>
                            </div>
                            <div class="col-auto">
                                <span>⚠️</span>
                            </div>
                        </div>
                    </div>
                </div>
            </a>
        </div>
    </div>

    <div class="row">
        <!-- Recent Transactions -->
        <div class="col-lg-8 mb-4">
            <div class="card shadow">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Transactions</h6>
                    <a href="{% url 'payments:transactions' %}" class="btn btn-sm btn-primary">View All</a>
                </div>
                <div class="card-body">
                    {% if recent_transactions %}
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Transaction ID</th>
                                        <th>Customer</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for transaction in recent_transactions %}
                                    <tr>
                                        <td>
                                            <a href="{% url 'payments:transaction_detail' transaction.id %}">
                                                {{ transaction.trans_id }}
                                            </a>
                                        </td>
                                        <td>
                                            {% if transaction.borrower %}
                                                {{ transaction.borrower.get_full_name }}
                                            {% else %}
                                                {{ transaction.get_customer_name|default:"Unknown" }}
                                            {% endif %}
                                        </td>
                                        <td>KES {{ transaction.trans_amount|floatformat:2|intcomma }}</td>
                                        <td>
                                            <span class="badge badge-{% if transaction.status == 'processed' %}success{% elif transaction.status == 'failed' %}danger{% elif transaction.status == 'pending' %}warning{% else %}info{% endif %}">
                                                {{ transaction.get_status_display }}
                                            </span>
                                        </td>
                                        <td>{{ transaction.created_at|timesince }} ago</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <p class="text-muted">No transactions yet.</p>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Failed Transactions -->
        <div class="col-lg-4 mb-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-danger">Needs Attention</h6>
                </div>
                <div class="card-body">
                    {% if failed_transactions %}
                        {% for transaction in failed_transactions %}
                        <div class="d-flex align-items-center mb-3">
                            <div class="mr-3">
                                <div class="icon-circle bg-danger">
                                    <span>⚠️</span>
                                </div>
                            </div>
                            <div class="flex-grow-1">
                                <div class="small text-gray-500">{{ transaction.created_at|timesince }} ago</div>
                                <div class="font-weight-bold">
                                    <a href="{% url 'payments:transaction_detail' transaction.id %}">
                                        {{ transaction.trans_id }}
                                    </a>
                                </div>
                                <div class="small">
                                    KES {{ transaction.trans_amount|floatformat:2|intcomma }}
                                    {% if transaction.borrower %}
                                        - {{ transaction.borrower.get_full_name }}
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <p class="text-muted small">No failed transactions.</p>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.icon-circle {
    height: 2rem;
    width: 2rem;
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.hover-card {
    transition: all 0.3s ease;
}

.hover-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15) !important;
}
</style>

<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_payments_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);
}
</script>
{% endblock %}