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

{% block extra_css %}
<style>
  .scope-card {
    border: 2px solid #dee2e6; border-radius: 8px; cursor: pointer;
    transition: border-color .15s, background .15s;
    padding: 10px 14px; display: flex; align-items: center; gap: 8px; user-select: none;
  }
  .scope-card:hover { border-color: #0d6efd; background: #f0f5ff; }
  .scope-card.active { border-color: #0d6efd; background: #e7f0ff; font-weight: 600; }
  .scope-card input[type=radio] { accent-color: #0d6efd; }
  #class-picker { display: none; }
  .class-chip {
    display: inline-flex; align-items: center; gap: 4px;
    border: 1.5px solid #ced4da; border-radius: 20px; padding: 3px 10px;
    cursor: pointer; font-size: .82rem; transition: border-color .12s, background .12s; user-select: none;
  }
  .class-chip:hover { border-color: #0d6efd; }
  .class-chip input { accent-color: #0d6efd; width: 14px; height: 14px; }
  .class-chip.checked { background: #e7f0ff; border-color: #0d6efd; font-weight: 600; }
  .stat-card { border-left: 4px solid; border-radius: 6px; }
  .stat-card.blue  { border-left-color: #0d6efd; }
  .stat-card.amber { border-left-color: #fd7e14; }
  .stat-card.green { border-left-color: #198754; }
  .stat-card.teal  { border-left-color: #0dcaf0; }
  .preview-table { max-height: 430px; overflow-y: auto; }
  .preview-table thead th { position: sticky; top: 0; background: #f8f9fa; z-index: 1; }
  .amount { font-variant-numeric: tabular-nums; }
</style>
{% 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">Bulk Invoice Generation</h1>
      <p class="text-muted mb-0">Create invoices for all active students at once</p>
    </div>
    <a href="{% url 'finance:invoice_list' %}" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Invoices
    </a>
  </div>

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

  {% if not preview %}
  <!-- STEP 1: FORM -->
  <div class="row justify-content-center">
    <div class="col-lg-7">
      <div class="card shadow">
        <div class="card-header py-3 bg-primary text-white">
          <h6 class="m-0 fw-bold">
            <i class="fas fa-magic me-2"></i>Step 1 — Choose Invoice Type, Scope &amp; Due Date
          </h6>
        </div>
        <div class="card-body">
          <div class="alert alert-info mb-4">
            <i class="fas fa-info-circle me-2"></i>
            Creates one invoice per active student using the correct fee structure for their class.
            Students who already have an invoice of the same type for the selected year are skipped.
            <strong>Fee structures must be set up first</strong>
            (<a href="{% url 'finance:fee_list' %}">Finance → Fee Structures</a>).
          </div>

          <form method="post" id="bulkForm">
            {% csrf_token %}

            <!-- Academic Year -->
            <div class="mb-3">
              <label class="form-label fw-bold">Academic Year <span class="text-danger">*</span></label>
              <select class="form-select" name="academic_year" required>
                {% for yr in year_choices %}
                <option value="{{ yr }}" {% if yr == default_year %}selected{% endif %}>{{ yr }}</option>
                {% endfor %}
              </select>
            </div>

            <!-- Invoice Type (replaces Term) -->
            <div class="mb-3">
              <label class="form-label fw-bold">Invoice Type <span class="text-danger">*</span></label>
              <select class="form-select" name="invoice_type" required>
                <option value="">Select type…</option>
                {% for val, label in invoice_type_choices %}
                <option value="{{ val }}">{{ label }}</option>
                {% endfor %}
              </select>
              <div class="form-text">
                Select <em>Registration</em> for enrollment fees,
                <em>1st/2nd Installment</em> for tuition payments.
              </div>
            </div>

            <!-- Due Date -->
            <div class="mb-4">
              <label class="form-label fw-bold">Due Date <span class="text-danger">*</span></label>
              <input type="date" class="form-control" name="due_date" required>
            </div>

            <!-- Scope -->
            <div class="mb-4">
              <label class="form-label fw-bold">Generate For</label>
              <div class="d-flex flex-wrap gap-2 mb-3">
                <label class="scope-card active" data-scope="all">
                  <input type="radio" name="scope" value="all" checked>
                  <i class="fas fa-users text-primary"></i> All Students
                </label>
                <label class="scope-card" data-scope="nursery">
                  <input type="radio" name="scope" value="nursery">
                  <i class="fas fa-child text-warning"></i> Nursery Section
                </label>
                <label class="scope-card" data-scope="primary">
                  <input type="radio" name="scope" value="primary">
                  <i class="fas fa-book text-success"></i> Primary (Class&nbsp;1–5)
                </label>
                <label class="scope-card" data-scope="class6">
                  <input type="radio" name="scope" value="class6">
                  <i class="fas fa-graduation-cap text-danger"></i> Class&nbsp;6 Only
                </label>
                <label class="scope-card" data-scope="english">
                  <input type="radio" name="scope" value="english">
                  <i class="fas fa-flag text-info"></i> English Section
                </label>
                <label class="scope-card" data-scope="bilingual">
                  <input type="radio" name="scope" value="bilingual">
                  <i class="fas fa-language" style="color:#6f42c1"></i> Bilingual Section
                </label>
                <label class="scope-card" data-scope="specific">
                  <input type="radio" name="scope" value="specific">
                  <i class="fas fa-filter text-secondary"></i> Specific Classes…
                </label>
              </div>

              <div id="class-picker" class="border rounded p-3 bg-light">
                <p class="small text-muted mb-2 fw-bold">Select the classes to include:</p>
                <div class="d-flex flex-wrap gap-2">
                  {% for cls in all_classes %}
                  <label class="class-chip" id="chip-{{ cls.pk }}">
                    <input type="checkbox" name="class_ids" value="{{ cls.pk }}">
                    {{ cls }}
                    <span class="badge bg-secondary ms-1" style="font-size:.7rem">
                      {{ cls.get_section_type_display }}
                    </span>
                  </label>
                  {% endfor %}
                </div>
              </div>
            </div>

            <div class="d-grid">
              <button type="submit" class="btn btn-primary btn-lg">
                <i class="fas fa-eye me-2"></i>Preview Invoices
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  {% else %}
  <!-- STEP 2: PREVIEW -->

  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="card stat-card blue shadow-sm h-100 py-2 px-3">
        <div class="text-uppercase fw-bold mb-1 text-primary" style="font-size:.72rem">
          Invoices to Create
        </div>
        <div class="h3 mb-0 fw-bold text-success">{{ total_to_create }}</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="card stat-card amber shadow-sm h-100 py-2 px-3">
        <div class="text-uppercase fw-bold mb-1" style="font-size:.72rem;color:#fd7e14">
          Already Invoiced
        </div>
        <div class="h3 mb-0 fw-bold text-warning">{{ skip_count }} skipped</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="card stat-card green shadow-sm h-100 py-2 px-3">
        <div class="text-uppercase fw-bold mb-1 text-success" style="font-size:.72rem">Total Value</div>
        <div class="h3 mb-0 fw-bold amount" data-raw="{{ total_amount }}">
          {{ total_amount|floatformat:0 }} XAF
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="card stat-card teal shadow-sm h-100 py-2 px-3">
        <div class="text-uppercase fw-bold mb-1" style="font-size:.72rem;color:#0dcaf0">Type</div>
        <div class="h6 mb-0 fw-bold">{{ academic_year }}</div>
        <small class="text-muted">{{ invoice_type|title }} — Due: {{ due_date }}</small>
      </div>
    </div>
  </div>

  {% if total_to_create == 0 %}
  <div class="alert alert-warning">
    <i class="fas fa-exclamation-triangle me-2"></i>
    <strong>No invoices to create.</strong>
    Either all matching students already have this invoice type for {{ academic_year }},
    or no fee structures are set up for this year/section combination.
    <a href="{% url 'finance:fee_list' %}">Check fee structures →</a>
  </div>
  <a href="{% url 'finance:bulk_invoice' %}" class="btn btn-outline-secondary">
    <i class="fas fa-arrow-left me-2"></i>Start Over
  </a>

  {% else %}

  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
      <h6 class="m-0 fw-bold text-primary">
        Preview — {{ total_to_create }} invoice{{ total_to_create|pluralize }} will be created
      </h6>
      <span class="badge bg-info">{{ academic_year }} — {{ invoice_type|title }}</span>
    </div>
    <div class="card-body p-0">
      <div class="preview-table">
        <table class="table table-hover table-sm mb-0">
          <thead class="table-light">
            <tr>
              <th class="ps-3" style="width:42px">#</th>
              <th>Student</th>
              <th>Class</th>
              <th>Fee Tier</th>
              <th class="text-end pe-3">Amount (XAF)</th>
            </tr>
          </thead>
          <tbody>
            {% for item in preview %}
            <tr>
              <td class="ps-3 text-muted">{{ forloop.counter }}</td>
              <td>
                <strong>{{ item.student.get_full_name }}</strong>
                {% if item.is_new_pupil %}
                <span class="badge bg-warning text-dark ms-1" style="font-size:.7rem">New</span>
                {% endif %}
              </td>
              <td>
                <span class="badge bg-light text-dark border">
                  {{ item.student.current_class }}
                </span>
              </td>
              <td class="small text-muted">
                {{ item.fee.get_section_display }} — {{ item.fee.get_class_group_display }}
              </td>
              <td class="text-end pe-3 fw-bold text-success amount" data-raw="{{ item.amount }}">
                {{ item.amount|floatformat:0 }}
              </td>
            </tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light fw-bold border-top">
            <tr>
              <td colspan="4" class="ps-3 text-end py-2">Grand Total:</td>
              <td class="text-end pe-3 text-success amount" data-raw="{{ total_amount }}">
                {{ total_amount|floatformat:0 }} XAF
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

  <div class="row justify-content-center">
    <div class="col-lg-6">
      <div class="card border-success shadow">
        <div class="card-header bg-success text-white py-3">
          <h6 class="m-0 fw-bold">
            <i class="fas fa-check-circle me-2"></i>Step 2 — Confirm &amp; Create
          </h6>
        </div>
        <div class="card-body">
          <p class="mb-3">
            You are about to create
            <strong>{{ total_to_create }} invoice{{ total_to_create|pluralize }}</strong>
            totalling
            <strong class="amount" data-raw="{{ total_amount }}">
              {{ total_amount|floatformat:0 }} XAF
            </strong>
            for <strong>{{ academic_year }} — {{ invoice_type|title }}</strong>.
            All invoices will be created with status
            <span class="badge bg-secondary">Draft</span>.
          </p>
          <form method="post" class="d-flex gap-3">
            {% csrf_token %}
            <input type="hidden" name="academic_year"  value="{{ academic_year }}">
            <input type="hidden" name="invoice_type"   value="{{ invoice_type }}">
            <input type="hidden" name="due_date"       value="{{ due_date }}">
            <input type="hidden" name="scope"          value="{{ scope }}">
            {% for cid in class_ids %}
            <input type="hidden" name="class_ids" value="{{ cid }}">
            {% endfor %}
            <input type="hidden" name="confirmed" value="yes">

            <a href="{% url 'finance:bulk_invoice' %}" class="btn btn-outline-secondary flex-fill">
              <i class="fas fa-arrow-left me-2"></i>Start Over
            </a>
            <button type="submit" class="btn btn-success flex-fill">
              <i class="fas fa-bolt me-2"></i>
              Create {{ total_to_create }} Invoice{{ total_to_create|pluralize }}
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>

  {% endif %}
  {% endif %}

</div>
{% endblock %}

{% block extra_js %}
<script>
document.querySelectorAll('.scope-card').forEach(card => {
  card.addEventListener('click', () => {
    document.querySelectorAll('.scope-card').forEach(c => c.classList.remove('active'));
    card.classList.add('active');
    document.getElementById('class-picker').style.display =
      card.dataset.scope === 'specific' ? 'block' : 'none';
  });
});

document.querySelectorAll('.class-chip input[type=checkbox]').forEach(cb => {
  cb.addEventListener('change', () => {
    cb.closest('.class-chip').classList.toggle('checked', cb.checked);
  });
});

function fmtXAF(raw) {
  const n = parseInt(String(raw).replace(/[^\d]/g, ''));
  if (isNaN(n)) return raw;
  return n.toLocaleString('fr-CM');
}
document.querySelectorAll('.amount').forEach(el => {
  const raw    = el.dataset.raw || el.textContent.replace(/[^\d]/g, '');
  const hasXAF = el.textContent.includes('XAF');
  el.textContent = fmtXAF(raw) + (hasXAF ? ' XAF' : '');
});
</script>
{% endblock %}