prepare("SELECT * FROM users WHERE student_id = ? AND email = ? AND role = ?"); $stmt->execute([$student_id, $email, $role]); $user = $stmt->fetch(); if ($user) { // 2. Authenticate with Supabase $auth = SupabaseAuth::signIn($email, $password); if ($auth['error']) { // Check if user exists locally with this password but not in Supabase yet if (!empty($user['password_hash']) && password_verify($password, $user['password_hash'])) { // Migrate to Supabase $supabaseUser = SupabaseAuth::createUser($email, $password); if (!$supabaseUser['error']) { $auth = SupabaseAuth::signIn($email, $password); } } } if (!$auth['error']) { // Update supabase_uid if missing if (empty($user['supabase_uid'])) { $supabase_uid = $auth['data']['user']['id'] ?? null; $upd = db()->prepare("UPDATE users SET supabase_uid = ? WHERE id = ?"); $upd->execute([$supabase_uid, $user['id']]); } $_SESSION['user_id'] = $user['id']; $_SESSION['user_role'] = $user['role']; header('Location: index.php'); exit; } else { $error = 'Authentication failed: ' . $auth['error']; } } else { $error = 'Invalid Credentials. Please check your UID, Email, and Role.'; } if ($error && isset($_POST['role'])) { // Redirect back to landing if coming from modal header('Location: index.php?error=' . urlencode($error)); exit; } } ?>