<?php

declare(strict_types=1);

require_once __DIR__ . '/../config.php';



if (session_status() === PHP_SESSION_NONE) session_start();



// If already logged in AND has a staff record, go straight to portal

// (don't redirect if staff record is missing — that would cause a redirect loop)

if (!empty($_SESSION['tp_user_id']) || !empty($_SESSION['user_id'])) {

    require_once __DIR__ . '/ajax/tp_auth.php';

    if (tp_staff_id() > 0) {

        header('Location: index.php');

        exit;

    }

    // Staff record not linked — fall through to show login form with a message

    $early_error = 'Your account is not linked to a staff record. '

                 . 'Ask your administrator to click "Reset Teacher Login" on your staff profile.';

    session_destroy();

    session_start();

}



$error = $early_error ?? '';

$next  = preg_replace('/[^a-zA-Z0-9\/_\-\.]/', '', $_GET['next'] ?? 'index.php');



if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = trim((string)($_POST['username'] ?? ''));

    $password = (string)($_POST['password'] ?? '');



    if ($username === '' || $password === '') {

        $error = 'Username and password are required.';

    } else {

        $conn = getDBConnection();

        $stmt = $conn->prepare(

            "SELECT id, username, password, full_name, role

               FROM users WHERE username = ? AND is_active = 1 LIMIT 1"

        );

        $stmt->bind_param('s', $username);

        $stmt->execute();

        $user = $stmt->get_result()->fetch_assoc();

        $stmt->close();



        $pwd_ok = $user && password_verify($password, (string)$user['password']);

        // Legacy: accounts created via User Management used md5() — auto-upgrade on login

        if (!$pwd_ok && $user && $user['password'] === md5($password)) {

            $pwd_ok  = true;

            $new_hash = password_hash($password, PASSWORD_BCRYPT);

            $up = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");

            $up->bind_param('si', $new_hash, $user['id']);

            $up->execute();

            $up->close();

        }



        if ($pwd_ok) {

            session_regenerate_id(true);

            $_SESSION['tp_user_id']   = (int)$user['id'];

            $_SESSION['tp_user_name'] = (string)$user['full_name'];

            $_SESSION['tp_user_role'] = (string)$user['role'];

            // Pre-resolve staff.id so every AJAX call doesn't need an extra DB round-trip

            $sid_stmt = $conn->prepare("SELECT id FROM staff WHERE user_id = ? LIMIT 1");

            $sid_stmt->bind_param('i', $user['id']);

            $sid_stmt->execute();

            $sid_row = $sid_stmt->get_result()->fetch_assoc();

            $sid_stmt->close();

            if ($sid_row) $_SESSION['tp_staff_id'] = (int)$sid_row['id'];

            $conn->query("UPDATE users SET last_login=NOW() WHERE id=" . (int)$user['id']);

            header('Location: ' . ($next ?: 'index.php'));

            exit;

        }

        $error = 'Invalid username or password.';

    }

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

<title>Teacher Portal — Sign In</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<link rel="stylesheet" href="assets/tp.css">

</head>

<body>

<div class="tp-auth-wrap">

  <div class="tp-auth-card">

    <div class="tp-auth-logo"><i class="fas fa-chalkboard-teacher"></i></div>

    <h1 class="tp-auth-title">Teacher Portal</h1>

    <p class="tp-auth-sub">Sign in with your EduTrack staff credentials</p>



    <?php if ($error !== ''): ?>

      <div style="background:#fee2e2;color:#b91c1c;border-radius:8px;padding:.6rem .9rem;font-size:.85rem;margin-bottom:1rem;">

        <?= htmlspecialchars($error) ?>

      </div>

    <?php endif; ?>



    <form method="POST">

      <div class="tp-form-group">

        <label class="tp-label" for="username">Username</label>

        <input id="username" name="username" type="text" class="tp-input"

               placeholder="Your username" autocomplete="username" required>

      </div>

      <div class="tp-form-group">

        <label class="tp-label" for="password">Password</label>

        <div style="position:relative;">

          <input id="password" name="password" type="password" class="tp-input"

                 placeholder="••••••••" autocomplete="current-password" required

                 style="padding-right:2.5rem;">

          <button type="button" onclick="togglePwd()" style="position:absolute;right:.7rem;top:50%;transform:translateY(-50%);border:none;background:none;color:#94a3b8;cursor:pointer;font-size:.9rem;">

            <i id="pwd-eye" class="fas fa-eye"></i>

          </button>

        </div>

      </div>

      <button type="submit" class="tp-btn tp-btn-primary tp-btn-block" style="margin-top:.5rem;">

        <i class="fas fa-sign-in-alt"></i> Sign In

      </button>

    </form>



    <p style="text-align:center;font-size:.78rem;color:#94a3b8;margin-top:1.2rem;">

      EduTrack Teacher Portal — ORIC Network Limited

    </p>

  </div>

</div>

<script>

function togglePwd() {

  const i = document.getElementById('password');

  const e = document.getElementById('pwd-eye');

  if (i.type === 'password') { i.type = 'text'; e.className = 'fas fa-eye-slash'; }

  else { i.type = 'password'; e.className = 'fas fa-eye'; }

}

</script>

</body>

</html>

