{% extends 'base.html' %}
{% load static %}
{% block title %}{{ title }} — Rapha-Bethel BNPS{% endblock %}

{% block content %}
<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h1 class="h3 mb-0">{{ title }}</h1>
      <p class="text-muted mb-0">Assign a fee structure to a student for the academic year</p>
    </div>
    <a href="{% url 'finance:enrollment_fee_list' %}" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-1"></i>Back
    </a>
  </div>

  <div class="row justify-content-center">
    <div class="col-md-8">
      <div class="card shadow">
        <div class="card-header py-3 bg-primary text-white">
          <h6 class="m-0"><i class="fas fa-user-graduate me-2"></i>Enrollment Fee Details</h6>
        </div>
        <div class="card-body">
          <form method="post">
            {% csrf_token %}
            {% if form.errors %}
            <div class="alert alert-danger">
              Please correct the errors below. {{ form.non_field_errors }}
            </div>
            {% endif %}

            <div class="row mb-3">
              <div class="col-md-6">
                <label class="form-label fw-bold">Student <span class="text-danger">*</span></label>
                {{ form.student }}
                {% if form.student.errors %}<div class="text-danger small">{{ form.student.errors }}</div>{% endif %}
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">Academic Year <span class="text-danger">*</span></label>
                {{ form.academic_year }}
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-bold">Fee Structure (Class Tier) <span class="text-danger">*</span></label>
              {{ form.fee_structure }}
              <div class="form-text">
                Select the row matching this student's class level and section.
              </div>
              {% if form.fee_structure.errors %}
              <div class="text-danger small">{{ form.fee_structure.errors }}</div>
              {% endif %}
            </div>

            <!-- Fee preview table (populated by JS) -->
            <div id="fee-preview" class="alert alert-light border mb-3" style="display:none;">
              <table class="table table-sm table-borderless mb-0">
                <tr>
                  <td class="text-muted">Registration (New)</td>
                  <td class="fw-bold text-end" id="prev-reg-new">—</td>
                </tr>
                <tr>
                  <td class="text-muted">Registration (Returning)</td>
                  <td class="fw-bold text-end" id="prev-reg-old">—</td>
                </tr>
                <tr><td colspan="2"><hr class="my-1"></td></tr>
                <tr>
                  <td class="text-muted">Total Annual Fees</td>
                  <td class="fw-bold text-primary text-end" id="prev-total">—</td>
                </tr>
                <tr>
                  <td class="text-muted">1st Installment</td>
                  <td class="text-success fw-bold text-end" id="prev-inst1">—</td>
                </tr>
                <tr>
                  <td class="text-muted">2nd Installment</td>
                  <td class="text-success fw-bold text-end" id="prev-inst2">—</td>
                </tr>
              </table>
            </div>

            <div class="mb-3">
              <div class="form-check">
                {{ form.is_new_pupil }}
                <label class="form-check-label fw-bold">New Pupil (first-time admission)</label>
              </div>
              <div class="form-text">
                Tick for new admissions — registration fee = 15,000 XAF.
                Leave unticked for returning pupils — registration fee = 10,000 XAF.
              </div>
            </div>

            <div class="row mb-3">
              <div class="col-md-6">
                <label class="form-label fw-bold">1st Installment Due Date</label>
                {{ form.installment_1_due }}
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">2nd Installment Due Date</label>
                {{ form.installment_2_due }}
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-bold">Notes</label>
              {{ form.notes }}
            </div>

            <div class="d-flex justify-content-end gap-2 mt-4">
              <a href="{% url 'finance:enrollment_fee_list' %}" class="btn btn-secondary">Cancel</a>
              <button type="submit" class="btn btn-primary">
                <i class="fas fa-save me-1"></i>Save Enrollment Record
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Fee structure quick-reference -->
    <div class="col-md-4">
      <div class="card shadow">
        <div class="card-header py-3">
          <h6 class="m-0 fw-bold text-primary">Available Fee Structures</h6>
        </div>
        <div class="card-body p-0">
          <table class="table table-sm table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th>Section / Tier</th>
                <th class="text-end">Total</th>
              </tr>
            </thead>
            <tbody>
              {% for fs in fee_structures %}
              <tr data-pk="{{ fs.pk }}"
                  data-reg-new="{{ fs.registration_new }}"
                  data-reg-old="{{ fs.registration_old }}"
                  data-total="{{ fs.total_fees }}"
                  data-inst1="{{ fs.installment_1 }}"
                  data-inst2="{{ fs.installment_2 }}">
                <td>
                  <span class="badge {% if fs.section == 'anglo' %}bg-primary{% else %}bg-success{% endif %} me-1">
                    {{ fs.get_section_display }}
                  </span>
                  {{ fs.get_class_group_display }}
                </td>
                <td class="text-end fw-bold">{{ fs.total_fees|floatformat:0 }}</td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Apply Bootstrap classes
document.querySelectorAll('input:not(.form-check-input):not([type="submit"]), select, textarea').forEach(el => {
  el.classList.add(el.tagName === 'SELECT' ? 'form-select' : 'form-control');
});

// Fee preview on structure select
const feeSelect = document.querySelector('[name="fee_structure"]');
const preview   = document.getElementById('fee-preview');
const rows      = document.querySelectorAll('table tbody tr[data-pk]');

function fmt(n) { return parseInt(n).toLocaleString('fr-CM') + ' XAF'; }

feeSelect?.addEventListener('change', () => {
  const pk  = feeSelect.value;
  const row = [...rows].find(r => r.dataset.pk === pk);
  if (!row) { preview.style.display = 'none'; return; }
  document.getElementById('prev-reg-new').textContent  = fmt(row.dataset.regNew);
  document.getElementById('prev-reg-old').textContent  = fmt(row.dataset.regOld);
  document.getElementById('prev-total').textContent    = fmt(row.dataset.total);
  document.getElementById('prev-inst1').textContent    = fmt(row.dataset.inst1);
  document.getElementById('prev-inst2').textContent    = fmt(row.dataset.inst2);
  preview.style.display = 'block';
});
</script>
{% endblock %}