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

{% block title %}SMS Logs{% endblock %}

{% block extra_css %}
<style>
.sms-header { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; border-radius: 10px 10px 0 0; padding: 20px; }
.stat-card  { border-radius: 8px; padding: 15px; text-align: center; }
.badge-sent    { background: #28a745; color: white; }
.badge-failed  { background: #dc3545; color: white; }
.badge-partial { background: #ffc107; color: #212529; }
.msg-preview   { max-width: 320px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 0.85rem; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">

  <!-- Header -->
  <div class="card border-0 mb-4">
    <div class="sms-header">
      <div class="row align-items-center">
        <div class="col-md-7">
          <h2 class="mb-0">📱 SMS Logs</h2>
          <p class="mb-0 mt-1" style="opacity:.85">Every SMS sent by the system — payment confirmations, approvals, reminders</p>
          <div class="mt-2">
            <a href="{% url 'payments:sasapay_dashboard' %}" class="text-white-50 text-decoration-none mr-3" style="font-size:.85rem">💳 SasaPay Dashboard</a>
            <a href="{% url 'payments:dashboard' %}" class="text-white-50 text-decoration-none" style="font-size:.85rem">📊 M-Pesa Dashboard</a>
          </div>
        </div>
        <div class="col-md-5">
          <div class="row text-center">
            <div class="col-4">
              <div class="stat-card" style="background:rgba(255,255,255,.15)">
                <div style="font-size:1.8rem;font-weight:700">{{ stats.today }}</div>
                <div style="font-size:.8rem;opacity:.9">Today</div>
              </div>
            </div>
            <div class="col-4">
              <div class="stat-card" style="background:rgba(255,255,255,.15)">
                <div style="font-size:1.8rem;font-weight:700">{{ stats.sent }}</div>
                <div style="font-size:.8rem;opacity:.9">Delivered</div>
              </div>
            </div>
            <div class="col-4">
              <div class="stat-card" style="background:rgba(220,53,69,.4)">
                <div style="font-size:1.8rem;font-weight:700">{{ stats.failed }}</div>
                <div style="font-size:.8rem;opacity:.9">Failed</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Type breakdown pills -->
  {% if type_counts %}
  <div class="mb-3">
    {% for tc in type_counts %}
    <span class="badge badge-pill badge-info mr-1" style="font-size:.8rem">
      {{ tc.sms_type|title|cut:"_" }}: {{ tc.count }}
    </span>
    {% endfor %}
  </div>
  {% endif %}

  <!-- Filters -->
  <div class="card shadow-sm mb-4">
    <div class="card-body py-3">
      <form method="get" class="row align-items-end">
        <div class="col-md-2">
          <label class="small font-weight-bold">Type</label>
          <select name="sms_type" class="form-control form-control-sm">
            <option value="">All Types</option>
            {% for val, label in sms_types %}
            <option value="{{ val }}" {% if filters.sms_type == val %}selected{% endif %}>{{ label }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="col-md-2">
          <label class="small font-weight-bold">Status</label>
          <select name="status" class="form-control form-control-sm">
            <option value="">All</option>
            <option value="sent"    {% if filters.status == 'sent'    %}selected{% endif %}>✅ Sent</option>
            <option value="failed"  {% if filters.status == 'failed'  %}selected{% endif %}>❌ Failed</option>
            <option value="partial" {% if filters.status == 'partial' %}selected{% endif %}>⚠️ Partial</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="small font-weight-bold">Search (phone / name / loan)</label>
          <input type="text" name="search" class="form-control form-control-sm" value="{{ filters.search }}" placeholder="0712345678 or John...">
        </div>
        <div class="col-md-2">
          <label class="small font-weight-bold">From</label>
          <input type="date" name="date_from" class="form-control form-control-sm" value="{{ filters.date_from }}">
        </div>
        <div class="col-md-2">
          <label class="small font-weight-bold">To</label>
          <input type="date" name="date_to" class="form-control form-control-sm" value="{{ filters.date_to }}">
        </div>
        <div class="col-md-1">
          <button type="submit" class="btn btn-primary btn-sm btn-block">🔍</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Table -->
  <div class="card shadow">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover mb-0" style="font-size:.88rem">
          <thead class="thead-dark">
            <tr>
              <th>Date &amp; Time</th>
              <th>Type</th>
              <th>Recipients</th>
              <th>Message</th>
              <th>Loan / Borrower</th>
              <th>Amount</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {% for log in page_obj %}
            <tr>
              <td style="white-space:nowrap">
                <strong>{{ log.created_at|date:"d/m/Y" }}</strong><br>
                <small class="text-muted">{{ log.created_at|date:"H:i:s" }}</small>
              </td>
              <td>
                {% if log.sms_type == 'payment_confirmation' %}
                  <span class="badge badge-success">💰 Payment</span>
                {% elif log.sms_type == 'loan_approval' %}
                  <span class="badge badge-primary">✅ Approval</span>
                {% elif log.sms_type == 'loan_disbursement' %}
                  <span class="badge badge-info">💸 Disbursement</span>
                {% elif log.sms_type == 'overdue_reminder' %}
                  <span class="badge badge-warning text-dark">⏰ Overdue</span>
                {% elif log.sms_type == 'unknown_payment' %}
                  <span class="badge badge-danger">❓ Unknown Pmt</span>
                {% elif log.sms_type == 'stk_push' %}
                  <span class="badge badge-secondary">📲 STK Push</span>
                {% elif log.sms_type == 'test' %}
                  <span class="badge badge-light border">🧪 Test</span>
                {% else %}
                  <span class="badge badge-light border">{{ log.sms_type }}</span>
                {% endif %}
              </td>
              <td>
                <small>
                  {% for phone in log.recipients.split %}
                    {{ phone|cut:"," }}<br>
                  {% endfor %}
                </small>
                <small class="text-muted">({{ log.recipient_count }} recipient{{ log.recipient_count|pluralize }})</small>
              </td>
              <td>
                <div class="msg-preview" title="{{ log.message }}">{{ log.message }}</div>
                <a href="{% url 'payments:sms_log_detail' log.id %}" class="small text-primary">View full</a>
              </td>
              <td>
                {% if log.loan_number %}<span class="badge badge-light border">{{ log.loan_number }}</span><br>{% endif %}
                <small>{{ log.borrower_name }}</small>
              </td>
              <td>
                {% if log.amount %}
                <strong class="text-success">KES {{ log.amount|floatformat:2|intcomma }}</strong>
                {% else %}<span class="text-muted">—</span>{% endif %}
              </td>
              <td>
                {% if log.status == 'sent' %}
                  <span class="badge badge-sent">✓ Sent</span>
                {% elif log.status == 'failed' %}
                  <span class="badge badge-failed">✗ Failed</span>
                {% else %}
                  <span class="badge badge-partial">⚠ Partial</span>
                {% endif %}
              </td>
              <td>
                <a href="{% url 'payments:sms_log_detail' log.id %}" class="btn btn-xs btn-outline-secondary" style="font-size:.75rem;padding:2px 8px">👁 View</a>
                {% if log.status != 'sent' %}
                <form method="post" action="{% url 'payments:resend_sms' log.id %}" style="display:inline">
                  {% csrf_token %}
                  <button type="submit" class="btn btn-xs btn-outline-warning" style="font-size:.75rem;padding:2px 8px"
                    onclick="return confirm('Re-send this SMS?')">🔄 Retry</button>
                </form>
                {% endif %}
              </td>
            </tr>
            {% empty %}
            <tr>
              <td colspan="8" class="text-center text-muted py-5">
                <div style="font-size:3rem">📭</div>
                <h5>No SMS logs yet</h5>
                <p>SMS messages will appear here once the system starts sending them.</p>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Pagination -->
  {% if page_obj.has_other_pages %}
  <nav class="mt-3">
    <ul class="pagination justify-content-center">
      {% if page_obj.has_previous %}
      <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}&sms_type={{ filters.sms_type }}&status={{ filters.status }}&search={{ filters.search }}&date_from={{ filters.date_from }}&date_to={{ filters.date_to }}">‹ Prev</a></li>
      {% endif %}
      <li class="page-item disabled"><span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} ({{ page_obj.paginator.count }} total)</span></li>
      {% if page_obj.has_next %}
      <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}&sms_type={{ filters.sms_type }}&status={{ filters.status }}&search={{ filters.search }}&date_from={{ filters.date_from }}&date_to={{ filters.date_to }}">Next ›</a></li>
      {% endif %}
    </ul>
  </nav>
  {% endif %}

</div>
{% endblock %}
