<?php

session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
  mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);

include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';

$stResult           = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');

if (strlen($_SESSION['sid']) == 0) {
  header('location:logout.php');
}

require_once 'vendor/autoload.php';
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$admissionPrefix = $_ENV['Admission_prefix']; // e.g. ACI  — used for FormNo

// ── AJAX: return payment record for prefill ──────────────────────────────────
if (isset($_GET['fetch_payment']) && !empty($_GET['payment_id'])) {
  header('Content-Type: application/json');
  $pid  = intval($_GET['payment_id']);
  $stmt = $con->prepare(
    "SELECT studentName, class, school_type, studentno AS email, session, Term
     FROM payment WHERE id = ? LIMIT 1"
  );
  // Note: payment.studentno stores the email in this context (see entrancepay.php)
  $stmt->bind_param("i", $pid);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  echo json_encode($row ?: []);
  exit;
}

// ── Helper: generate next FormNo ─────────────────────────────────────────────
function generateFormNo(string $prefix, mysqli $con): string
{
  $likePattern = $prefix . '/NS/%';
  $result = mysqli_query($con, "SELECT FormNo FROM students WHERE FormNo LIKE '$likePattern'");
  $existing = [];
  while ($r = mysqli_fetch_assoc($result)) {
    $existing[] = $r['FormNo'];
  }

  $maxNum = 0;
  foreach ($existing as $f) {
    if (strpos($f, $prefix . '/NS/') === 0) {
      $num = (int) substr($f, strrpos($f, '/') + 1);
      if ($num > $maxNum) $maxNum = $num;
    }
  }
  $nextNum = $maxNum + 1;
  $formNo  = $prefix . '/NS/' . str_pad($nextNum, 5, '0', STR_PAD_LEFT);
  while (in_array($formNo, $existing)) {
    $nextNum++;
    $formNo = $prefix . '/NS/' . str_pad($nextNum, 5, '0', STR_PAD_LEFT);
  }
  return $formNo;
}

// ── Form submission ───────────────────────────────────────────────────────────
if (isset($_POST['submit'])) {
  $names     = $con->real_escape_string(trim($_POST['names']));
  $class     = $con->real_escape_string(trim($_POST['class']));
  $email     = $con->real_escape_string(trim($_POST['email']));
  $stream    = $con->real_escape_string(trim($_POST['school_type']));
  $acsession = $con->real_escape_string(trim($_POST['session_id']));
  $term      = $con->real_escape_string(trim($_POST['term_id']));
  $status    = 4;

  // Generate FormNo with table lock
  mysqli_query($con, "LOCK TABLES students WRITE");
  $formNo = generateFormNo($admissionPrefix, $con);

  $query = "INSERT INTO students
    (status, FormNo, StudentName, class, stream, email,
     academic_session, admission_term,
     gender, parentName, relation, occupation, country, district,
     state, village, contactno, nextphone,
     physical_peculiarity, medical_history, doctor_address, doctor_phone,
     religion, language, studentImage)
    VALUES
    ('$status', '$formNo', '$names', '$class', '$stream', '$email',
     '$acsession', '$term',
     '', '', '', '', '', '', '', '', '', '',
     '', '', '', '', '', '', 'but.jpg')";

  $result = mysqli_query($con, $query);

  if ($result) {
    mysqli_query($con, "UNLOCK TABLES");
    flash_alert("Student added successfully. Form No: $formNo");
    header('Location: registration2.php');
    exit;
  } else {
    mysqli_query($con, "UNLOCK TABLES");
    flash_alert('Error: ' . mysqli_error($con));
  }
}

