{% extends "admin_base.html" %}
{% block title %}Registrations | Nexora Admin{% endblock %}
{% block content %}
<div class="admin-head">
  <p class="eyebrow">Player Data</p>
  <h1>Registrations</h1>
  <p>Filter registrations, verify payments, and export Excel/PDF reports. <strong>Under Verification rows are highlighted in yellow</strong>.</p>
</div>

<section class="admin-panel">
  <div class="ajax-feedback" role="status" aria-live="polite" hidden></div>
  <h2><i class="fas fa-filter"></i> Search &amp; Filter</h2>

  <form class="filter-bar" method="get" action="{{ url_for('admin_registrations') }}">
    <label>Search <span class="field-hint">name / email / phone / team</span>
      <input name="q" value="{{ filters.q }}" placeholder="e.g. Ahmed or ahmed@mail.com">
    </label>
    <label>Game
      <select name="game_id">
        <option value="">All games</option>
        {% for game in games %}
        <option value="{{ game.id }}" {% if filters.game_id == game.id %}selected{% endif %}>{{ game.title }}</option>
        {% endfor %}
      </select>
    </label>
    <label>Payment Status
      <select name="status">
        <option value="">All</option>
        <option value="under_verification" {% if filters.status == 'under_verification' %}selected{% endif %}>Under Verification</option>
        <option value="paid" {% if filters.status == 'paid' %}selected{% endif %}>Paid only</option>
        <option value="unpaid" {% if filters.status == 'unpaid' %}selected{% endif %}>Unpaid only</option>
        <option value="partial" {% if filters.status == 'partial' %}selected{% endif %}>Partial</option>
        <option value="refunded" {% if filters.status == 'refunded' %}selected{% endif %}>Refunded</option>
      </select>
    </label>
    <label>Registration Type
      <select name="entry_type">
        <option value="">All types</option>
        <option value="individual" {% if filters.entry_type == 'individual' %}selected{% endif %}>Individual</option>
        <option value="group" {% if filters.entry_type == 'group' %}selected{% endif %}>Group / Team</option>
      </select>
    </label>
    <label>Payment Method
      <select name="payment_method">
        <option value="">All methods</option>
        {% for method in payment_methods %}<option value="{{ method.payment_method }}" {% if filters.payment_method == method.payment_method %}selected{% endif %}>{{ method.payment_method }}</option>{% endfor %}
      </select>
    </label>
    <label>Check-In State
      <select name="checkin_status">
        <option value="">All states</option>
        <option value="pending" {% if filters.checkin_status == 'pending' %}selected{% endif %}>Not Arrived</option>
        <option value="approved" {% if filters.checkin_status == 'approved' %}selected{% endif %}>Checked In</option>
        <option value="rejected" {% if filters.checkin_status == 'rejected' %}selected{% endif %}>Rejected</option>
      </select>
    </label>
    <label>From Date
      <input type="date" name="date_from" value="{{ filters.date_from }}">
    </label>
    <label>To Date
      <input type="date" name="date_to" value="{{ filters.date_to }}">
    </label>
    <div class="filter-actions">
      <button class="btn primary small" type="submit"><i class="fas fa-magnifying-glass"></i> Apply</button>
      <a class="btn outline small" href="{{ url_for('admin_registrations') }}"><i class="fas fa-rotate-left"></i>
        Reset</a>
    </div>
  </form>

  <div class="result-summary">
    <span><strong>{{ totals.shown }}</strong> result{{ '' if totals.shown == 1 else 's' }}</span>
    <span class="dot-paid">{{ totals.paid }} paid</span>
    <span class="dot-unpaid">{{ totals.unpaid }} unpaid</span>
    <span class="dot-verification">{{ totals.under_verification }} under verification</span>
    {% if can('export_excel_reports') %}<a class="btn primary small" style="margin-left:auto;"
      href="{{ url_for('export_registrations', **request.args) }}">
      <i class="fas fa-file-excel"></i> Export to Excel
    </a>
    <a class="btn outline small" href="{{ url_for('export_registrations_pdf', **request.args) }}">
      <i class="fas fa-file-pdf"></i> Export PDF
    </a>{% endif %}
  </div>

  <div class="game-registration-tabs" role="tablist" aria-label="Game registrations">
    <button class="game-registration-tab {% if not filters.game_id %}active{% endif %}" type="button" role="tab"
      data-game-tab="all">All Games <span>{{ rows|length }}</span></button>
    {% for game in games %}
    <button class="game-registration-tab {% if filters.game_id == game.id %}active{% endif %}" type="button" role="tab"
      data-game-tab="{{ game.id }}">{{ game.title }} <span>{{ rows_by_game[game.id]|length }}</span></button>
    {% endfor %}
  </div>

  <section class="game-registration-panel {% if not filters.game_id %}active{% endif %}" data-game-panel="all" role="tabpanel">
    <div class="game-panel-heading"><div><p class="eyebrow">Game Registrations</p><h2>All Games</h2></div><span>{{ rows|length }} registration{{ '' if rows|length == 1 else 's' }}</span></div>
    <div class="admin-table-wrap game-registration-table"><table>
      <thead><tr><th>Ticket &amp; Player</th><th>Game</th><th>Team / Members</th><th>Payment</th><th>Check-In</th><th>Options</th></tr></thead>
      <tbody>{% for row in rows %}<tr class="game-registration-row row-{{ row.payment_status }}">
        <td><strong>{{ row.full_name }}</strong><small>{{ row.ticket_serial }}</small><small>{{ row.email }} · {{ row.phone }}</small></td>
        <td><strong>{{ row.game_title }}</strong><small>{{ row.platform }}</small></td>
        <td><strong>{{ row.team_name or 'Individual Entry' }}</strong><small>{% if row.team_id %}{{ row.team_id }} · {% endif %}{{ row.member_names|join(', ') }}</small></td>
        <td>{% if can('confirm_payments') %}<form method="post" action="{{ url_for('update_payment', reg_id=row.id) }}" class="inline-payment-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><select name="payment_status"><option value="under_verification" {% if row.payment_status == 'under_verification' %}selected{% endif %}>Under Verification</option><option value="unpaid" {% if row.payment_status == 'unpaid' %}selected{% endif %}>Unpaid</option><option value="paid" {% if row.payment_status == 'paid' %}selected{% endif %}>Paid</option></select></form>{% else %}<span class="badge {{ row.payment_status }}">{{ row.payment_status|replace('_', ' ')|title }}</span>{% endif %}<small>Total: {{ row.total_payable }} · Paid: <span data-payment-amount>{{ row.amount_paid }}</span></small><small class="remaining-value">Remaining: <span data-remaining-amount>{{ row.remaining_amount }}</span></small></td>
        <td><span class="checkin-chip {{ 'ci-in' if row.entry_status == 'approved' else ('ci-rej' if row.entry_status == 'rejected' else 'ci-wait') }}">{{ 'Checked In' if row.entry_status == 'approved' else ('Rejected' if row.entry_status == 'rejected' else 'Not Arrived') }}</span></td>
        <td class="registration-options"><a class="mini-action" href="{{ url_for('registration_view', reg_id=row.id) }}"><i class="fas fa-eye"></i> View</a>{% if can('edit_registrations') %}<a class="mini-action" href="{{ url_for('edit_registration', reg_id=row.id) }}"><i class="fas fa-pen"></i> Edit</a>{% endif %}{% if can('download_pdf_tickets') %}<a class="mini-action" href="{{ url_for('registration_ticket_pdf', reg_id=row.id) }}"><i class="fas fa-file-pdf"></i> PDF</a>{% endif %}{% if can('confirm_payments') %}<button class="mini-action send-email-btn" type="button" data-email-url="{{ url_for('send_registration_email', reg_id=row.id) }}" data-email-status="{{ row.payment_status }}"><i class="fas fa-envelope"></i> Email</button>{% endif %}</td>
      </tr>{% else %}<tr><td colspan="6" class="muted-line">No registrations yet.</td></tr>{% endfor %}</tbody>
    </table></div>
  </section>

  {% for game in games %}
  <section class="game-registration-panel {% if filters.game_id == game.id %}active{% endif %}" data-game-panel="{{ game.id }}" role="tabpanel">
    <div class="game-panel-heading"><div><p class="eyebrow">Game Registrations</p><h2>{{ game.title }}</h2></div><span>{{ rows_by_game[game.id]|length }} registration{{ '' if rows_by_game[game.id]|length == 1 else 's' }}</span></div>
    <div class="admin-table-wrap game-registration-table"><table>
      <thead><tr><th>Ticket &amp; Player</th><th>Team / Members</th><th>Payment</th><th>Check-In</th><th>Options</th></tr></thead>
      <tbody>{% for row in rows_by_game[game.id] %}<tr class="game-registration-row row-{{ row.payment_status }}">
        <td><strong>{{ row.full_name }}</strong><small>{{ row.ticket_serial }}</small><small>{{ row.email }} · {{ row.phone }}</small></td>
        <td><strong>{{ row.team_name or 'Individual Entry' }}</strong><small>{% if row.team_id %}{{ row.team_id }} · {% endif %}{{ row.member_names|join(', ') }}</small></td>
        <td>{% if can('confirm_payments') %}<form method="post" action="{{ url_for('update_payment', reg_id=row.id) }}" class="inline-payment-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><select name="payment_status"><option value="under_verification" {% if row.payment_status == 'under_verification' %}selected{% endif %}>Under Verification</option><option value="unpaid" {% if row.payment_status == 'unpaid' %}selected{% endif %}>Unpaid</option><option value="paid" {% if row.payment_status == 'paid' %}selected{% endif %}>Paid</option></select></form>{% else %}<span class="badge {{ row.payment_status }}">{{ row.payment_status|replace('_', ' ')|title }}</span>{% endif %}<small>Total: {{ row.total_payable }} · Paid: <span data-payment-amount>{{ row.amount_paid }}</span></small><small class="remaining-value">Remaining: <span data-remaining-amount>{{ row.remaining_amount }}</span></small></td>
        <td><span class="checkin-chip {{ 'ci-in' if row.entry_status == 'approved' else ('ci-rej' if row.entry_status == 'rejected' else 'ci-wait') }}">{{ 'Checked In' if row.entry_status == 'approved' else ('Rejected' if row.entry_status == 'rejected' else 'Not Arrived') }}</span></td>
        <td class="registration-options"><a class="mini-action" href="{{ url_for('registration_view', reg_id=row.id) }}"><i class="fas fa-eye"></i> View</a>{% if can('edit_registrations') %}<a class="mini-action" href="{{ url_for('edit_registration', reg_id=row.id) }}"><i class="fas fa-pen"></i> Edit</a>{% endif %}{% if can('download_pdf_tickets') %}<a class="mini-action" href="{{ url_for('registration_ticket_pdf', reg_id=row.id) }}"><i class="fas fa-file-pdf"></i> PDF</a>{% endif %}{% if can('confirm_payments') %}<button class="mini-action send-email-btn" type="button" data-email-url="{{ url_for('send_registration_email', reg_id=row.id) }}" data-email-status="{{ row.payment_status }}"><i class="fas fa-envelope"></i> Email</button>{% endif %}</td>
      </tr>{% else %}<tr><td colspan="5" class="muted-line">No registrations for this game yet.</td></tr>{% endfor %}</tbody>
    </table></div>
  </section>
  {% endfor %}

