<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
        $error = 'Invalid session token.';
    } else {
        // Only student_id
        $student_id = trim($_POST['student_id'] ?? '');
        // Optional: basic normalization (remove spaces)
        $student_id = preg_replace('/\s+/', '', $student_id);

        if ($student_id !== '') {
            $stmt = $mysqli1->prepare("SELECT id FROM students WHERE student_id = ? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param("s", $student_id);
                $stmt->execute();
                $res = $stmt->get_result();
                if ($row = $res->fetch_assoc()) {
                    $_SESSION['student_id']     = $student_id;
                    $_SESSION['student_row_id'] = (int)$row['id'];
                    header("Location: student_profile4.php");
                    exit;
                } else {
                    $error = 'Invalid Student ID.';
                }
                $stmt->close();
            } else {
                $error = 'Server error. Please try again.';
            }
        } else {
            $error = 'Please enter your Student ID.';
        }
    }
}

include 'header.php';
?>
<div class="container-fluid bg-light min-vh-100 d-flex flex-column justify-content-center align-items-center">

  <!-- Header Image Card -->
  <div class="col-12 col-md-10 col-lg-8 col-xl-6 mb-4">
    <div class="card border-0 shadow-sm overflow-hidden rounded-4">
      <img src="img/banar2.jpg" class="img-fluid w-100" alt="Admissions Banner" style="max-height: 300px; object-fit: cover;">
    </div>
  </div>

  <!-- Student Login Card -->
  <div class="col-12 col-md-10 col-lg-8 col-xl-6">
    <div class="card p-5 shadow-lg rounded-4">
      <h3 class="mb-4 text-center fw-bold">تسجيل دخول</h3>

      <?php if ($error): ?>
        <div class="alert alert-danger text-center fs-5"><?= e($error) ?></div>
      <?php endif; ?>

      <form method="post" class="row g-4" autocomplete="off" novalidate>
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

<div class="form-floating">
  <input
    type="text"
    class="form-control form-control-lg text-center"
    id="student_id"
    name="student_id"
    placeholder="Student ID"
    required
    pattern="^[A-Za-z0-9_-]{3,}$"
    title="Enter a valid Student ID (letters, numbers, - or _)"
    autocomplete="off"
    dir="ltr"
    style="text-align:center"
  >
  <label for="student_id" class="fs-6 w-100 text-center">
    الرقم الجامعي أو رقم إستمارة القبول مسبوقا ب23- مثال 110024563-23
  </label>
  <div class="invalid-feedback text-center">Please enter a valid Student ID.</div>
</div>


        <button class="btn btn-primary w-100 py-3 fs-5" type="submit">تسجيل دخول</button>
      </form>
    </div>
  </div>

</div>

<script>
  // Optional: live validation for nicer UX
  (function () {
    const idEl = document.getElementById('student_id');
    if (!idEl) return;

    const RE = /^[A-Za-z0-9_-]{3,}$/;

    function validate() {
      const v = idEl.value.trim();
      const ok = RE.test(v);
      idEl.classList.toggle('is-valid', ok);
      idEl.classList.toggle('is-invalid', !ok && v.length > 0);
      idEl.setCustomValidity(ok ? '' : 'invalid');
    }

    idEl.addEventListener('input', () => {
      // strip spaces while typing
      const cleaned = idEl.value.replace(/\s+/g, '');
      if (cleaned !== idEl.value) idEl.value = cleaned;
      validate();
    });
    idEl.addEventListener('blur', validate);
  })();
</script>

<?php include 'footer.php'; ?>