// ── Load payment list for dropdown ───────────────────────────────────────────
$paymentList = mysqli_query($con,
  "SELECT id, studentName, class, school_type, session, Term
   FROM payment
   WHERE pay_for IN ('ENTRANCE FORM (DAY STUDENT)', 'ENTRANCE FORM (BOARDING STUDENT)')
   ORDER BY studentName ASC"
);
?>
<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

  <?php @include("includes/header.php"); ?>
  <?php @include("includes/sidebar.php"); ?>

  <div class="content-wrapper">

    <!-- Page header -->
    <section class="content-header premium-header">
      <div class="container-fluid">
        <div class="header-glass-card">
          <div class="row align-items-center">
            <div class="col-md-8">
              <div class="title-section">
                <div class="icon-box bg-primary-gradient shadow-sm">
                  <i class="fas fa-user-graduate"></i>
                </div>
                <div>
                  <h1 class="premium-title text-primary">
                    Student Information Management
                    <span class="premium-subtitle text-secondary">Quick Registration</span>
                  </h1>
                  <div class="mt-1">
                    <?php if ($currentSessionName): ?>
                      <span class="badge badge-primary mr-1">
                        <i class="fas fa-calendar-alt"></i>
                        <?= htmlspecialchars($currentSessionName) ?>
                      </span>
                    <?php endif; ?>
                    <?php if ($currentTermName): ?>
                      <span class="badge badge-success">
                        <i class="fas fa-bookmark"></i>
                        <?= htmlspecialchars($currentTermName) ?>
                      </span>
                    <?php else: ?>
                      <span class="badge badge-warning">
                        <i class="fas fa-exclamation-triangle"></i> No active term
                      </span>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <nav aria-label="breadcrumb">
                <ol class="breadcrumb premium-breadcrumb">
                  <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>
                  <li class="breadcrumb-item active">Quick Registration</li>
                </ol>
              </nav>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-12">

            <div class="card card-primary">
              <div class="card-header">
                <h5 class="card-title font-weight-bold">
                  <i class="fas fa-user-plus"></i> Quick Registration — New Students (from Payment Records)
                </h5>
              </div>

              <form role="form" method="POST">
                <div class="card-body">

                  <span style="color: brown"><h5><i class="fas fa-search"></i> Select Student from Payment Records</h5></span>
                  <hr>

                  <div class="row">
                    <div class="form-group col-md-12">
                      <label for="payment_select">Select Student <span class="text-danger">*</span></label>
                      <select id="payment_select" class="form-control">
                        <option value="">-- Select a student from entrance form payments --</option>
                        <?php while ($p = mysqli_fetch_assoc($paymentList)): ?>
                          <option value="<?= $p['id'] ?>"
                            data-name="<?= htmlspecialchars($p['studentName']) ?>"
                            data-class="<?= htmlspecialchars($p['class']) ?>"
                            data-stream="<?= htmlspecialchars($p['school_type']) ?>"
                            data-session="<?= htmlspecialchars($p['session']) ?>"
                            data-term="<?= htmlspecialchars($p['Term']) ?>">
                            <?= htmlspecialchars($p['studentName']) ?>
                            — <?= htmlspecialchars($p['class']) ?>
                            (<?= htmlspecialchars($p['school_type']) ?>)
                            — <?= htmlspecialchars($p['session']) ?>
                          </option>
                        <?php endwhile; ?>
                      </select>
                      <small class="text-muted">Only entrance form payments are listed. Selecting a student will prefill the fields below.</small>
                    </div>
                  </div>

                  <span style="color: brown"><h5><i class="fas fa-user"></i> Student Details</h5></span>
                  <hr>

                  <div class="row">

                    <div class="form-group col-md-6">
                      <label>Student's Fullname <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" id="names" name="names"
                             placeholder="Surname Firstname Othername" required>
                    </div>

                    <div class="form-group col-md-6">
                      <label>Email Address <span class="text-danger">*</span></label>
                      <input type="email" class="form-control" id="email" name="email"
                             placeholder="Parent email" required>
                    </div>

                    <div class="form-group col-md-6">
                      <label>Class <span class="text-danger">*</span></label>
                      <select class="form-control" id="class" name="class" required>
                        <option value="">-- Select Class --</option>
                        <?php
                        $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class ASC");
                        while ($cr = $classResult->fetch_assoc()):
                          echo "<option value='{$cr['class']}'>{$cr['class']}</option>";
                        endwhile;
                        ?>
                      </select>
                    </div>

                    <div class="form-group col-md-6">
                      <label>School Type <span class="text-danger">*</span></label>
                      <select class="form-control" id="school_type" name="school_type" required>
                        <option value="">-- Select --</option>
                        <option value="Day">Day</option>
                        <option value="Boarding">Boarding</option>
                      </select>
                    </div>

                    <div class="form-group col-md-6">
                      <label>Academic Session to Resume <span class="text-danger">*</span></label>
                      <select class="form-control" id="session_id" name="session_id" required>
                        <option value="">-- Select Session --</option>
                        <?php
                        $sessResult = $con->query("SELECT DISTINCT session_name FROM school_sessions ORDER BY session_name DESC");
                        while ($sr = $sessResult->fetch_assoc()):
                          $sel = ($currentSessionName == $sr['session_name']) ? 'selected' : '';
                          echo "<option value='{$sr['session_name']}' $sel>{$sr['session_name']}</option>";
                        endwhile;
                        ?>
                      </select>
                    </div>

                    <div class="form-group col-md-6">
                      <label>Academic Term to Resume <span class="text-danger">*</span></label>
                      <select class="form-control" id="term_id" name="term_id" required>
                        <option value="">-- Select Term --</option>
                        <?php
                        $termResult = $con->query("SELECT DISTINCT term_name FROM school_terms ORDER BY term_name ASC");
                        while ($tr = $termResult->fetch_assoc()):
                          $sel = ($currentTermName == $tr['term_name']) ? 'selected' : '';
                          echo "<option value='{$tr['term_name']}' $sel>{$tr['term_name']}</option>";
                        endwhile;
                        ?>
                      </select>
                    </div>

                  </div>

                </div><!-- /.card-body -->

                <div class="card-footer">
                  <center>
                    <button type="submit" name="submit" class="btn btn-primary">
                      <i class="fas fa-check-circle"></i> Add Student
                    </button>
                  </center>
                </div>

              </form>
            </div><!-- /.card -->

          </div>
        </div>
      </div>
    </section>

  </div><!-- /.content-wrapper -->

  <?php @include("includes/footer.php"); ?>