</section>
<script>
  document.querySelectorAll('[data-game-tab]').forEach(function (tab) {
    tab.addEventListener('click', function () {
      document.querySelectorAll('[data-game-tab]').forEach(function (item) { item.classList.toggle('active', item === tab); });
      document.querySelectorAll('[data-game-panel]').forEach(function (panel) { panel.classList.toggle('active', panel.dataset.gamePanel === tab.dataset.gameTab); });
    });
  });

  (function () {
    var feedback = document.querySelector('.ajax-feedback');
    var timer;

    function showFeedback(message, isError) {
      feedback.textContent = message;
      feedback.hidden = false;
      feedback.classList.toggle('error', Boolean(isError));
      clearTimeout(timer);
      timer = setTimeout(function () { feedback.hidden = true; }, 4200);
    }

    function updateSummary() {
      var counts = { paid: 0, unpaid: 0, under_verification: 0 };
      document.querySelectorAll('.game-registration-row').forEach(function (row) {
        Object.keys(counts).forEach(function (status) {
          if (row.classList.contains('row-' + status)) counts[status] += 1;
        });
      });
      var paid = document.querySelector('.dot-paid');
      var unpaid = document.querySelector('.dot-unpaid');
      var verification = document.querySelector('.dot-verification');
      if (paid) paid.textContent = counts.paid + ' paid';
      if (unpaid) unpaid.textContent = counts.unpaid + ' unpaid';
      if (verification) verification.textContent = counts.under_verification + ' under verification';
    }

    document.querySelectorAll('.inline-payment-form select').forEach(function (select) {
      var form = select.closest('form');
      form.addEventListener('submit', function (event) { event.preventDefault(); });
      select.addEventListener('change', async function () {
        var row = select.closest('.game-registration-row');
        var selectedStatus = select.value;
        var previousStatus = ['paid', 'unpaid', 'under_verification'].find(function (status) {
          return row.classList.contains('row-' + status);
        }) || 'under_verification';
        var payload = new FormData(form);
        select.disabled = true;
        try {
          var response = await fetch(form.action, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            body: payload,
            credentials: 'same-origin'
          });
          var result = await response.json();
          if (!response.ok || !result.ok) throw new Error(result.message || 'Status update failed.');
          ['paid', 'unpaid', 'under_verification'].forEach(function (status) {
            row.classList.remove('row-' + status);
          });
          row.classList.add('row-' + result.status);
          select.value = result.status;
          row.querySelectorAll('[data-payment-amount]').forEach(function (item) { item.textContent = result.amount_paid; });
          row.querySelectorAll('[data-remaining-amount]').forEach(function (item) { item.textContent = result.remaining_amount; });
          updateSummary();
          showFeedback(result.message, false);
        } catch (error) {
          showFeedback(error.message || 'Status update failed. Please try again.', true);
          select.value = previousStatus;
        } finally {
          select.disabled = false;
        }
      });
    });
    document.querySelectorAll('.send-email-btn').forEach(function (btn) {
      btn.addEventListener('click', async function () {
        var url = btn.dataset.emailUrl;
        btn.disabled = true;
        try {
          var csrfField = document.querySelector('[name="csrf_token"]');
          var csrfVal = csrfField ? csrfField.value : "";
          var response = await fetch(url, {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json', 'X-CSRF-Token': csrfVal },
            credentials: 'same-origin'
          });
          var result = await response.json();
          if (!response.ok || !result.ok) throw new Error(result.message || 'Failed to send email.');
          showFeedback(result.message, false);
        } catch (error) {
          showFeedback(error.message || 'Failed to send email. Please try again.', true);
        } finally {
          btn.disabled = false;
        }
      });
    });
  }());
</script>
{% endblock %}
