{% 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">All amounts in XAF (Central African CFA Franc)</p>
    </div>
    <a href="{% url 'finance: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-9">
      <div class="card shadow">
        <div class="card-header py-3 bg-primary text-white">
          <h6 class="m-0"><i class="fas fa-money-check-alt me-2"></i>Fee Structure Details</h6>
        </div>
        <div class="card-body">
          <form method="post">
            {% csrf_token %}
            {% if form.errors %}
            <div class="alert alert-danger">
              <i class="fas fa-exclamation-circle me-2"></i>Please correct the errors below.
              {{ form.non_field_errors }}
            </div>
            {% endif %}

            <!-- Section & Class Group -->
            <h6 class="text-primary border-bottom pb-2 mb-3">Classification</h6>
            <div class="row mb-3">
              <div class="col-md-4">
                <label class="form-label fw-bold">Section <span class="text-danger">*</span></label>
                {{ form.section }}
                {% if form.section.errors %}<div class="text-danger small">{{ form.section.errors }}</div>{% endif %}
              </div>
              <div class="col-md-4">
                <label class="form-label fw-bold">Class Group <span class="text-danger">*</span></label>
                {{ form.class_group }}
                {% if form.class_group.errors %}<div class="text-danger small">{{ form.class_group.errors }}</div>{% endif %}
              </div>
              <div class="col-md-4">
                <label class="form-label fw-bold">Academic Year <span class="text-danger">*</span></label>
                {{ form.academic_year }}
              </div>
            </div>

            <!-- Registration Fees -->
            <h6 class="text-primary border-bottom pb-2 mb-3 mt-4">Registration Fees</h6>
            <div class="alert alert-light border mb-3 small">
              <i class="fas fa-info-circle me-1 text-info"></i>
              Registration fees differ for <strong>new admissions</strong> vs <strong>returning pupils</strong>.
              From your fee table: New = 15,000 XAF / Returning = 10,000 XAF.
            </div>
            <div class="row mb-3">
              <div class="col-md-6">
                <label class="form-label fw-bold">New Pupil Registration (XAF) <span class="text-danger">*</span></label>
                {{ form.registration_new }}
                {% if form.registration_new.errors %}<div class="text-danger small">{{ form.registration_new.errors }}</div>{% endif %}
              </div>
              <div class="col-md-6">
                <label class="form-label fw-bold">Returning Pupil Registration (XAF) <span class="text-danger">*</span></label>
                {{ form.registration_old }}
                {% if form.registration_old.errors %}<div class="text-danger small">{{ form.registration_old.errors }}</div>{% endif %}
              </div>
            </div>

            <!-- Tuition & Installments -->
            <h6 class="text-primary border-bottom pb-2 mb-3 mt-4">Annual Tuition &amp; Installments</h6>
            <div class="alert alert-light border mb-3 small">
              <i class="fas fa-info-circle me-1 text-info"></i>
              <strong>Total Fees must equal 1st Installment + 2nd Installment.</strong>
              The system will validate this before saving.
            </div>
            <div class="row mb-3">
              <div class="col-md-4">
                <label class="form-label fw-bold">Total Annual Fees (XAF) <span class="text-danger">*</span></label>
                {{ form.total_fees }}
                {% if form.total_fees.errors %}<div class="text-danger small">{{ form.total_fees.errors }}</div>{% endif %}
              </div>
              <div class="col-md-4">
                <label class="form-label fw-bold">1st Installment (XAF) <span class="text-danger">*</span></label>
                {{ form.installment_1 }}
                {% if form.installment_1.errors %}<div class="text-danger small">{{ form.installment_1.errors }}</div>{% endif %}
              </div>
              <div class="col-md-4">
                <label class="form-label fw-bold">2nd Installment (XAF) <span class="text-danger">*</span></label>
                {{ form.installment_2 }}
                {% if form.installment_2.errors %}<div class="text-danger small">{{ form.installment_2.errors }}</div>{% endif %}
              </div>
            </div>

            <!-- Live validation hint -->
            <div class="alert alert-info small mb-4" id="installment-check" style="display:none;">
              <span id="installment-msg"></span>
            </div>

            <!-- Optional class pins -->
            <h6 class="text-primary border-bottom pb-2 mb-3 mt-2">Optional — Pin to Specific Classes</h6>
            <div class="mb-3">
              <label class="form-label fw-bold">Specific Classes</label>
              {{ form.specific_classes }}
              <div class="form-text">Leave blank to apply to the whole class group.</div>
            </div>

            <!-- Settings -->
            <h6 class="text-primary border-bottom pb-2 mb-3 mt-4">Settings</h6>
            <div class="row mb-3">
              <div class="col-md-8">
                <label class="form-label fw-bold">Notes</label>
                {{ form.description }}
              </div>
              <div class="col-md-4 d-flex align-items-center mt-4">
                <div class="form-check">
                  {{ form.is_active }}
                  <label class="form-check-label fw-bold">Active</label>
                </div>
              </div>
            </div>

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

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

// Live installment validation
const fTotal = document.querySelector('[name="total_fees"]');
const fInst1 = document.querySelector('[name="installment_1"]');
const fInst2 = document.querySelector('[name="installment_2"]');
const checkDiv = document.getElementById('installment-check');
const checkMsg = document.getElementById('installment-msg');

function validateInstallments() {
  const t = parseFloat(fTotal?.value) || 0;
  const i1 = parseFloat(fInst1?.value) || 0;
  const i2 = parseFloat(fInst2?.value) || 0;
  if (!t && !i1 && !i2) { checkDiv.style.display = 'none'; return; }
  checkDiv.style.display = 'block';
  const sum = i1 + i2;
  if (sum === t) {
    checkDiv.className = 'alert alert-success small mb-4';
    checkMsg.textContent = `✓ ${i1.toLocaleString()} + ${i2.toLocaleString()} = ${t.toLocaleString()} XAF — correct!`;
  } else {
    checkDiv.className = 'alert alert-danger small mb-4';
    checkMsg.textContent = `✗ ${i1.toLocaleString()} + ${i2.toLocaleString()} = ${sum.toLocaleString()}, but Total is ${t.toLocaleString()} XAF — must be equal.`;
  }
}

[fTotal, fInst1, fInst2].forEach(el => el?.addEventListener('input', validateInstallments));
</script>
{% endblock %}