</div><!-- ./wrapper -->

<?php @include("includes/foot.php"); ?>

<script src="dist/js/select2.min.js"></script>

<script>
$(document).ready(function () {

  // Init select2 on all dropdowns
  $('#payment_select').select2({ width: '100%', placeholder: '-- Select a student --' });
  $('#class').select2({ width: '100%' });
  $('#school_type').select2({ width: '100%' });
  $('#session_id').select2({ width: '100%' });
  $('#term_id').select2({ width: '100%' });

  // Prefill fields when a payment record is selected
  $('#payment_select').on('change', function () {
    const opt = $(this).find(':selected');
    if (!opt.val()) return;

    // Prefill text fields
    $('#names').val(opt.data('name'));

    // Prefill and trigger select2 for dropdowns
    const classVal   = opt.data('class');
    const streamVal  = opt.data('stream');
    const sessionVal = opt.data('session');
    const termVal    = opt.data('term');

    // Class — try to match existing option, else add it
    if ($('#class option[value="' + classVal + '"]').length === 0) {
      $('#class').append(new Option(classVal, classVal));
    }
    $('#class').val(classVal).trigger('change');

    // School type
    $('#school_type').val(streamVal).trigger('change');

    // Session
    if ($('#session_id option[value="' + sessionVal + '"]').length === 0) {
      $('#session_id').append(new Option(sessionVal, sessionVal));
    }
    $('#session_id').val(sessionVal).trigger('change');

    // Term
    if ($('#term_id option[value="' + termVal + '"]').length === 0) {
      $('#term_id').append(new Option(termVal, termVal));
    }
    $('#term_id').val(termVal).trigger('change');

    // Fetch email from server (payment.studentno holds the email)
    $.getJSON('registration2.php', { fetch_payment: 1, payment_id: opt.val() }, function (data) {
    });
  });

});
</script>

</body>
</html>
