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

{% block title %}Record Payment — Rapha-Bethel BNPS{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet">
<style>
  .invoice-preview {
    background: #f0fdf4;
    border-left: 4px solid #198754;
    border-radius: 6px;
    padding: 1rem 1.25rem;
    display: none;
  }
  .invoice-preview.visible { display: block; }
  .balance-amount { font-size: 1.25rem; font-weight: 700; color: #dc3545; }
  .invoice-locked { background: #e9ecef !important; cursor: not-allowed; }
  .btn-submit-payment { min-width: 180px; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
  <div class="row justify-content-center">
    <div class="col-lg-7 col-xl-6">

      <!-- Header -->
      <div class="d-flex align-items-center mb-3">
        <a href="{% url 'finance:invoice_list' %}" class="btn btn-outline-secondary btn-sm me-3">
          <i class="fas fa-arrow-left"></i>
        </a>
        <div>
          <h4 class="mb-0 fw-bold">
            <i class="fas fa-money-bill-wave text-success me-2"></i>Record Payment
          </h4>
          <small class="text-muted">All amounts in XAF (Central African CFA Franc)</small>
        </div>
      </div>

      <!-- Invoice Preview Card (shown by JS when invoice selected) -->
      <div id="invoicePreview" class="invoice-preview mb-3
        {% if locked_invoice %}visible{% endif %}">
        <div class="row g-2">
          <div class="col-8">
            <div class="text-muted small mb-0">Student</div>
            <div id="prev_student" class="fw-bold">
              {% if locked_invoice %}{{ locked_invoice.student.get_full_name }}{% endif %}
            </div>
          </div>
          <div class="col-4">
            <div class="text-muted small mb-0">Invoice #</div>
            <div id="prev_number" class="fw-bold">
              {% if locked_invoice %}{{ locked_invoice.invoice_number }}{% endif %}
            </div>
          </div>
          <div class="col-6">
            <div class="text-muted small mb-0">Type / Year</div>
            <div id="prev_type">
              {% if locked_invoice %}{{ locked_invoice.get_invoice_type_display }} — {{ locked_invoice.academic_year }}{% endif %}
            </div>
          </div>
          <div class="col-6">
            <div class="text-muted small mb-0">Due Date</div>
            <div id="prev_due">
              {% if locked_invoice %}{{ locked_invoice.due_date|date:"d M Y" }}{% endif %}
            </div>
          </div>
          <div class="col-4">
            <div class="text-muted small mb-0">Total</div>
            <div id="prev_total">
              {% if locked_invoice %}{{ locked_invoice.total_amount|floatformat:0 }} XAF{% endif %}
            </div>
          </div>
          <div class="col-4">
            <div class="text-muted small mb-0">Paid</div>
            <div id="prev_paid" class="text-success">
              {% if locked_invoice %}{{ locked_invoice.amount_paid|floatformat:0 }} XAF{% endif %}
            </div>
          </div>
          <div class="col-4">
            <div class="text-muted small mb-0">Balance Due</div>
            <div id="prev_balance" class="balance-amount">
              {% if locked_invoice %}{{ locked_invoice.balance|floatformat:0 }} XAF{% endif %}
            </div>
          </div>
        </div>
      </div>

      <!-- Payment Form Card -->
      <div class="card shadow-sm">
        <div class="card-header py-3 bg-success text-white">
          <h6 class="mb-0 fw-bold">
            <i class="fas fa-receipt me-2"></i>
            {% if locked_invoice %}
              Payment for Invoice {{ locked_invoice.invoice_number }}
            {% else %}
              New Payment
            {% endif %}
          </h6>
        </div>
        <div class="card-body">
          <form method="post" id="paymentForm" novalidate>
            {% csrf_token %}

            <!-- Display non-field errors -->
            {% if form.non_field_errors %}
            <div class="alert alert-danger">{{ form.non_field_errors }}</div>
            {% endif %}

            <!-- ── INVOICE FIELD ── -->
            <div class="mb-3">
              <label class="form-label fw-semibold">
                Invoice <span class="text-danger">*</span>
              </label>

              {% if locked_invoice %}
                {# Coming from invoice detail — lock the invoice, show read-only display #}
                <input type="hidden" name="invoice" value="{{ locked_invoice.pk }}">
                <input type="text" class="form-control invoice-locked"
                       value="{{ locked_invoice.invoice_number }} — {{ locked_invoice.student.get_full_name }} ({{ locked_invoice.get_invoice_type_display }}, {{ locked_invoice.academic_year }})"
                       readonly tabindex="-1">
              {% else %}
                {# Normal open selection #}
                <select id="id_invoice" name="invoice"
                        class="form-select select2-invoice"
                        data-placeholder="Type to search invoice or student name…"
                        required>
                  <option value=""></option>
                  {% for inv in invoices %}
                  <option value="{{ inv.pk }}"
                    data-student-name="{{ inv.student.get_full_name }}"
                    data-number="{{ inv.invoice_number }}"
                    data-type="{{ inv.get_invoice_type_display }} — {{ inv.academic_year }}"
                    data-total="{{ inv.total_amount }}"
                    data-paid="{{ inv.amount_paid }}"
                    data-balance="{{ inv.balance }}"
                    data-due="{{ inv.due_date|date:'d M Y' }}"
                    data-status="{{ inv.get_status_display }}"
                    {% if preselected_invoice and preselected_invoice.pk == inv.pk %}selected{% endif %}>
                    {{ inv.invoice_number }} — {{ inv.student.get_full_name }}
                    ({{ inv.get_invoice_type_display }}, bal: {{ inv.balance|floatformat:0 }} XAF)
                  </option>
                  {% endfor %}
                </select>
                {% if form.invoice.errors %}
                <div class="text-danger small mt-1">{{ form.invoice.errors }}</div>
                {% endif %}
              {% endif %}
            </div>

            <!-- ── AMOUNT ── -->
            <div class="mb-3">
              <label for="id_amount" class="form-label fw-semibold">
                Amount (XAF) <span class="text-danger">*</span>
              </label>
              <div class="input-group">
                <span class="input-group-text fw-bold">XAF</span>
                <input type="number" name="amount" id="id_amount"
                       class="form-control form-control-lg"
                       min="1" step="1"
                       value="{{ form.amount.value|default:'' }}"
                       placeholder="0"
                       required>
              </div>
              {% if form.amount.errors %}
              <div class="text-danger small mt-1">{{ form.amount.errors }}</div>
              {% endif %}
              <!-- Quick-fill buttons (only useful when balance is known) -->
              <div class="mt-2 d-flex gap-2" id="quickFillBtns" style="display:none !important">
                <button type="button" class="btn btn-sm btn-outline-success" id="btnPayFull">
                  <i class="fas fa-check-double me-1"></i>Full Balance
                </button>
                <button type="button" class="btn btn-sm btn-outline-warning" id="btnPayHalf">
                  Half
                </button>
              </div>
            </div>

            <!-- ── PAYMENT METHOD ── -->
            <div class="mb-3">
              <label for="id_payment_method" class="form-label fw-semibold">
                Payment Method <span class="text-danger">*</span>
              </label>
              <select name="payment_method" id="id_payment_method" class="form-select" required>
                <option value="">— Select method —</option>
                {% for val, label in form.fields.payment_method.choices %}
                  {% if val %}
                  <option value="{{ val }}"
                    {% if form.payment_method.value == val %}selected{% endif %}>
                    {{ label }}
                  </option>
                  {% endif %}
                {% endfor %}
              </select>
              {% if form.payment_method.errors %}
              <div class="text-danger small mt-1">{{ form.payment_method.errors }}</div>
              {% endif %}
            </div>

            <!-- ── PAYMENT DATE ── -->
            <div class="mb-3">
              <label for="id_payment_date" class="form-label fw-semibold">Payment Date</label>
              <input type="date" name="payment_date" id="id_payment_date"
                     class="form-control"
                     value="{{ form.payment_date.value|date:'Y-m-d'|default:today }}">
            </div>

            <!-- ── MOBILE MONEY (shown when method = mobile_money) ── -->
            <div id="mobileMoneyCols" class="row g-2 mb-3" style="display:none">
              <div class="col-sm-6">
                <label class="form-label">Provider</label>
                <select name="mobile_money_provider" id="id_mobile_money_provider" class="form-select">
                  {% for val, label in form.fields.mobile_money_provider.choices %}
                  <option value="{{ val }}"
                    {% if form.mobile_money_provider.value == val %}selected{% endif %}>
                    {{ label }}
                  </option>
                  {% endfor %}
                </select>
              </div>
              <div class="col-sm-6">
                <label class="form-label">Mobile Money Number</label>
                <input type="text" name="mobile_money_number" id="id_mobile_money_number"
                       class="form-control"
                       value="{{ form.mobile_money_number.value|default:'' }}"
                       placeholder="e.g. 677000000">
              </div>
            </div>

            <!-- ── BANK / CHEQUE (shown when method = bank_transfer or check) ── -->
            <div id="bankCols" class="row g-2 mb-3" style="display:none">
              <div class="col-sm-6">
                <label class="form-label">Bank Name</label>
                <input type="text" name="bank_name" id="id_bank_name"
                       class="form-control"
                       value="{{ form.bank_name.value|default:'' }}">
              </div>
              <div class="col-sm-6">
                <label class="form-label">Transaction / Cheque #</label>
                <input type="text" name="transaction_id" id="id_transaction_id"
                       class="form-control"
                       value="{{ form.transaction_id.value|default:'' }}">
              </div>
            </div>

            <!-- ── STATUS ── -->
            <div class="mb-3">
              <label for="id_status" class="form-label fw-semibold">Status</label>
              <select name="status" id="id_status" class="form-select">
                {% for val, label in form.fields.status.choices %}
                <option value="{{ val }}"
                  {% if form.status.value == val or val == 'completed' and not form.status.value %}selected{% endif %}>
                  {{ label }}
                </option>
                {% endfor %}
              </select>
            </div>

            <!-- ── NOTES ── -->
            <div class="mb-3">
              <label for="id_notes" class="form-label">Notes</label>
              <textarea name="notes" id="id_notes" class="form-control" rows="2"
                        placeholder="Optional remarks…">{{ form.notes.value|default:'' }}</textarea>
            </div>

            <!-- ── SUBMIT ── -->
            <div class="d-flex gap-2 mt-4 pt-2 border-top">
              <button type="submit" class="btn btn-success btn-submit-payment" id="btnSubmit">
                <i class="fas fa-check me-1"></i> Record Payment
              </button>
              <a href="{% url 'finance:invoice_list' %}" class="btn btn-outline-secondary">
                Cancel
              </a>
            </div>

          </form>
        </div>
      </div>

    </div>
  </div>
</div>
{% endblock %}


{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
(function () {
  'use strict';

  // ── Format XAF number ──────────────────────────────────────────
  const fmt = n => (n !== null && n !== undefined && n !== '')
    ? Number(n).toLocaleString('fr-CM') + ' XAF' : '—';

  // ── Select2 on invoice dropdown ────────────────────────────────
  const $invSel = $('#id_invoice');
  if ($invSel.length) {
    $invSel.select2({
      theme: 'bootstrap-5',
      placeholder: 'Type to search invoice or student name…',
      allowClear: true,
      width: '100%',
    });

    // Update preview card whenever invoice changes
    $invSel.on('change', function () {
      const opt = this.options[this.selectedIndex];
      const preview = document.getElementById('invoicePreview');
      const quickBtns = document.getElementById('quickFillBtns');
      if (!opt || !opt.value) {
        preview.classList.remove('visible');
        if (quickBtns) quickBtns.style.setProperty('display', 'none', 'important');
        return;
      }
      document.getElementById('prev_student').textContent = opt.dataset.studentName || '—';
      document.getElementById('prev_number').textContent  = opt.dataset.number      || '—';
      document.getElementById('prev_type').textContent    = opt.dataset.type        || '—';
      document.getElementById('prev_due').textContent     = opt.dataset.due         || '—';
      document.getElementById('prev_total').textContent   = fmt(opt.dataset.total);
      document.getElementById('prev_paid').textContent    = fmt(opt.dataset.paid);
      document.getElementById('prev_balance').textContent = fmt(opt.dataset.balance);
      preview.classList.add('visible');
      if (quickBtns) quickBtns.style.removeProperty('display');
    });

    // Trigger on load if already selected (pre-populated)
    if ($invSel.val()) $invSel.trigger('change');
  }

  // ── Quick-fill amount buttons ───────────────────────────────────
  const amtField = document.getElementById('id_amount');
  const getBalance = () => {
    const opt = document.getElementById('id_invoice');
    if (!opt) return null;
    const sel = opt.options[opt.selectedIndex];
    return sel && sel.value ? Number(sel.dataset.balance) : null;
  };
  document.getElementById('btnPayFull')?.addEventListener('click', () => {
    const b = getBalance();
    if (b !== null) amtField.value = Math.ceil(b);
  });
  document.getElementById('btnPayHalf')?.addEventListener('click', () => {
    const b = getBalance();
    if (b !== null) amtField.value = Math.ceil(b / 2);
  });

  // ── Show quick-fill buttons if coming in with locked_invoice ───
  {% if locked_invoice %}
  const qb = document.getElementById('quickFillBtns');
  if (qb) qb.style.removeProperty('display');
  document.getElementById('btnPayFull')?.addEventListener('click', () => {
    amtField.value = Math.ceil({{ locked_invoice.balance }});
  });
  document.getElementById('btnPayHalf')?.addEventListener('click', () => {
    amtField.value = Math.ceil({{ locked_invoice.balance }} / 2);
  });
  {% endif %}

  // ── Payment method → show/hide extra fields ─────────────────────
  const methodSel = document.getElementById('id_payment_method');
  const mmCols    = document.getElementById('mobileMoneyCols');
  const bankCols  = document.getElementById('bankCols');

  function toggleMethod() {
    const v = methodSel ? methodSel.value : '';
    if (mmCols)   mmCols.style.display   = (v === 'mobile_money')                      ? '' : 'none';
    if (bankCols) bankCols.style.display = (v === 'bank_transfer' || v === 'check')    ? '' : 'none';
  }
  if (methodSel) {
    methodSel.addEventListener('change', toggleMethod);
    toggleMethod();
  }

  // ── Double-submit prevention ────────────────────────────────────
  const form   = document.getElementById('paymentForm');
  const btnSub = document.getElementById('btnSubmit');
  let submitted = false;

  form.addEventListener('submit', function (e) {
    if (submitted) {
      e.preventDefault();
      return;
    }
    if (!form.checkValidity()) {
      e.preventDefault();
      form.classList.add('was-validated');
      return;
    }
    submitted = true;
    btnSub.disabled = true;
    btnSub.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status"></span>Processing…';
  });

})();
</script>
{% endblock %}