<?= $this->include('layout/header') ?>
<?php $tax = config('Tax'); $vatRate = isset($vatRate) ? (float)$vatRate : (float)($tax->vatRate ?? 0.15); $vatRatePct = (int) round($vatRate * 100); ?>
<?php $isArabic = (service('language')->getLocale() === 'ar'); ?>
<div class="card">
  <div class="card-header d-flex align-items-center">
    <i class="bi bi-receipt me-2"></i> <?= lang('App.payment_receipts') ?>
  </div>
  <div class="card-body">
    <?php if (session('success')): ?>
      <div class="alert alert-success"><?= esc(session('success')) ?></div>
    <?php elseif (session('error')): ?>
      <div class="alert alert-danger"><?= esc(session('error')) ?></div>
    <?php endif; ?>

    <div class="mb-4">
      <form method="get" action="/payments" class="input-group">
        <input type="text" name="q" value="<?= esc($query ?? '') ?>" class="form-control" placeholder="<?= lang('App.search_student_placeholder') ?>" />
        <button class="btn btn-outline-secondary" type="submit"><i class="bi bi-search"></i></button>
      </form>
      <?php if (!empty($students)): ?>
        <div class="table-responsive mt-3">
          <table class="table table-hover">
            <thead>
              <tr>
                <th><?= lang('App.student_id') ?></th>
                <th><?= lang('App.full_name') ?></th>
                <th><?= lang('App.parent_phone') ?></th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($students as $s): ?>
                <tr>
                  <td><?= esc($s['student_id'] ?? '') ?></td>
                  <td><?= esc(($s['first_name'] ?? '') . ' ' . ($s['last_name'] ?? '')) ?></td>
                  <td><?= esc($s['parent_phone'] ?? '') ?></td>
                  <td>
                    <button type="button" class="btn btn-sm btn-primary" onclick='selectStudent(<?= json_encode($s) ?>)'><i class="bi bi-plus"></i> <?= lang('App.select') ?></button>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php elseif (!empty($query)): ?>
        <div class="text-muted mt-3"><?= $isArabic ? 'لا توجد نتائج مطابقة للطلاب.' : 'No matching students found.' ?></div>
      <?php endif; ?>
    </div>

    <form method="post" action="/payments" id="receiptForm" data-confirm="<?= lang('App.save_and_print') ?>?">
      <?= csrf_field() ?>
      <input type="hidden" name="student_id" id="student_id" />

      <div class="row g-3">
        <div class="col-md-6">
          <div class="border rounded p-3 h-100">
            <div class="mb-2 fw-bold"><?= lang('App.selected_student') ?></div>
            <div id="studentInfo" class="text-muted"><?= lang('App.no_student_selected') ?></div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label"><?= lang('App.school_year') ?></label>
              <select class="form-select" name="school_year_id" required>
                <?php foreach (($schoolYears ?? []) as $y): ?>
                  <option value="<?= $y['id'] ?>"><?= esc($y['school_year'] ?? $y['sno'] ?? '') ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label"><?= lang('App.payment_method') ?></label>
              <select name="payment_method" class="form-select">
                <option value="cash"><?= lang('App.cash') ?></option>
                <option value="card"><?= lang('App.card') ?></option>
                <option value="transfer"><?= lang('App.transfer') ?></option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label"><?= lang('App.class') ?></label>
              <select class="form-select" name="class_id" required>
                <?php foreach (($classes ?? []) as $c): ?>
                  <option value="<?= $c['id'] ?>"><?= esc($isArabic ? ($c['name_ar'] ?? $c['name_en'] ?? '') : ($c['name_en'] ?? $c['name_ar'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label"><?= lang('App.section') ?></label>
              <select class="form-select" name="section_id" required>
                <?php foreach (($sections ?? []) as $s): ?>
                  <option value="<?= $s['id'] ?>"><?= esc($isArabic ? ($s['name_ar'] ?? $s['name_en'] ?? '') : ($s['name_en'] ?? $s['name_ar'] ?? '')) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </div>

      <hr />

      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label"><?= lang('App.payment_type') ?></label>
          <select class="form-select" id="ptSelect">
            <option value=""><?= lang('App.choose') ?></option>
            <?php foreach (($paymentTypes ?? []) as $pt): ?>
              <?php $ptLabel = $isArabic ? ($pt['description_ar'] ?? $pt['description_en'] ?? '') : ($pt['description_en'] ?? $pt['description_ar'] ?? ''); ?>
              <option value="<?= $pt['id'] ?>" data-amount="<?= esc($pt['amount'] ?? '0.00') ?>" data-label="<?= esc($ptLabel) ?>">
                <?= esc($ptLabel) ?> (<?= esc(number_format((float)($pt['amount'] ?? 0), 2)) ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label"><?= lang('App.description') ?></label>
          <input type="text" class="form-control" id="ptDesc" placeholder="<?= lang('App.optional_item_description') ?? lang('App.optional_field') ?>" />
        </div>
        <div class="col-md-3">
          <label class="form-label"><?= lang('App.amount') ?></label>
          <input type="number" step="0.01" class="form-control" id="ptAmount" value="0" />
        </div>
        <div class="col-md-1 d-flex align-items-end">
          <button class="btn btn-success w-100" type="button" onclick="addItem()"><i class="bi bi-plus-circle"></i></button>
        </div>
      </div>

      <div class="table-responsive mt-3">
        <table class="table table-striped" id="itemsTable">
          <thead>
            <tr>
              <th>#</th>
              <th><?= lang('App.payment_type') ?></th>
              <th><?= lang('App.description') ?></th>
              <th class="text-end"><?= lang('App.amount') ?></th>
              <th></th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>

      <div class="row g-3 mt-3">
        <div class="col-md-6">
          <div class="border rounded p-3">
            <div class="fw-bold mb-2"><?= lang('App.summary') ?></div>
            <div><?= lang('App.payment_method') ?>: <strong id="summary-method">—</strong></div>
            <div><?= lang('App.total') ?>: <strong id="summary-total">0.00</strong></div>
            <div>VAT (<?= esc($vatRatePct) ?>%): <span id="summary-vat">0.00</span></div>
            <div><?= lang('App.grand_total') ?>: <strong id="summary-grand">0.00</strong></div>
            <div class="small text-muted mt-2">VAT No: <?= esc($tax->vatNumber ?? '-') ?></div>
          </div>
        </div>
      </div>

      <div class="mt-3 d-flex justify-content-end gap-2">
        <button class="btn btn-primary" type="submit"><i class="bi bi-save"></i> <?= lang('App.save_and_print') ?></button>
      </div>

      <!-- hidden arrays -->
      <div id="hiddenItems"></div>
    </form>
  </div>
</div>

<script>
  const ptSelect = document.getElementById('ptSelect');
  const ptAmount = document.getElementById('ptAmount');
  const ptDesc = document.getElementById('ptDesc');
  const itemsBody = document.querySelector('#itemsTable tbody');
  const hiddenItems = document.getElementById('hiddenItems');
  const studentInfo = document.getElementById('studentInfo');
  const studentIdInput = document.getElementById('student_id');
  const VAT_RATE = <?= json_encode($vatRate) ?>;
  let selectedPlan = null;

  ptSelect.addEventListener('change', function() {
    const opt = ptSelect.options[ptSelect.selectedIndex];
    const label = (opt.getAttribute('data-label') || '').toLowerCase();
    let amt = parseFloat(opt.getAttribute('data-amount') || '0');
    if (!isNaN(amt)) {
      if (label.includes('tuition') && selectedPlan && parseInt(selectedPlan) > 1) {
        const n = parseInt(selectedPlan);
        amt = +(amt / n).toFixed(2);
      }
      ptAmount.value = amt.toFixed(2);
    } else {
      ptAmount.value = '0.00';
    }
    if (!ptDesc.value) {
      ptDesc.value = opt.getAttribute('data-label') || '';
    }
  });

  function selectStudent(s) {
    studentIdInput.value = s.id;
    selectedPlan = s.plan || null;
    const planText = selectedPlan ? ` | <?= lang('App.installments') ?>: ${selectedPlan}` : '';
    studentInfo.innerHTML = `<strong>${s.student_id}</strong> — ${s.first_name || ''} ${s.last_name || ''}${planText} <br/><small><?= lang('App.parent') ?>: ${s.parent_phone || ''}</small>`;
    window.scrollTo({ top: document.getElementById('receiptForm').offsetTop, behavior: 'smooth' });
  }

  function addItem() {
    const opt = ptSelect.value;
    const label = ptSelect.options[ptSelect.selectedIndex]?.getAttribute('data-label') || '';
    const desc = ptDesc.value.trim();
    const amount = parseFloat(ptAmount.value || '0');
    if (!opt || amount <= 0) { alert('<?= lang('App.select_option') ?>: <?= lang('App.payment_type') ?>, <?= lang('App.amount') ?> > 0'); return; }

    const idx = itemsBody.children.length + 1;
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${idx}</td>
      <td>${label}</td>
      <td>${desc || ''}</td>
      <td class="text-end">${amount.toFixed(2)}</td>
      <td><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeItem(this)"><i class="bi bi-x"></i></button></td>
    `;
    itemsBody.appendChild(tr);

    // hidden fields
    const wrapper = document.createElement('div');
    wrapper.innerHTML = `
      <input type="hidden" name="item_payment_type_id[]" value="${opt}" />
      <input type="hidden" name="item_description[]" value="${desc}" />
      <input type="hidden" name="item_amount[]" value="${amount.toFixed(2)}" />
    `;
    hiddenItems.appendChild(wrapper);

    // reset
    ptSelect.value = '';
    ptDesc.value = '';
    ptAmount.value = '0';

    recomputeTotals();
  }

  function removeItem(btn) {
    const row = btn.closest('tr');
    const idx = Array.from(itemsBody.children).indexOf(row);
    itemsBody.removeChild(row);
    // remove corresponding hidden inputs (3 per item)
    const inputs = hiddenItems.querySelectorAll('input');
    const start = idx * 3;
    for (let i = 0; i < 3; i++) {
      const el = inputs[start];
      if (el) el.remove();
    }
    // re-number rows
    Array.from(itemsBody.children).forEach((tr, i) => tr.children[0].textContent = i + 1);
    recomputeTotals();
  }

  function recomputeTotals() {
    let total = 0;
    Array.from(itemsBody.children).forEach(tr => {
      const amtText = tr.children[3].textContent || '0';
      total += parseFloat(amtText) || 0;
    });
    const vat = +(total * VAT_RATE).toFixed(2);
    const grand = +(total + vat).toFixed(2);
    document.getElementById('summary-total').textContent = total.toFixed(2);
    document.getElementById('summary-vat').textContent = vat.toFixed(2);
    document.getElementById('summary-grand').textContent = grand.toFixed(2);
  }
</script>
<?= $this->include('layout/footer') ?>