<?= $this->include('layout/header') ?>
<?php $prefill = $prefill ?? []; ?>
<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <span><?= lang('App.student_registration') ?></span>
    <div class="ms-auto">
      <label class="form-label mb-0 me-2"><?= lang('App.student_no') ?>:</label>
      <input type="text" class="form-control d-inline-block" style="width: 200px;" name="student_no" placeholder="" readonly />
    </div>
  </div>
  <div class="card-body">
    <?php if (session()->getFlashdata('success')): ?>
      <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('error')): ?>
      <div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
    <?php endif; ?>

    <?php $enrollId = session()->getFlashdata('enrollment_id'); $studentCode = session()->getFlashdata('student_code'); ?>
    <?php if (!empty($enrollId)): ?>
      <!-- Print prompt modal -->
      <div class="modal fade" id="printPrompt" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title"><i class="bi bi-check2-circle me-1"></i> <?= lang('App.completed') ?></h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <p class="mb-2"><?= lang('App.registration') ?> <?= lang('App.completed') ?>.</p>
              <div class="small text-muted"><?= lang('App.student_id') ?>: <strong><?= esc($studentCode) ?></strong> &nbsp; | &nbsp; <?= lang('App.registration') ?>: <strong><?= esc($enrollId) ?></strong></div>
            </div>
            <div class="modal-footer">
              <a class="btn btn-primary" target="_blank" href="<?= base_url('enrollment/print/' . urlencode($enrollId)) ?>"><i class="bi bi-printer me-1"></i> <?= lang('App.print') ?> (A4)</a>
              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal"><?= lang('App.cancel') ?></button>
            </div>
          </div>
        </div>
      </div>
      <script>
        document.addEventListener('DOMContentLoaded', function() {
          const modalEl = document.getElementById('printPrompt');
          const modal = new bootstrap.Modal(modalEl);
          modal.show();
        });
      </script>
    <?php endif; ?>

    <form method="post" action="/enrollment" enctype="multipart/form-data">
      <?= csrf_field() ?>
      <?php if (!empty($prefill['application_id'])): ?>
        <input type="hidden" name="application_id" value="<?= (int) $prefill['application_id'] ?>" />
      <?php endif; ?>

      <h6 class="mb-3"><?= lang('App.student_information') ?></h6>
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.student_name_en') ?> *</label>
          <input type="text" class="form-control" name="name_en" value="<?= esc(old('name_en') ?? ($prefill['name_en'] ?? '')) ?>" required />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.student_name_ar') ?> *</label>
          <input type="text" class="form-control" name="name_ar" value="<?= esc(old('name_ar') ?? ($prefill['name_ar'] ?? '')) ?>" required />
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.student_photo') ?></label>
          <input type="file" class="form-control" name="photo" accept="image/*" />
          <div class="form-text"><?= lang('App.photo_upload_help') ?></div>
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.passport_number') ?></label>
          <input type="text" class="form-control" name="passport_number" value="<?= esc(old('passport_number')) ?>" />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.gender') ?> *</label>
          <?php $genderCurrent = old('gender') ?? ($prefill['gender'] ?? 'Male'); ?>
          <select class="form-select" name="gender" required>
            <?php foreach ($genders as $g): ?>
              <option value="<?= esc($g['value']) ?>" <?= $genderCurrent === $g['value'] ? 'selected' : '' ?>><?= esc($g['display']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.nationality') ?> *</label>
          <select class="form-select" name="nationality" required>
            <?php foreach ($nationalities as $n): ?>
              <option value="<?= esc($n['value']) ?>" <?= (old('nationality') ? old('nationality') === $n['value'] : $n['value'] === 'Saudi Arabia') ? 'selected' : '' ?>><?= esc($n['display']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.religion') ?> *</label>
          <select class="form-select" name="religion" required>
            <?php foreach ($religions as $r): ?>
              <option value="<?= esc($r['value']) ?>" <?= (old('religion') ? old('religion') === $r['value'] : $r['value'] === 'Muslim') ? 'selected' : '' ?>><?= esc($r['display']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.birth_date_g') ?> *</label>
          <input type="date" class="form-control" name="dob_g" value="<?= esc(old('dob_g')) ?>" />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.birth_date_h') ?></label>
          <input type="text" class="form-control" name="dob_h" placeholder="1445/05/15" value="<?= esc(old('dob_h')) ?>" />
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.mobile_number') ?></label>
          <input type="text" class="form-control" name="mobile" value="<?= esc(old('mobile') ?? ($prefill['mobile'] ?? '')) ?>" />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.student_iqama_no') ?></label>
          <input type="text" class="form-control" name="student_iqama" value="<?= esc(old('student_iqama') ?? ($prefill['student_iqama'] ?? '')) ?>" />
        </div>

        <div class="col-12">
          <label class="form-label"><?= lang('App.home_address') ?></label>
          <textarea class="form-control" name="address" rows="2"><?= esc(old('address') ?? ($prefill['address'] ?? '')) ?></textarea>
        </div>
      </div>

      <hr class="my-4" />

      <h6 class="mb-3"><?= lang('App.parent_information') ?></h6>
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.father_name') ?> *</label>
          <input type="text" class="form-control" name="father_name" value="<?= esc(old('father_name') ?? ($prefill['father_name'] ?? '')) ?>" required />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.occupation') ?></label>
          <input type="text" class="form-control" name="occupation" value="<?= esc(old('occupation') ?? ($prefill['occupation'] ?? '')) ?>" />
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.iqama_number') ?></label>
          <input type="text" class="form-control" name="parent_iqama" value="<?= esc(old('parent_iqama')) ?>" />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.iqama_issue_date') ?></label>
          <input type="date" class="form-control" name="iqama_issue_date" value="<?= esc(old('iqama_issue_date')) ?>" />
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.iqama_expiry_date') ?></label>
          <input type="date" class="form-control" name="iqama_expiry_date" value="<?= esc(old('iqama_expiry_date')) ?>" />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.place_of_issue') ?></label>
          <input type="text" class="form-control" name="place_of_issue" value="<?= esc(old('place_of_issue')) ?>" />
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.telephone_number') ?></label>
          <input type="text" class="form-control" name="telephone" value="<?= esc(old('telephone') ?? ($prefill['telephone'] ?? '')) ?>" />
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.company_name') ?></label>
          <input type="text" class="form-control" name="company_name" value="<?= esc(old('company_name')) ?>" />
        </div>
      </div>

      <hr class="my-4" />

      <h6 class="mb-3"><?= lang('App.academic_information') ?></h6>
      <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">
            <?php foreach ($schoolYears as $y): ?>
              <option value="<?= $y['id'] ?>" <?= old('school_year_id') == $y['id'] ? 'selected' : '' ?>><?= esc($y['school_year']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.class') ?></label>
          <?php $classCurrent = old('class_id') ?? ($prefill['class_id'] ?? ''); ?>
          <select class="form-select" name="class_id">
            <?php foreach ($classes as $c): ?>
              <option value="<?= $c['id'] ?>" <?= (string)$classCurrent === (string)$c['id'] ? 'selected' : '' ?>><?= esc($c['display']) ?></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">
            <?php foreach ($sections as $s): ?>
              <option value="<?= $s['id'] ?>" <?= old('section_id') == $s['id'] ? 'selected' : '' ?>><?= esc($s['display']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.child_order_discount') ?></label>
          <select class="form-select" name="child_order">
            <?php foreach ($childOrders as $co): ?>
              <option value="<?= esc($co['value']) ?>" <?= old('child_order') == $co['value'] ? 'selected' : '' ?>><?= esc($co['display']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label"><?= lang('App.payment_type') ?></label>
          <select class="form-select" name="payment_type_id">
            <?php foreach ($paymentTypes as $pt): ?>
              <option value="<?= $pt['id'] ?>" <?= old('payment_type_id') == $pt['id'] ? 'selected' : '' ?>><?= esc($pt['display'] ?? '') ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label"><?= lang('App.plan') ?></label>
          <select class="form-select" name="plan">
            <?php foreach (['10','4','2','1'] as $pl): ?>
              <option value="<?= $pl ?>" <?= (old('plan') ? old('plan') === $pl : $pl === '1') ? 'selected' : '' ?>><?= $pl ?> <?= lang('App.installments') ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="mt-4 d-flex justify-content-end gap-2">
        <button type="reset" class="btn btn-outline-secondary"><?= lang('App.clear') ?></button>
        <button type="submit" class="btn btn-primary"><?= lang('App.save_enrollment') ?></button>
      </div>
    </form>
  </div>
</div>
<?= $this->include('layout/footer') ?>


<script>
// Auto-fill Hijri birth date when Gregorian date is entered
(function(){
  const g = document.querySelector('input[name="dob_g"]');
  const h = document.querySelector('input[name="dob_h"]');
  if (!g || !h) return;

  function islamicFromDate(date) {
    // Preferred: use Intl Islamic calendar with Latin digits
    try {
      const fmt = new Intl.DateTimeFormat('en-TN-u-ca-islamic-nu-latn', { year: 'numeric', month: '2-digit', day: '2-digit' });
      const parts = fmt.formatToParts(date);
      const y = parts.find(p => p.type === 'year')?.value;
      const m = parts.find(p => p.type === 'month')?.value;
      const d = parts.find(p => p.type === 'day')?.value;
      if (y && m && d) {
        return { y: parseInt(y, 10), m: parseInt(m, 10), d: parseInt(d, 10) };
      }
    } catch (e) {}

    // Fallback: tabular Islamic calendar approximation (no Umm al-Qura adjustments)
    const y = date.getUTCFullYear();
    const m = date.getUTCMonth() + 1;
    const d = date.getUTCDate();
    const jd = (function(y, m, d) {
      const a = Math.floor((14 - m) / 12);
      const y1 = y + 4800 - a;
      const m1 = m + 12 * a - 3;
      return d + Math.floor((153 * m1 + 2) / 5) + 365 * y1 + Math.floor(y1 / 4) - Math.floor(y1 / 100) + Math.floor(y1 / 400) - 32045;
    })(y, m, d);
    const islamic = (function(jd) {
      jd = jd - 1948440 + 10632;
      const n = Math.floor((jd - 1) / 10631);
      jd = jd - 10631 * n + 354;
      const j = Math.floor((10985 - jd) / 5316) * Math.floor(50 * jd / 17719) + Math.floor(jd / 5670) * Math.floor(43 * jd / 15238);
      jd = jd - Math.floor((30 - j) / 15) * Math.floor(17719 * j / 50) - Math.floor(j / 16) * Math.floor(15238 * j / 43) + 29;
      const im = Math.floor(24 * jd / 709);
      const id = jd - Math.floor(709 * im / 24);
      const iy = 30 * n + j - 30;
      return { y: iy, m: im, d: id };
    })(jd);
    return islamic;
  }

  function updateHijri() {
    const val = g.value;
    if (!val) { h.value = ''; return; }
    // Date input value is ISO: YYYY-MM-DD
    const date = new Date(val + 'T00:00:00Z');
    if (isNaN(date.getTime())) return;
    const hi = islamicFromDate(date);
    if (hi) {
      const mm = String(hi.m).padStart(2, '0');
      const dd = String(hi.d).padStart(2, '0');
      h.value = `${hi.y}/${mm}/${dd}`; // e.g., 1445/05/15
    }
  }

  g.addEventListener('change', updateHijri);
  g.addEventListener('input', updateHijri);
  // Initialize if the Gregorian date is already filled (e.g., when returning after error)
  if (g.value) updateHijri();
})();
</script>