<?php
declare(strict_types=1);
require_once __DIR__ . '/connect.php';
// JavaScript sends JSON with a CSRF header. The normal form includes the same
// session token as a hidden field, so both login paths use the same protection.
$contentType = strtolower(trim(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0]));
$isTraditionalForm = $contentType === 'application/x-www-form-urlencoded';
if ($isTraditionalForm) {
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
        header('Allow: POST');
        reply(405, ['status' => 'error', 'message' => 'Use POST for this request.']);
    }
    start_auth_session();
    $data = $_POST;
    $formToken = is_string($data['csrf_token'] ?? null) ? $data['csrf_token'] : '';
    if (!hash_equals($_SESSION['csrf_token'], $formToken)) {
        reply(403, ['status' => 'error', 'message' => 'Your sign-in form expired. Reload the sign-in page and try again.']);
    }
} else {
    // Keep the JSON + session-token security check for the JavaScript request.
    $data = post_data();
}

// Read the form, then check each required value before contacting the database.
$username = text_field($data, 'username', 150);
$password = text_field($data, 'password', 1024, false);
$role = '';
if ($username === '' || $password === '') {
    reply(422, ['status' => 'error', 'message' => 'Enter your student number or assigned login ID and password.']);
}
rate_limit('login-ip', client_ip(), 50, 900);
rate_limit('login-account', strtolower($username), 10, 900);
// Get the shared MySQLi connection used by all project panels.
$database = db();
// Refuse ambiguous matches (one account's username equals another account's email).
// Prepared queries keep form values separate from SQL text.
$stmt = $database->prepare('SELECT id, username, email, password_hash, role, is_active FROM users WHERE username = ? OR email = ? LIMIT 2');
$stmt->execute([$username, $username]);
$matches = $stmt->fetchAll();
$user = count($matches) === 1 ? $matches[0] : null;
$dummyHash = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
$valid = password_verify($password, $user ? $user['password_hash'] : $dummyHash);
if (!$valid || !$user || !(int)$user['is_active'] || !in_array($user['role'], ['admin', 'staff', 'hod', 'student'], true) || ($user['role'] === 'student' && !hash_equals((string)$user['username'], $username))) {
    reply(401, ['status' => 'error', 'message' => 'The username or password is incorrect, or the account is inactive.']);
}
$role = $user['role'];
// Lock the account while checking the password so a simultaneous account change cannot create an old session.
$database->beginTransaction();
try {
    $stmt = $database->prepare('SELECT password_hash, role, is_active FROM users WHERE id = ? FOR UPDATE');
    $stmt->execute([$user['id']]);
    $fresh = $stmt->fetch();
    if (!$fresh || !$fresh['is_active'] || $fresh['role'] !== $role || !hash_equals($user['password_hash'], $fresh['password_hash'])) {
        $database->rollBack();
        reply(401, ['status' => 'error', 'message' => 'Your account changed. Please sign in again.']);
    }
    if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
        $user['password_hash'] = password_hash($password, PASSWORD_DEFAULT);
    }
    $stmt = $database->prepare('UPDATE users SET password_hash = ?, last_login = UTC_TIMESTAMP() WHERE id = ?');
    $stmt->execute([$user['password_hash'], $user['id']]);
    $database->commit();
} catch (Throwable $e) {
    if ($database->inTransaction()) { $database->rollBack(); }
    throw $e;
}
session_regenerate_id(true);
$_SESSION = [
    'user_id' => (int)$user['id'], 'role' => $user['role'],
    'password_fingerprint' => hash('sha256', $user['password_hash']),
    'login_time' => time(), 'last_activity' => time(),
    'csrf_token' => bin2hex(random_bytes(32)),
];
require_once __DIR__.'/../../shared/lib/login_attendance.php';
record_student_login($user);
audit_event((int)$user['id'], (string)$user['role'], 'auth', (int)$user['id'], 'login', 'Signed in successfully.');
if ($isTraditionalForm) {
    // A regular form expects a page navigation, not a JSON response.
    header('Cache-Control: no-store');
    header('Location: ' . redirect_for($user['role']), true, 303);
    exit;
}
reply(200, ['status' => 'success', 'message' => 'Signed in successfully.', 'redirect' => redirect_for($user['role'])]);
