<?php
// Student Login — academic_email + academic_password_hash ONLY

declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/helpers.php';

/* helpers */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function flash($k,$v=null){ if($v===null){ $x=$_SESSION['flash'][$k]??null; unset($_SESSION['flash'][$k]); return $x; } $_SESSION['flash'][$k]=$v; }

/* DB handle ($mysqli or $conn from db.php). Fallback if needed. */
$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) {
  $mysqli = new mysqli('localhost','root','','edencamp_edencampus');
  if ($mysqli->connect_error) { http_response_code(500); exit('DB connection failed'); }
  $mysqli->set_charset('utf8mb4');
}

/* redirect target hardening */
$base = app_url();                                // e.g. https://admin.edencampus.lk/elms/
$next = $_GET['next'] ?? $_POST['next'] ?? app_url('');
if (strpos($next, $base)!==0) $next = app_url('student/');

/* already logged in */
if (!empty($_SESSION['student_id'])) { header("Location: $next"); exit; }

/* POST: authenticate (email + hash only) */
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $email = trim((string)($_POST['email'] ?? ''));
  $pass  = (string)($_POST['password'] ?? '');

  if ($email === '' || $pass === '') {
    flash('err','Please enter your email and password.');
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    flash('err','Enter a valid academic email address.');
  } else {
    $sql = "SELECT id, full_name, academic_email, academic_password_hash, lms_active, center_reg_no
            FROM studentss
            WHERE academic_email = ?
            LIMIT 1";
    if ($st = $mysqli->prepare($sql)) {
      $st->bind_param('s', $email);
      $st->execute();
      $row = $st->get_result()->fetch_assoc();
      $st->close();
    } else {
      flash('err','Server error. Please try again later.');
    }

    if (!empty($row)) {
      $hash = (string)($row['academic_password_hash'] ?? '');
      $ok = ($hash !== '' && password_get_info($hash)['algo'] !== 0 && password_verify($pass, $hash));

      if ($ok && isset($row['lms_active']) && (string)$row['lms_active'] === '0') {
        $ok = false;
        flash('err','Your LMS account is not active. Please contact your coordinator.');
      }

      if ($ok) {
        $_SESSION['student_id']    = (int)$row['id'];
        $_SESSION['student_name']  = $row['full_name'] ?: $row['academic_email'];
        $_SESSION['academic_email']= $row['academic_email'];
        $_SESSION['center_reg_no'] = (string)($row['center_reg_no'] ?? '');
        session_regenerate_id(true);
        header("Location: $next"); exit;
      }
    }

    if (empty($_SESSION['student_id'])) {
      // Generic message (don’t leak which field was wrong)
      if (!flash('err')) flash('err','Invalid email or password.');
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Eden Campus · Student Login</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet" />

  <style>
    :root{
      /* Brand */
      --eden-blue:#2563eb;
      --eden-deep:#1e3a8a;
      --eden-red:#e31e24;

      /* Theme */
      --ink:#0b1220;
      --muted:#5b6472;
      --bg:#f7fafc;
      --card:#ffffff;
      --card-border:rgba(2,8,23,.08);
      --ring:rgba(37,99,235,.22);

      /* Hero image path (swap here) */
      --hero:url('/elms/assets/hero/graduates.jpg');
      /* Optional watermark (logo over hero) */
      --watermark:url('/elms/assets/brand/logo.png');
    }

    html,body{height:100%}
    body{
      margin:0; color:var(--ink);
      background:
        radial-gradient(1300px 600px at 20% -10%, rgba(37,99,235,.06), transparent 60%),
        radial-gradient(1000px 500px at 90% 110%, rgba(37,99,235,.04), transparent 60%),
        var(--bg);
    }

    /* Layout: hero LEFT, content RIGHT */
    .screen{
      min-height:100vh; display:grid;
      grid-template-columns:minmax(320px, 45vw) 1fr;
    }
    @media (max-width: 992px){
      .screen{ grid-template-columns:1fr }
      .hero{ height:40vh }
    }

    /* HERO */
    .hero{ position:relative; overflow:hidden; background:#0b1220 }
    .hero::before{
      content:""; position:absolute; inset:0;
      background:
        linear-gradient( to left, rgba(0,0,0,.14), rgba(0,0,0,.36) ),
        var(--hero) center 45% / cover no-repeat;
      filter:saturate(106%) contrast(103%);
    }
    /* Subtle watermark in hero (auto hides on small screens) */
    .hero::after{
      content:""; position:absolute; bottom:24px; left:24px; width:160px; height:48px;
      background: var(--watermark) center / contain no-repeat;
      opacity:.25; filter:grayscale(10%) contrast(90%);
    }
    @media (max-width: 576px){ .hero::after{ display:none } }

    /* RIGHT COLUMN */
    .right{
      display:flex; align-items:center; justify-content:center;
      padding:clamp(20px,4vw,60px);
    }
    .wrap{ width:100%; max-width:640px }

    /* BRAND MASTHEAD */
    .mast{ display:flex; align-items:center; gap:14px; margin-bottom:10px }
    .mast img{ height:70px; width:auto }
    .brand-name{ font-weight:800; font-size:22px; letter-spacing:.2px }

    /* TITLE BLOCK */
    .title{
      font-weight:900; line-height:1.04; letter-spacing:.1px;
      font-size: clamp(30px, 5vw, 50px); margin:.15rem 0 .35rem;
    }
    .tag{ color:#334155; font-weight:600; margin-bottom:14px }
    .underline{
      width:196px; height:4px; border-radius:999px;
      background:linear-gradient(90deg, var(--eden-red), var(--eden-blue));
      margin-bottom:22px;
    }

    /* LOGIN CARD */
    .card-login{
      background:color-mix(in oklab, var(--card) 88%, transparent);
      backdrop-filter: blur(10px);
      border:1px solid var(--card-border);
      border-radius:16px;
      box-shadow: 0 28px 80px rgba(2,8,23,.12);
      padding:20px 20px 16px;
    }
    .form-label{ font-weight:600; color:#202733 }
    .input-group-text{ background:#f8fafc }
    .form-control{ height:46px; }
    .form-control:focus{ border-color:var(--eden-blue); box-shadow:0 0 0 .25rem var(--ring) }
    .btn-primary{ background:var(--eden-blue); border-color:var(--eden-blue); font-weight:700; height:46px; }
    .help{ color:var(--muted) }
    .footer{ color:#8a98a9 }
  </style>
</head>
<body>

<div class="screen">
  <!-- LEFT: HERO -->
  <aside class="hero" aria-hidden="true"></aside>

  <!-- RIGHT: BRAND + TITLE + FORM -->
  <main class="right">
    <div class="wrap">
      <!-- Masthead -->
      <div class="mast">
        <img src="/elms/assets/brand/logo.png" alt="Eden Campus" onerror="this.src='/elms/assets/119.jpg'">
        <div class="brand-name">Eden Campus</div>
      </div>

      <div class="tag">Student Login</div>
      <h1 class="title">Learning Management System</h1>
      <div class="underline"></div>

      <div class="card-login">
        <?php if($m=flash('err')): ?>
          <div class="alert alert-danger d-flex align-items-center" role="alert">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            <div><?= esc($m) ?></div>
          </div>
        <?php endif; ?>

        <form method="post" class="needs-validation" novalidate>
          <input type="hidden" name="next" value="<?= esc($next) ?>">
          <div class="mb-3">
            <label for="email" class="form-label">Academic Email</label>
            <input type="email" class="form-control" id="email" name="email"
                   placeholder="student@eden.academy" autocomplete="username" required>
            <div class="invalid-feedback">Please enter a valid academic email.</div>
          </div>

          <div class="mb-3">
            <label for="password" class="form-label">Password</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-shield-lock"></i></span>
              <input type="password" class="form-control" id="password" name="password"
                     placeholder="Your account password" autocomplete="current-password" required>
              <button class="btn btn-outline-primary" type="button" id="togglePwd" tabindex="-1">Show</button>
              <div class="invalid-feedback">Please enter your password.</div>
            </div>
            <small id="capsWarn" class="text-warning d-none">Caps Lock seems to be ON</small>
          </div>

          <button class="btn btn-primary w-100" type="submit">Login</button>
          <div class="help small mt-3">Need help? Contact your coordinator.</div>
        </form>
      </div>

      <div class="footer small mt-3">© <span id="yr"></span> Eden Campus. All rights reserved.</div>
    </div>
  </main>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  document.getElementById('yr').textContent = new Date().getFullYear();

  // client-side validation
  (() => {
    const form = document.querySelector('.needs-validation');
    form.addEventListener('submit', (e) => {
      if (!form.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
      form.classList.add('was-validated');
    }, false);
  })();

  // show/hide password + CapsLock hint
  const pwd  = document.getElementById('password');
  const btn  = document.getElementById('togglePwd');
  const caps = document.getElementById('capsWarn');
  btn.addEventListener('click', () => {
    const show = pwd.type === 'password';
    pwd.type = show ? 'text' : 'password';
    btn.textContent = show ? 'Hide' : 'Show';
  });
  pwd.addEventListener('keyup', (e) => {
    if (e.getModifierState) caps.classList.toggle('d-none', !e.getModifierState('CapsLock'));
  });
</script>
</body>
</html>
