<?php
// /elms/student/login.php
// Student Login — academic_email + password

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';
require_once __DIR__ . '/../includes/elms_settings.php';

if (!function_exists('esc')) {
    function esc($s): string {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('flash')) {
    function flash($k, $v = null) {
        if ($v === null) {
            $x = $_SESSION['flash'][$k] ?? null;
            unset($_SESSION['flash'][$k]);
            return $x;
        }

        $_SESSION['flash'][$k] = $v;
        return null;
    }
}

if (!function_exists('safe_student_next')) {
    function safe_student_next(string $next): string {
        $studentHome = '/elms/student/index.php';

        $next = trim($next);
        $next = str_replace('/student/student/', '/student/', $next);

        if ($next === '') {
            return $studentHome;
        }

        if (preg_match('#^https?://#i', $next) || str_starts_with($next, '//')) {
            return $studentHome;
        }

        if ($next[0] !== '/') {
            return $studentHome;
        }

        $pathOnly = parse_url($next, PHP_URL_PATH) ?: '';

        $blocked = [
            '/elms/student/login.php',
            '/elms/student/logout.php',
            '/elms/auth/login.php',
            '/elms/admin/login.php',
        ];

        if (in_array($pathOnly, $blocked, true)) {
            return $studentHome;
        }

        if (!str_starts_with($pathOnly, '/elms/student/')) {
            return $studentHome;
        }

        return $next;
    }
}

/* DB handle */
$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('DB connection failed');
}

$mysqli->set_charset('utf8mb4');
if (!elms_setting_on($mysqli, 'student_login_enabled', 'on')) {
    flash('err', 'Student login is currently disabled.');

    if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
        header('Location: /elms/student/login.php');
        exit;
    }
}

$studentHome = '/elms/student/index.php';
$next = safe_student_next((string)($_GET['next'] ?? $_POST['next'] ?? $studentHome));

/*
|--------------------------------------------------------------------------
| Already logged in
|--------------------------------------------------------------------------
| Important:
| Never redirect back to login.php, otherwise ERR_TOO_MANY_REDIRECTS.
*/

if (!empty($_SESSION['student_id'])) {
    header('Location: ' . $next);
    exit;
}

/*
|--------------------------------------------------------------------------
| POST Login
|--------------------------------------------------------------------------
*/

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, 
                academic_plain_password, 
                lms_status, 
                center_reg_no
            FROM studentss
            WHERE academic_email = ?
            LIMIT 1
        ";

        $row = null;

        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  = trim((string)($row['academic_password_hash'] ?? ''));
            $plain = trim((string)($row['academic_plain_password'] ?? ''));

            $ok = false;

            if ($hash !== '') {
                $info = password_get_info($hash);

                if (($info['algoName'] ?? 'unknown') !== 'unknown') {
                    $ok = password_verify($pass, $hash);
                } else {
                    $ok = hash_equals($hash, $pass);
                }
            }

            if (!$ok && $plain !== '') {
                $ok = hash_equals($plain, $pass);
            }

            $lms_status = strtolower(trim((string)($row['lms_status'] ?? 'active')));

            if ($ok && in_array($lms_status, ['inactive', 'suspended'], true)) {
                $ok = false;
                flash('err', 'Your LMS account is not active. Please contact your coordinator.');
            }

            if ($ok) {
                session_regenerate_id(true);

                $_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'] ?? '');

                header('Location: ' . safe_student_next($next));
                exit;
            }
        }

        if (empty($_SESSION['student_id']) && !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 {
            --eden-blue: #2563eb;
            --eden-deep: #1e3a8a;
            --eden-red: #e31e24;
            --ink: #0b1220;
            --muted: #5b6472;
            --bg: #f7fafc;
            --card: #ffffff;
            --card-border: rgba(2,8,23,.08);
            --ring: rgba(37,99,235,.22);
            --hero: url('/elms/assets/hero/graduates.jpg');
            --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);
        }

        .screen {
            min-height: 100vh;
            display: grid;
            grid-template-columns: minmax(320px, 45vw) 1fr;
        }

        .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%);
        }

        .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%);
        }

        .right {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: clamp(20px, 4vw, 60px);
        }

        .wrap {
            width: 100%;
            max-width: 640px;
        }

        .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 {
            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;
        }

        .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;
        }

        @media (max-width: 992px) {
            .screen {
                grid-template-columns: 1fr;
            }

            .hero {
                height: 35vh;
            }
        }

        @media (max-width: 576px) {
            .hero::after {
                display: none;
            }
        }
    </style>
</head>

<body>

<div class="screen">
    <aside class="hero" aria-hidden="true"></aside>

    <main class="right">
        <div class="wrap">
            <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();

(() => {
    const form = document.querySelector('.needs-validation');

    form.addEventListener('submit', (e) => {
        if (!form.checkValidity()) {
            e.preventDefault();
            e.stopPropagation();
        }

        form.classList.add('was-validated');
    }, false);
})();

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>