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

{% block title %}SasaPay 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">💳 SasaPay &amp; SMS Dashboard</h1>
                <div>
                    <a href="{% url 'payments:sasapay_test_token' %}" class="btn btn-outline-info btn-sm">
                        🔑 Test SasaPay Token
                    </a>
                    <a href="{% url 'payments:sms_logs' %}" class="btn btn-outline-success btn-sm">
                        📱 SMS Logs
                    </a>
                    <a href="{% url 'payments:sasapay_unknown_payments' %}" class="btn btn-outline-warning btn-sm">
                        ⚠️ Unknown Payments
                        {% if stats.unknown_pending > 0 %}
                        <span class="badge badge-warning">{{ stats.unknown_pending }}</span>
                        {% endif %}
                    </a>
                    <a href="{% url 'payments:dashboard' %}" class="btn btn-outline-secondary btn-sm">
                        📊 M-Pesa Dashboard
                    </a>
                    <a href="{% url 'payments:developer_payments' %}" class="btn btn-outline-dark btn-sm">
                        <i class="fas fa-code me-1"></i> Developer Payments
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Callback URLs Info -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-left-info shadow">
                <div class="card-header bg-info text-white">
                    <strong>📡 SasaPay Callback URLs (register these with SasaPay)</strong>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <small class="text-muted">C2B IPN (incoming payments)</small>
                            <div class="input-group input-group-sm">
                                <input type="text" class="form-control" value="{{ callback_urls.ipn }}" readonly id="ipn-url">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" onclick="copyUrl('ipn-url')">📋</button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted">STK Push callback</small>
                            <div class="input-group input-group-sm">
                                <input type="text" class="form-control" value="{{ callback_urls.stk }}" readonly id="stk-url">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" onclick="copyUrl('stk-url')">📋</button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted">B2C Disbursement callback</small>
                            <div class="input-group input-group-sm">
                                <input type="text" class="form-control" value="{{ callback_urls.disbursement }}" readonly id="disb-url">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" onclick="copyUrl('disb-url')">📋</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">IPN Payments Today</div>
                    <div class="h5 mb-0 font-weight-bold">{{ stats.ipn_today }}</div>
                    <small class="text-muted">Total: {{ stats.ipn_total }}</small>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">STK Push Today</div>
                    <div class="h5 mb-0 font-weight-bold">{{ stats.stk_today }}</div>
                    <small class="text-muted">Successful: {{ stats.stk_success }}</small>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Disbursements Today</div>
                    <div class="h5 mb-0 font-weight-bold">{{ stats.disb_today }}</div>
                    <small class="text-muted">KES {{ stats.disb_amount|floatformat:2|intcomma }} disbursed</small>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Unknown Payments</div>
                    <div class="h5 mb-0 font-weight-bold">{{ stats.unknown_pending }}</div>
                    <small class="text-muted">Pending review</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- STK Push Form -->
        <div class="col-md-6 mb-4">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <strong>📲 Initiate STK Push (Request Payment)</strong>
                </div>
                <div class="card-body">
                    <form method="post" action="{% url 'payments:sasapay_initiate_stk' %}">
                        {% csrf_token %}
                        <div class="form-group">
                            <label>Customer Phone Number</label>
                            <input type="text" name="phone_number" class="form-control" placeholder="e.g. 0712345678" required>
                        </div>
                        <div class="form-group">
                            <label>Amount (KES)</label>
                            <input type="number" name="amount" class="form-control" placeholder="e.g. 5000" step="0.01" min="1" required>
                        </div>
                        <div class="form-group">
                            <label>Loan Number / Account Reference</label>
                            <input type="text" name="loan_number" class="form-control" placeholder="e.g. LN-2024-001" required>
                            <small class="text-muted">Or select from active loans:</small>
                            <select class="form-control mt-1" onchange="this.previousElementSibling.previousElementSibling.value=this.value">
                                <option value="">-- Select loan --</option>
                                {% for loan in active_loans %}
                                <option value="{{ loan.loan_number }}">{{ loan.loan_number }} — {{ loan.borrower.get_full_name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Description (optional)</label>
                            <input type="text" name="description" class="form-control" value="Loan Payment">
                        </div>
                        <button type="submit" class="btn btn-primary btn-block">
                            📲 Send STK Push
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Disbursement Form -->
        <div class="col-md-6 mb-4">
            <div class="card shadow">
                <div class="card-header bg-success text-white">
                    <strong>💸 Disburse Loan (B2C)</strong>
                </div>
                <div class="card-body">
                    <form method="post" action="{% url 'payments:sasapay_disburse' %}">
                        {% csrf_token %}
                        <div class="form-group">
                            <label>Borrower Phone Number</label>
                            <input type="text" name="phone_number" class="form-control" placeholder="e.g. 0712345678" required>
                        </div>
                        <div class="form-group">
                            <label>Amount (KES)</label>
                            <input type="number" name="amount" class="form-control" placeholder="e.g. 10000" step="0.01" min="1" required>
                        </div>
                        <div class="form-group">
                            <label>Loan Number</label>
                            <input type="text" name="loan_number" class="form-control" placeholder="e.g. LN-2024-001" required>
                            <small class="text-muted">Or select from approved loans:</small>
                            <select class="form-control mt-1" onchange="this.previousElementSibling.previousElementSibling.value=this.value">
                                <option value="">-- Select loan --</option>
                                {% for loan in active_loans %}
                                <option value="{{ loan.loan_number }}">{{ loan.loan_number }} — {{ loan.borrower.get_full_name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <button type="submit" class="btn btn-success btn-block"
                            onclick="return confirm('Confirm disbursement? This will send money to the borrower\'s M-Pesa.')">
                            💸 Disburse Loan
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Test SMS Form -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card shadow">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <strong>📱 Send Test SMS (Africa's Talking)</strong>
                    <span class="badge badge-warning text-dark" style="font-size:.75rem">⚠️ KES 0.80 per SMS</span>
                </div>
                <div class="card-body">
                    <div class="alert alert-warning py-2 mb-3" style="font-size:.82rem;border-left:3px solid #ffc107">
                        <strong>Real charges apply.</strong> Each SMS costs KES 0.80 from your Africa's Talking balance.
                        Only use your own number for testing — do not send to all admin numbers.
                    </div>
                    <form method="post" action="{% url 'payments:sasapay_test_sms' %}">
                        {% csrf_token %}
                        <div class="form-group">
                            <label>Phone Number <small class="text-muted">(your own number only)</small></label>
                            <input type="text" name="phone_number" class="form-control" placeholder="e.g. +254712345678" required>
                        </div>
                        <div class="form-group">
                            <label>Message</label>
                            <textarea name="message" class="form-control" rows="3">Test SMS from HAVEN GRAZURI system.</textarea>
                        </div>
                        <button type="submit" class="btn btn-secondary btn-block"
                            onclick="return confirm('This sends a real SMS costing KES 0.80. Continue?')">
                            📱 Send Test SMS
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Recent IPN Logs -->
        <div class="col-md-6">
            <div class="card shadow">
                <div class="card-header">
                    <strong>📥 Recent IPN Payments</strong>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th>Time</th>
                                    <th>TransID</th>
                                    <th>Amount</th>
                                    <th>BillRef</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for ipn in recent_ipn %}
                                <tr>
                                    <td><small>{{ ipn.created_at|date:"d/m H:i" }}</small></td>
                                    <td><small>{{ ipn.raw_data.TransID|default:"-" }}</small></td>
                                    <td><small>{{ ipn.raw_data.TransAmount|default:"-" }}</small></td>
                                    <td><small>{{ ipn.raw_data.BillRefNumber|default:"-" }}</small></td>
                                </tr>
                                {% empty %}
                                <tr><td colspan="4" class="text-center text-muted">No IPN logs yet</td></tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent STK & Disbursement Results -->
    <div class="row">
        <div class="col-md-6 mb-4">
            <div class="card shadow">
                <div class="card-header">
                    <strong>📲 Recent STK Push Results</strong>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead class="thead-light">
                                <tr><th>Time</th><th>CheckoutID</th><th>Amount</th><th>Status</th></tr>
                            </thead>
                            <tbody>
                                {% for stk in recent_stk %}
                                <tr>
                                    <td><small>{{ stk.created_at|date:"d/m H:i" }}</small></td>
                                    <td><small>{{ stk.checkout_request_id|truncatechars:15 }}</small></td>
                                    <td><small>{{ stk.trans_amount|floatformat:2 }}</small></td>
                                    <td>
                                        {% if stk.is_success %}
                                        <span class="badge badge-success">✓</span>
                                        {% else %}
                                        <span class="badge badge-danger">✗ {{ stk.result_code }}</span>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% empty %}
                                <tr><td colspan="4" class="text-center text-muted">No STK results yet</td></tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6 mb-4">
            <div class="card shadow">
                <div class="card-header">
                    <strong>💸 Recent Disbursements</strong>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead class="thead-light">
                                <tr><th>Time</th><th>Loan Ref</th><th>Amount</th><th>Status</th></tr>
                            </thead>
                            <tbody>
                                {% for disb in recent_disb %}
                                <tr>
                                    <td><small>{{ disb.created_at|date:"d/m H:i" }}</small></td>
                                    <td><small>{{ disb.loan_reference }}</small></td>
                                    <td><small>{{ disb.trans_amount|floatformat:2 }}</small></td>
                                    <td>
                                        {% if disb.is_success %}
                                        <span class="badge badge-success">✓ Sent</span>
                                        {% else %}
                                        <span class="badge badge-danger">✗ {{ disb.result_code }}</span>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% empty %}
                                <tr><td colspan="4" class="text-center text-muted">No disbursements yet</td></tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function copyUrl(inputId) {
    var el = document.getElementById(inputId);
    el.select();
    document.execCommand('copy');
    alert('Copied: ' + el.value);
}
</script>
{% endblock %}
