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

{% block title %}Developer Payments — PhinTech Solutions{% endblock %}

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

  <!-- ── Page Header ── -->
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h1 class="h3 mb-0">
        <i class="fas fa-code text-primary me-2"></i>Developer Payments
      </h1>
      <small class="text-muted">
        Payments to <strong>{{ developer }}</strong> &nbsp;·&nbsp;
        <span class="badge bg-secondary" style="font-size:0.65rem;">v{{ system_version }}</span>
      </small>
    </div>
    <div>
      <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newPaymentModal">
        <i class="fas fa-plus me-1"></i> New Payment
      </button>
      <a href="{% url 'payments:sasapay_dashboard' %}" class="btn btn-outline-secondary btn-sm ms-1">
        <i class="fas fa-arrow-left me-1"></i> Back
      </a>
    </div>
  </div>

  <!-- ── Alert messages ── -->
  {% for msg in messages %}
  <div class="alert alert-{{ msg.tags|default:'info' }} alert-dismissible fade show" role="alert">
    {{ msg }}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
  {% endfor %}

  <!-- ── Stats Cards ── -->
  <div class="row g-3 mb-4">
    <div class="col-xl-3 col-md-6">
      <div class="card border-0 shadow-sm h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="rounded-circle bg-success bg-opacity-10 p-3">
            <i class="fas fa-check-circle text-success fa-lg"></i>
          </div>
          <div>
            <div class="text-muted small text-uppercase fw-semibold">Total Paid</div>
            <div class="h5 mb-0 fw-bold">KES {{ stats.total_paid|floatformat:2|intcomma }}</div>
            <small class="text-muted">{{ stats.total_count }} payment{{ stats.total_count|pluralize }}</small>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6">
      <div class="card border-0 shadow-sm h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="rounded-circle bg-info bg-opacity-10 p-3">
            <i class="fas fa-calendar-alt text-info fa-lg"></i>
          </div>
          <div>
            <div class="text-muted small text-uppercase fw-semibold">This Month</div>
            <div class="h5 mb-0 fw-bold">KES {{ stats.this_month|floatformat:2|intcomma }}</div>
            <small class="text-muted">Current month</small>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6">
      <div class="card border-0 shadow-sm h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="rounded-circle bg-warning bg-opacity-10 p-3">
            <i class="fas fa-clock text-warning fa-lg"></i>
          </div>
          <div>
            <div class="text-muted small text-uppercase fw-semibold">Pending</div>
            <div class="h5 mb-0 fw-bold">{{ stats.pending_count }}</div>
            <small class="text-muted">Awaiting confirmation</small>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6">
      <div class="card border-0 shadow-sm h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="rounded-circle bg-danger bg-opacity-10 p-3">
            <i class="fas fa-times-circle text-danger fa-lg"></i>
          </div>
          <div>
            <div class="text-muted small text-uppercase fw-semibold">Failed</div>
            <div class="h5 mb-0 fw-bold">{{ stats.failed_count }}</div>
            <small class="text-muted">Need attention</small>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Filters ── -->
  <div class="card border-0 shadow-sm mb-4">
    <div class="card-body py-2">
      <form method="get" class="row g-2 align-items-end">
        <div class="col-md-3">
          <label class="form-label small mb-1">Search</label>
          <input type="text" name="q" class="form-control form-control-sm"
                 placeholder="Reference, receipt, phone…" value="{{ filters.q }}">
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Status</label>
          <select name="status" class="form-select form-select-sm">
            <option value="">All statuses</option>
            {% for val, label in status_choices %}
            <option value="{{ val }}" {% if filters.status == val %}selected{% endif %}>{{ label }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Type</label>
          <select name="payment_type" class="form-select form-select-sm">
            <option value="">All types</option>
            {% for val, label in payment_type_choices %}
            <option value="{{ val }}" {% if filters.payment_type == val %}selected{% endif %}>{{ label }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">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="form-label small mb-1">To</label>
          <input type="date" name="date_to" class="form-control form-control-sm" value="{{ filters.date_to }}">
        </div>
        <div class="col-md-1 d-flex gap-1">
          <button type="submit" class="btn btn-primary btn-sm w-100">
            <i class="fas fa-search"></i>
          </button>
          <a href="{% url 'payments:developer_payments' %}" class="btn btn-outline-secondary btn-sm w-100">
            <i class="fas fa-times"></i>
          </a>
        </div>
      </form>
    </div>
  </div>

  <!-- ── Payments Table ── -->
  <div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center py-2">
      <span class="fw-semibold">
        <i class="fas fa-list me-1 text-muted"></i>
        Payment History
        <span class="badge bg-light text-dark ms-1">{{ page_obj.paginator.count }}</span>
      </span>
      <small class="text-muted fst-italic">
        Only payments initiated from this system are shown
      </small>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover table-sm mb-0 align-middle">
          <thead class="table-light">
            <tr>
              <th class="ps-3">Reference</th>
              <th>Date</th>
              <th>Type</th>
              <th>Description</th>
              <th>Amount</th>
              <th>Phone</th>
              <th>M-Pesa Receipt</th>
              <th>Initiated By</th>
              <th>Status</th>
              <th class="text-end pe-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {% for payment in page_obj %}
            <tr id="row-{{ payment.id }}">
              <td class="ps-3">
                <a href="{% url 'payments:developer_payment_detail' payment.id %}"
                   class="text-decoration-none fw-semibold text-primary small">
                  {{ payment.reference }}
                </a>
              </td>
              <td>
                <small>{{ payment.created_at|date:"d M Y" }}</small><br>
                <small class="text-muted">{{ payment.created_at|date:"H:i" }}</small>
              </td>
              <td>
                <span class="badge bg-light text-dark border small">
                  {{ payment.get_payment_type_display }}
                </span>
              </td>
              <td>
                <small class="text-truncate d-inline-block" style="max-width:180px;"
                       title="{{ payment.description }}">
                  {{ payment.description }}
                </small>
              </td>
              <td class="fw-semibold">KES {{ payment.amount|floatformat:2|intcomma }}</td>
              <td><small>{{ payment.payer_phone }}</small></td>
              <td>
                {% if payment.mpesa_receipt %}
                  <code class="small text-success">{{ payment.mpesa_receipt }}</code>
                {% else %}
                  <span class="text-muted small">—</span>
                {% endif %}
              </td>
              <td>
                <small>{{ payment.initiated_by.get_full_name|default:"—" }}</small>
              </td>
              <td>
                {% if payment.status == 'completed' %}
                  <span class="badge bg-success">
                    <i class="fas fa-check me-1"></i>Completed
                  </span>
                {% elif payment.status == 'processing' %}
                  <span class="badge bg-info text-dark status-badge" data-payment-id="{{ payment.id }}">
                    <i class="fas fa-spinner fa-spin me-1"></i>Processing
                  </span>
                {% elif payment.status == 'pending' %}
                  <span class="badge bg-warning text-dark status-badge" data-payment-id="{{ payment.id }}">
                    <i class="fas fa-clock me-1"></i>Pending
                  </span>
                {% elif payment.status == 'failed' %}
                  <span class="badge bg-danger">
                    <i class="fas fa-times me-1"></i>Failed
                  </span>
                {% elif payment.status == 'cancelled' %}
                  <span class="badge bg-secondary">
                    <i class="fas fa-ban me-1"></i>Cancelled
                  </span>
                {% endif %}
              </td>
              <td class="text-end pe-3">
                <div class="d-flex gap-1 justify-content-end">
                  <a href="{% url 'payments:developer_payment_detail' payment.id %}"
                     class="btn btn-outline-secondary btn-xs py-0 px-2"
                     title="View details">
                    <i class="fas fa-eye"></i>
                  </a>
                  {% if payment.status in 'pending,processing,failed' %}
                  <form method="post" action="{% url 'payments:retry_developer_payment' payment.id %}"
                        class="d-inline"
                        onsubmit="return confirm('Re-send STK push for {{ payment.reference }}?')">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-outline-primary btn-xs py-0 px-2" title="Retry">
                      <i class="fas fa-redo"></i>
                    </button>
                  </form>
                  <form method="post" action="{% url 'payments:cancel_developer_payment' payment.id %}"
                        class="d-inline"
                        onsubmit="return confirm('Cancel payment {{ payment.reference }}?')">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-outline-danger btn-xs py-0 px-2" title="Cancel">
                      <i class="fas fa-times"></i>
                    </button>
                  </form>
                  {% endif %}
                </div>
              </td>
            </tr>
            {% empty %}
            <tr>
              <td colspan="10" class="text-center text-muted py-5">
                <i class="fas fa-inbox fa-2x mb-2 d-block opacity-25"></i>
                No developer payments found.
                <a href="#" data-bs-toggle="modal" data-bs-target="#newPaymentModal">Make the first payment</a>.
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>

    <!-- Pagination -->
    {% if page_obj.has_other_pages %}
    <div class="card-footer bg-white border-top py-2">
      <nav>
        <ul class="pagination pagination-sm mb-0 justify-content-center">
          {% if page_obj.has_previous %}
          <li class="page-item">
            <a class="page-link" href="?page={{ page_obj.previous_page_number }}&status={{ filters.status }}&payment_type={{ filters.payment_type }}&date_from={{ filters.date_from }}&date_to={{ filters.date_to }}&q={{ filters.q }}">
              &laquo; Prev
            </a>
          </li>
          {% endif %}
          <li class="page-item disabled">
            <span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
          </li>
          {% if page_obj.has_next %}
          <li class="page-item">
            <a class="page-link" href="?page={{ page_obj.next_page_number }}&status={{ filters.status }}&payment_type={{ filters.payment_type }}&date_from={{ filters.date_from }}&date_to={{ filters.date_to }}&q={{ filters.q }}">
              Next &raquo;
            </a>
          </li>
          {% endif %}
        </ul>
      </nav>
    </div>
    {% endif %}
  </div>

  <!-- ── Footer branding ── -->
  <div class="text-center mt-4 text-muted" style="font-size:0.7rem;">
    <i class="fas fa-code me-1"></i>
    Developed &amp; maintained by <strong>PhinTech Solutions Company Ltd</strong>
    &nbsp;·&nbsp; System v{{ system_version }}
  </div>

</div><!-- /container-fluid -->


<!-- ══════════════════════════════════════════════════════════════
     New Payment Modal
══════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="newPaymentModal" tabindex="-1" aria-labelledby="newPaymentModalLabel" aria-modal="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="newPaymentModalLabel">
          <i class="fas fa-paper-plane me-2"></i>Pay Developer — PhinTech Solutions
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="post" action="{% url 'payments:initiate_developer_payment' %}" id="paymentForm">
        {% csrf_token %}
        <div class="modal-body">

          <div class="alert alert-info py-2 small">
            <i class="fas fa-info-circle me-1"></i>
            An M-Pesa STK push will be sent to the phone number you enter.
            Enter your PIN on your phone to complete the payment.
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Payment Type <span class="text-danger">*</span></label>
            <select name="payment_type" class="form-select" required>
              {% for val, label in payment_type_choices %}
              <option value="{{ val }}">{{ label }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Amount (KES) <span class="text-danger">*</span></label>
            <div class="input-group">
              <span class="input-group-text">KES</span>
              <input type="number" name="amount" class="form-control" placeholder="e.g. 5000"
                     min="1" step="1" required>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">M-Pesa Phone Number <span class="text-danger">*</span></label>
            <input type="tel" name="phone" class="form-control"
                   placeholder="e.g. 0712345678 or +254712345678" required>
            <div class="form-text">The company phone that will receive the STK push.</div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold">Description / Purpose <span class="text-danger">*</span></label>
            <textarea name="description" class="form-control" rows="3"
                      placeholder="e.g. Monthly system maintenance fee for June 2026" required></textarea>
          </div>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="submitPaymentBtn">
            <i class="fas fa-paper-plane me-1"></i> Send STK Push
          </button>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
// Prevent double-submit
document.getElementById('paymentForm').addEventListener('submit', function () {
  var btn = document.getElementById('submitPaymentBtn');
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Sending…';
});

// Poll pending/processing payments every 8 seconds
(function pollStatuses() {
  var badges = document.querySelectorAll('.status-badge[data-payment-id]');
  if (!badges.length) return;

  badges.forEach(function (badge) {
    var paymentId = badge.dataset.paymentId;
    var url = '/payments/developer/status/' + paymentId + '/';

    var interval = setInterval(function () {
      fetch(url, { credentials: 'same-origin' })
        .then(function (r) { return r.json(); })
        .then(function (data) {
          if (data.status === 'completed') {
            clearInterval(interval);
            badge.className = 'badge bg-success';
            badge.innerHTML = '<i class="fas fa-check me-1"></i>Completed';
            // Update receipt cell if present
            var row = document.getElementById('row-' + paymentId);
            if (row && data.mpesa_receipt) {
              var receiptCell = row.querySelectorAll('td')[6];
              if (receiptCell) {
                receiptCell.innerHTML = '<code class="small text-success">' + data.mpesa_receipt + '</code>';
              }
            }
          } else if (data.status === 'failed' || data.status === 'cancelled') {
            clearInterval(interval);
            badge.className = 'badge bg-danger';
            badge.innerHTML = '<i class="fas fa-times me-1"></i>' + data.status_display;
          }
        })
        .catch(function () { /* silently ignore network errors */ });
    }, 8000);
  });
})();
</script>
{% endblock %}
