feat: Add /student and /teacher portals with Alpine.js, WhatsApp OTP, and device fingerprinting

This commit is contained in:
Hamza-Ayed
2026-08-26 22:15:33 +03:00
parent a2f72a1c29
commit 388944cbff
5 changed files with 1453 additions and 146 deletions
+298 -142
View File
@@ -8,199 +8,355 @@ use App\Core\Database;
use App\Core\Security;
use App\Core\Validator;
use App\Core\RedisClient;
use App\Services\NabehService;
class AuthController
{
/**
* Register a new user using Phone Number
*/
public function register(Request $request, Response $response): void
{
$body = $request->getBody();
$validator = new Validator();
$isValid = $validator->validate($body, [
'full_name' => 'required',
'phone_number' => 'required',
'password' => 'required|min:8',
'role' => 'required'
]);
if (!$isValid) {
$response->status(400)->json([
'status' => 'error',
'message' => 'Validation failed',
'errors' => $validator->getErrors()
]);
return;
}
$phone = $body['phone_number'];
$role = $body['role'];
if (!in_array($role, ['student', 'teacher', 'guardian'])) {
$response->status(400)->json([
'status' => 'error',
'message' => 'Invalid role specified'
]);
return;
}
$phoneHash = Security::blindIndex($phone);
$existing = Database::selectOne("SELECT id FROM users WHERE phone_hash = ? LIMIT 1", [$phoneHash]);
if ($existing) {
$response->status(409)->json([
'status' => 'error',
'message' => 'Phone number is already registered'
]);
return;
}
$passwordHash = Security::hashPassword($body['password']);
// Generate UUID
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
$userId = Database::insert(
"INSERT INTO users (uuid, full_name, phone_number, phone_hash, password_hash, role, status) VALUES (?, ?, ?, ?, ?, ?, 'active')",
[$uuid, $body['full_name'], $phone, $phoneHash, $passwordHash, $role]
);
$this->generateSessionAndRespond($userId, $uuid, $role, $response, "User registered successfully");
}
/**
* Login using Phone Number and Password
*/
public function login(Request $request, Response $response): void
{
$body = $request->getBody();
$validator = new Validator();
if (!$validator->validate($body, [
'phone_number' => 'required',
'password' => 'required'
])) {
$response->status(400)->json([
'status' => 'error',
'message' => 'Validation failed',
'errors' => $validator->getErrors()
]);
return;
}
$phoneHash = Security::blindIndex($body['phone_number']);
$user = Database::selectOne("SELECT * FROM users WHERE phone_hash = ? LIMIT 1", [$phoneHash]);
if (!$user || !Security::verifyPassword($body['password'], $user['password_hash'])) {
$response->status(401)->json([
'status' => 'error',
'message' => 'Invalid phone number or password'
]);
return;
}
if ($user['status'] === 'suspended') {
$response->status(403)->json([
'status' => 'error',
'message' => 'Account is suspended'
]);
return;
}
$this->generateSessionAndRespond($user['id'], $user['uuid'], $user['role'], $response, "Login successful");
}
/**
* Request OTP for phone verification
* Request OTP via WhatsApp (Nabeh Gateway)
* POST /api/auth/otp/request
*/
public function requestOtp(Request $request, Response $response): void
{
$body = $request->getBody();
if (empty($body['phone_number'])) {
$response->status(400)->json(['status' => 'error', 'message' => 'Phone number is required']);
$validator = new Validator();
if (!$validator->validate($body, ['phone_number' => 'required'])) {
$response->status(400)->json([
'status' => 'error',
'message' => 'رقم الهاتف مطلوب',
'errors' => $validator->getErrors()
]);
return;
}
$phone = $body['phone_number'];
$rawPhone = trim((string)$body['phone_number']);
$cleanPhone = preg_replace('/\D+/', '', $rawPhone);
// Normalize Jordanian numbers (e.g. 079XXXXXXX -> 96279XXXXXXX)
if (str_starts_with($cleanPhone, '07')) {
$cleanPhone = '962' . substr($cleanPhone, 1);
} elseif (str_starts_with($cleanPhone, '7') && strlen($cleanPhone) === 9) {
$cleanPhone = '962' . $cleanPhone;
}
if (strlen($cleanPhone) < 9 || strlen($cleanPhone) > 15) {
$response->status(400)->json([
'status' => 'error',
'message' => 'صيغة رقم الهاتف غير صحيحة'
]);
return;
}
$role = $body['role'] ?? 'student';
if (!in_array($role, ['student', 'teacher', 'guardian', 'school_admin', 'super_admin'], true)) {
$role = 'student';
}
$appName = ($role === 'teacher') ? 'صَقِل للمعلمين' : 'منصة صَقِل التعليمية';
// 1. Rate Limiting via Redis (Max 3 OTP requests per 5 minutes per phone)
$phoneHash = Security::blindIndex($cleanPhone);
try {
$redis = RedisClient::getInstance();
$rateKey = "otp_rate:{$phoneHash}";
$attempts = (int)$redis->incr($rateKey);
if ($attempts === 1) {
$redis->expire($rateKey, 300); // 5 minutes window
}
if ($attempts > 3) {
$ttl = $redis->ttl($rateKey);
$response->status(429)->json([
'status' => 'error',
'message' => "تم تجاوز الحد المسموح. يرجى المحاولة بعد {$ttl} ثانية."
]);
return;
}
} catch (\Exception $e) {
error_log("Redis rate limit warning: " . $e->getMessage());
}
// 2. Generate 6-digit OTP
$otp = (string)random_int(100000, 999999);
// Save OTP to Redis for 5 minutes
$redis = RedisClient::getInstance();
$redis->setex('otp:' . $phone, 300, $otp);
// TODO: Integrate SMS gateway here to actually send the OTP via SMS
// 3. Save OTP in Redis (TTL: 300s / 5 minutes)
try {
$redis = RedisClient::getInstance();
$otpKey = "otp:{$phoneHash}";
$redis->setex($otpKey, 300, password_hash($otp, PASSWORD_BCRYPT));
} catch (\Exception $e) {
error_log("Redis OTP store error: " . $e->getMessage());
}
$response->json([
'status' => 'success',
'message' => 'OTP sent successfully (Simulated: ' . $otp . ')'
]);
// 4. Send OTP via Nabeh Service
$nabeh = new NabehService();
$sent = $nabeh->sendOtp($cleanPhone, $otp, 'image', $appName);
$isDebug = filter_var(getenv('APP_DEBUG') ?: true, FILTER_VALIDATE_BOOLEAN);
$resData = [
'status' => 'success',
'message' => 'تم إرسال رمز التحقق بنجاح عبر الواتساب',
'data' => [
'phone_masked' => substr($cleanPhone, 0, 3) . '****' . substr($cleanPhone, -3),
'expires_in' => 300,
]
];
// Expose OTP only in debug mode for seamless local testing
if ($isDebug || !$sent) {
$resData['debug_otp'] = $otp;
if (!$sent) {
$resData['message'] = 'تم توليد رمز التحقق (بيئة التطوير / محاكاة الإرسال)';
}
}
$response->json($resData);
}
/**
* Common method to generate JWT and save session to Redis
* Verify OTP and Login / Register User
* POST /api/auth/otp/verify
*/
private function generateSessionAndRespond(int $userId, string $uuid, string $role, Response $response, string $msg): void
public function verifyOtp(Request $request, Response $response): void
{
$payload = [
'user_id' => $userId,
'uuid' => $uuid,
'role' => $role
];
$token = Security::generateJWT($payload);
$body = $request->getBody();
$validator = new Validator();
// Store session in Redis (Active for 30 days)
if (!$validator->validate($body, [
'phone_number' => 'required',
'otp' => 'required'
])) {
$response->status(400)->json([
'status' => 'error',
'message' => 'رقم الهاتف ورمز التحقق مطلوبان',
'errors' => $validator->getErrors()
]);
return;
}
$rawPhone = trim((string)$body['phone_number']);
$cleanPhone = preg_replace('/\D+/', '', $rawPhone);
if (str_starts_with($cleanPhone, '07')) {
$cleanPhone = '962' . substr($cleanPhone, 1);
} elseif (str_starts_with($cleanPhone, '7') && strlen($cleanPhone) === 9) {
$cleanPhone = '962' . $cleanPhone;
}
$inputOtp = trim((string)$body['otp']);
$role = $body['role'] ?? 'student';
$fullName = trim((string)($body['full_name'] ?? ''));
$deviceFingerprint = trim((string)($body['device_fingerprint'] ?? 'browser_default'));
$phoneHash = Security::blindIndex($cleanPhone);
// 1. Verify OTP against Redis
$redis = RedisClient::getInstance();
$otpKey = "otp:{$phoneHash}";
$storedHash = $redis->get($otpKey);
$isValidOtp = false;
if ($storedHash && password_verify($inputOtp, $storedHash)) {
$isValidOtp = true;
$redis->del($otpKey); // Invalidate OTP after success
} elseif (getenv('APP_DEBUG') && $inputOtp === '123456') {
// Master debug OTP
$isValidOtp = true;
}
if (!$isValidOtp) {
$response->status(401)->json([
'status' => 'error',
'message' => 'رمز التحقق غير صحيح أو انتهت صلاحيته'
]);
return;
}
// 2. Find or Create User
$user = Database::selectOne("SELECT * FROM users WHERE phone_hash = ? LIMIT 1", [$phoneHash]);
if (!$user) {
// New user registration
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
$encryptedPhone = Security::encrypt($cleanPhone);
$encryptedName = Security::encrypt($fullName ?: ($role === 'teacher' ? 'معلم جديد' : 'طالب جديد'));
$userId = Database::insert(
"INSERT INTO users (uuid, full_name, phone_number, phone_hash, role, status, token_version) VALUES (?, ?, ?, ?, ?, 'active', 1)",
[$uuid, $encryptedName, $encryptedPhone, $phoneHash, $role]
);
$user = [
'id' => $userId,
'uuid' => $uuid,
'full_name' => $encryptedName,
'role' => $role,
'status' => 'active',
'token_version' => 1,
'school_id' => null,
];
} else {
// Verify role access if logging into specific portal
if ($role === 'teacher' && $user['role'] !== 'teacher' && $user['role'] !== 'super_admin') {
$response->status(403)->json([
'status' => 'error',
'message' => 'هذا الحساب مسجل كطالب وليس معلماً. يرجى الدخول من بوابة الطالب.'
]);
return;
}
if ($user['status'] === 'suspended') {
$response->status(403)->json([
'status' => 'error',
'message' => 'هذا الحساب معطل. يرجى مراجعة إدارة المنصة.'
]);
return;
}
// If name provided on existing profile, update if needed
if ($fullName && (empty($user['full_name']) || Security::decrypt($user['full_name']) === 'طالب جديد')) {
Database::query("UPDATE users SET full_name = ? WHERE id = ?", [Security::encrypt($fullName), $user['id']]);
}
}
// 3. Register / Update Device Fingerprint in user_devices
try {
Database::query(
"INSERT INTO user_devices (user_id, device_fingerprint, platform, is_active, last_active_at)
VALUES (?, ?, 'web', 1, NOW())
ON DUPLICATE KEY UPDATE last_active_at = NOW(), is_active = 1",
[$user['id'], $deviceFingerprint]
);
} catch (\Exception $e) {
error_log("Device recording notice: " . $e->getMessage());
}
// 4. Issue JWT and Bind Single Session in Redis
$displayName = Security::decrypt($user['full_name']) ?: 'مستخدم صَقِل';
$this->generateSessionAndRespond(
(int)$user['id'],
$user['uuid'],
$user['role'],
$deviceFingerprint,
$cleanPhone,
$displayName,
$response,
'تم تسجيل الدخول بنجاح'
);
}
/**
* Generate Secure JWT and Enforce Single Active Session in Redis
*/
private function generateSessionAndRespond(
int $userId,
string $uuid,
string $role,
string $deviceFingerprint,
string $cleanPhone,
string $displayName,
Response $response,
string $msg
): void {
$payload = [
'user_id' => $userId,
'uuid' => $uuid,
'role' => $role,
'device_fingerprint' => $deviceFingerprint,
'phone' => $cleanPhone,
'name' => $displayName,
];
// 30 days token expiry
$token = Security::generateJWT($payload, 30 * 86400);
// Single Session Enforcement: Store active session in Redis
try {
$redis = RedisClient::getInstance();
$redis->setex("session:{$userId}:{$token}", 30 * 86400, "active");
$sessionKey = "active_session:{$userId}";
$redis->setex($sessionKey, 30 * 86400, json_encode([
'token_signature' => substr($token, -32),
'device_fingerprint' => $deviceFingerprint,
'logged_at' => date('Y-m-d H:i:s'),
'ip' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
]));
} catch (\Exception $e) {
error_log("Failed to save session to Redis: " . $e->getMessage());
error_log("Failed to save active session in Redis: " . $e->getMessage());
}
$response->status(200)->json([
'status' => 'success',
'status' => 'success',
'message' => $msg,
'data' => [
'data' => [
'token' => $token,
'user' => [
'uuid' => $uuid,
'role' => $role
'user' => [
'uuid' => $uuid,
'name' => $displayName,
'phone' => $cleanPhone,
'role' => $role,
'is_student' => ($role === 'student'),
'is_teacher' => ($role === 'teacher'),
]
]
]);
}
/**
* Get Current User Data
* Get Current Authenticated User Data
* GET /api/auth/me
*/
public function me(Request $request, Response $response): void
{
$userId = $request->user_id;
$user = Database::selectOne(
"SELECT uuid, full_name, role, status, created_at FROM users WHERE id = ? LIMIT 1",
"SELECT uuid, full_name, phone_number, role, grade_level, stream, status, created_at FROM users WHERE id = ? LIMIT 1",
[$userId]
);
if (!$user) {
$response->status(404)->json([
'status' => 'error',
'message' => 'User not found'
'status' => 'error',
'message' => 'المستخدم غير موجود'
]);
return;
}
$user['full_name'] = Security::decrypt($user['full_name']);
$user['phone_number'] = Security::decrypt($user['phone_number']);
$response->json([
'status' => 'success',
'data' => $user
'data' => $user
]);
}
/**
* Logout and destroy Redis active session
* POST /api/auth/logout
*/
public function logout(Request $request, Response $response): void
{
$userId = $request->user_id;
if ($userId) {
try {
$redis = RedisClient::getInstance();
$redis->del("active_session:{$userId}");
} catch (\Exception $e) {
error_log("Logout Redis error: " . $e->getMessage());
}
}
$response->json([
'status' => 'success',
'message' => 'تم تسجيل الخروج بنجاح'
]);
}
}
+158
View File
@@ -0,0 +1,158 @@
<?php
namespace App\Services;
use App\Core\RedisClient;
class NabehService
{
private string $authUrl;
private string $sendUrl;
private ?string $email;
private ?string $password;
public function __construct()
{
$this->authUrl = getenv('NABEH_AUTH_URL') ?: 'https://nabeh.intaleqapp.com/api/auth/login';
$this->sendUrl = getenv('NABEH_SEND_URL') ?: 'https://nabeh.intaleqapp.com/api/otp/send';
$this->email = getenv('NABEH_EMAIL') ?: null;
$this->password = getenv('NABEH_PASSWORD') ?: null;
}
/**
* Retrieve Nabeh JWT Bearer Token, caching it in Redis for 24 hours.
*/
public function getBearerToken(): ?string
{
// 1. Try fetching from Redis first
try {
$redis = RedisClient::getInstance();
$cachedToken = $redis->get('nabeh_bearer_token');
if ($cachedToken) {
return (string)$cachedToken;
}
} catch (\Exception $e) {
error_log("⚠️ [Nabeh Auth Redis] Error reading token: " . $e->getMessage());
}
// 2. Token not cached, authenticate via Nabeh Login API
if (!$this->email || !$this->password) {
error_log("⚠️ [Nabeh Auth] Missing NABEH_EMAIL or NABEH_PASSWORD environment variables.");
return null;
}
$payload = json_encode([
'email' => $this->email,
'password' => $this->password,
]);
$ch = curl_init($this->authUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $response) {
$decoded = json_decode($response, true);
$token = $decoded['token'] ?? $decoded['message']['token'] ?? $decoded['jwt'] ?? $decoded['access_token'] ?? null;
if ($token) {
// Cache token in Redis for 24h
try {
$redis = RedisClient::getInstance();
$redis->setex('nabeh_bearer_token', 86400, (string)$token);
error_log("[Nabeh Auth] Token cached in Redis successfully.");
} catch (\Exception $e) {
error_log("⚠️ [Nabeh Auth Redis Cache Save] Error saving token: " . $e->getMessage());
}
return (string)$token;
}
}
error_log("❌ [Nabeh Auth Login Failed] Response: " . $response);
return null;
}
/**
* Send OTP via Nabeh JWT Auth Gateway (WhatsApp Image/Text OTP)
*/
public function sendOtp(string $receiver, string $otp, string $method = 'image', string $appName = 'منصة صَقِل'): bool
{
$bearerToken = $this->getBearerToken();
if (!$bearerToken) {
error_log("⚠️ [Nabeh OTP] Failed to obtain dynamic JWT Bearer token.");
return false;
}
$phoneRaw = preg_replace('/\D+/', '', $receiver);
$type = in_array($method, ['text', 'voice', 'image'], true) ? $method : 'image';
// 1. First attempt with image
$success = $this->attemptSend($phoneRaw, $type, $otp, $appName, $bearerToken);
if ($success) {
return true;
}
// 2. Fallback to text if image fails
if ($type === 'image') {
error_log("ℹ️ [Nabeh OTP Fallback] Image failed, retrying with text type...");
return $this->attemptSend($phoneRaw, 'text', $otp, $appName, $bearerToken);
}
return false;
}
private function attemptSend(string $phone, string $type, string $otp, string $appName, string $bearerToken): bool
{
$payload = json_encode([
'phone' => $phone,
'type' => $type,
'code' => $otp,
'message' => "رمز التحقق الخاص بك لمنصة {$appName} هو: *{$otp}* \n الرجاء عدم مشاركته مع أي شخص لحماية حسابك.",
]);
$ch = curl_init($this->sendUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"Authorization: Bearer {$bearerToken}",
],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $response) {
$decoded = json_decode($response, true);
if ($decoded) {
$statusStr = strtolower((string)($decoded['status'] ?? ''));
$msgStr = strtolower((string)($decoded['message'] ?? ''));
if (
!empty($decoded['success']) ||
in_array($statusStr, ['success', 'ok', 'true', '200', 'sent', 'queued', '1'], true) ||
($decoded['status'] ?? false) === true ||
str_contains($msgStr, 'success') ||
str_contains($msgStr, 'sent') ||
str_contains($msgStr, 'تم')
) {
return true;
}
}
}
error_log("❌ [Nabeh OTP Attempt Failed] Code: {$httpCode} Response: {$response}");
return false;
}
}
+508
View File
@@ -0,0 +1,508 @@
<?php
namespace App\Views;
class StudentPortal
{
public static function render(): string
{
return <<<'HTML'
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>بوابة الطالب — منصة صَقِل التعليمية</title>
<!-- Google Fonts: Cairo -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
saqel: {
dark: '#0B132B',
card: '#1C2541',
cardHover: '#222F55',
cyan: '#00F5D4',
cyanGlow: '#00F5D433',
gold: '#FFD166',
goldGlow: '#FFD16633',
border: '#2E3D66',
textMuted: '#94A3B8'
}
},
fontFamily: {
cairo: ['Cairo', 'sans-serif'],
}
}
}
}
</script>
<!-- Alpine.js -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<style>
body { font-family: 'Cairo', sans-serif; }
[x-cloak] { display: none !important; }
.glow-cyan { box-shadow: 0 0 25px -5px rgba(0, 245, 212, 0.35); }
.glow-gold { box-shadow: 0 0 25px -5px rgba(255, 209, 102, 0.35); }
.bg-grid {
background-size: 30px 30px;
background-image: linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
}
@keyframes bounce-watermark {
0%, 100% { transform: translate(10px, 10px); }
50% { transform: translate(120px, 60px); }
}
.watermark-anim { animation: bounce-watermark 12s infinite ease-in-out; }
</style>
</head>
<body class="bg-saqel-dark text-slate-100 min-h-screen bg-grid antialiased flex flex-col justify-between selection:bg-saqel-cyan selection:text-saqel-dark"
x-data="studentAuth()" x-init="initApp()">
<!-- Top Navigation Bar -->
<header class="border-b border-saqel-border/60 bg-saqel-dark/80 backdrop-blur-md sticky top-0 z-40">
<div class="max-w-6xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-saqel-cyan to-saqel-gold p-[2px] flex items-center justify-center glow-cyan">
<div class="w-full h-full bg-saqel-dark rounded-[10px] flex items-center justify-center text-saqel-cyan font-black text-xl">
صـ
</div>
</div>
<div>
<span class="font-extrabold text-lg text-white tracking-wide">صَقِل</span>
<span class="text-xs px-2 py-0.5 rounded-full bg-saqel-cyan/10 text-saqel-cyan border border-saqel-cyan/30 mr-2">بوابة الطالب</span>
</div>
</div>
<!-- Header Right Controls -->
<div class="flex items-center gap-3">
<template x-if="isLoggedIn">
<div class="flex items-center gap-3">
<span class="text-sm text-saqel-textMuted hidden sm:inline" x-text="'مرحباً، ' + (studentData.name || 'طالب صَقِل')"></span>
<button @click="logout()" class="text-xs px-3 py-1.5 rounded-lg border border-red-500/40 text-red-400 hover:bg-red-500/10 transition">
تسجيل الخروج
</button>
</div>
</template>
<template x-if="!isLoggedIn">
<a href="/teacher" class="text-xs sm:text-sm text-saqel-textMuted hover:text-saqel-gold transition flex items-center gap-1">
<span>أنت معلم؟</span>
<span class="text-saqel-gold font-bold">بوابة المعلمين ←</span>
</a>
</template>
</div>
</div>
</header>
<!-- Main Content Container -->
<main class="flex-1 max-w-6xl mx-auto px-4 sm:px-6 py-8 w-full flex items-center justify-center">
<!-- ============================================================= -->
<!-- VIEW 1: AUTHENTICATION FLOW (Phone Number & WhatsApp OTP) -->
<!-- ============================================================= -->
<div x-show="!isLoggedIn" class="w-full max-w-md" x-cloak>
<!-- Card Header -->
<div class="text-center mb-8">
<div class="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-saqel-card border border-saqel-cyan/30 text-saqel-cyan mb-4 glow-cyan">
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
</svg>
</div>
<h1 class="text-2xl sm:text-3xl font-black text-white">ادخل لعالم التمكين والفهم</h1>
<p class="text-sm text-saqel-textMuted mt-2">تسجيل دخول آمن وسريع عبر رمز الواتساب</p>
</div>
<!-- Auth Box -->
<div class="bg-saqel-card/90 border border-saqel-border rounded-2xl p-6 sm:p-8 shadow-2xl backdrop-blur-xl relative overflow-hidden">
<!-- Glow Accent -->
<div class="absolute top-0 right-0 w-32 h-32 bg-saqel-cyan/10 rounded-full blur-2xl pointer-events-none"></div>
<!-- Alert Messages -->
<div x-show="errorMessage" x-cloak class="mb-5 p-3.5 rounded-xl bg-red-500/10 border border-red-500/30 text-red-300 text-sm flex items-start gap-2">
<svg class="w-5 h-5 text-red-400 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
<span x-text="errorMessage"></span>
</div>
<div x-show="successMessage" x-cloak class="mb-5 p-3.5 rounded-xl bg-saqel-cyan/10 border border-saqel-cyan/30 text-saqel-cyan text-sm flex items-start gap-2">
<svg class="w-5 h-5 text-saqel-cyan shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
<span x-text="successMessage"></span>
</div>
<!-- STEP 1: PHONE NUMBER INPUT -->
<div x-show="authStep === 'phone'">
<form @submit.prevent="sendOtp()">
<!-- Full Name for New Registration -->
<div class="mb-4">
<label class="block text-xs font-bold text-saqel-textMuted mb-2">الاسم الكامل للتعريف بشهاداتك (اختياري)</label>
<input type="text" x-model="fullName" placeholder="مثال: أحمد محمد خالد"
class="w-full bg-saqel-dark/90 border border-saqel-border focus:border-saqel-cyan focus:ring-1 focus:ring-saqel-cyan rounded-xl px-4 py-3 text-sm text-white placeholder:text-slate-600 outline-none transition">
</div>
<!-- Phone Number with Jordan Prefix -->
<div class="mb-6">
<label class="block text-xs font-bold text-saqel-textMuted mb-2">رقم الهاتف (الواتساب) <span class="text-red-400">*</span></label>
<div class="relative flex items-center" dir="ltr">
<span class="absolute left-3.5 text-sm font-bold text-saqel-cyan bg-saqel-dark px-2 py-1 rounded-md border border-saqel-border">
🇯🇴 +962
</span>
<input type="tel" x-model="phone" required placeholder="790000000"
class="w-full bg-saqel-dark/90 border border-saqel-border focus:border-saqel-cyan focus:ring-1 focus:ring-saqel-cyan rounded-xl pl-28 pr-4 py-3 text-sm text-white placeholder:text-slate-600 outline-none transition font-mono tracking-wider">
</div>
<span class="text-[11px] text-saqel-textMuted block mt-1.5">سيصلك رمز التحقق مباشرة على الواتساب المعتمد.</span>
</div>
<!-- Submit Button -->
<button type="submit" :disabled="loading"
class="w-full py-3.5 px-4 bg-gradient-to-r from-saqel-cyan to-teal-400 text-saqel-dark font-extrabold rounded-xl hover:opacity-95 transition shadow-lg glow-cyan flex items-center justify-center gap-2 disabled:opacity-50">
<template x-if="loading">
<svg class="animate-spin h-5 w-5 text-saqel-dark" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg>
</template>
<span x-text="loading ? 'جارٍ الإرسال...' : 'إرسال رمز التحقق (OTP) ←'"></span>
</button>
</form>
</div>
<!-- STEP 2: OTP VERIFICATION -->
<div x-show="authStep === 'otp'" x-cloak>
<div class="text-center mb-6">
<span class="text-xs text-saqel-textMuted">تم إرسال الرمز إلى:</span>
<div class="font-mono font-bold text-saqel-cyan text-sm mt-0.5" x-text="phoneDisplay"></div>
</div>
<form @submit.prevent="verifyOtp()">
<!-- 6 Digits OTP Input -->
<div class="mb-6">
<label class="block text-xs font-bold text-saqel-textMuted mb-2 text-center">أدخل رمز التحقق (6 أرقام)</label>
<input type="text" x-model="otpCode" maxlength="6" autofocus placeholder="• • • • • •"
class="w-full bg-saqel-dark/90 border border-saqel-cyan/50 focus:border-saqel-cyan focus:ring-2 focus:ring-saqel-cyan/30 rounded-xl px-4 py-3.5 text-center text-2xl font-mono tracking-[0.5em] text-saqel-cyan placeholder:text-slate-700 outline-none transition">
</div>
<!-- Submit Verification -->
<button type="submit" :disabled="loading || otpCode.length < 6"
class="w-full py-3.5 px-4 bg-gradient-to-r from-saqel-cyan to-teal-400 text-saqel-dark font-extrabold rounded-xl hover:opacity-95 transition shadow-lg glow-cyan flex items-center justify-center gap-2 disabled:opacity-50">
<template x-if="loading">
<svg class="animate-spin h-5 w-5 text-saqel-dark" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg>
</template>
<span x-text="loading ? 'جارٍ التحقق...' : 'تأكيد الدخول للمنصة ✨'"></span>
</button>
<!-- Actions: Resend / Change Phone -->
<div class="flex items-center justify-between text-xs mt-5 pt-4 border-t border-saqel-border/50 text-saqel-textMuted">
<button type="button" @click="authStep = 'phone'" class="hover:text-white transition">← تعديل الرقم</button>
<template x-if="timer > 0">
<span class="text-slate-500" x-text="'إعادة الإرسال بعد (' + timer + 'ث)'"></span>
</template>
<template x-if="timer === 0">
<button type="button" @click="sendOtp()" class="text-saqel-cyan hover:underline font-bold">إعادة إرسال الرمز ↺</button>
</template>
</div>
</form>
</div>
<!-- Footer Security Notice -->
<div class="mt-6 pt-4 border-t border-saqel-border/40 text-center flex items-center justify-center gap-2 text-[11px] text-slate-500">
<svg class="w-3.5 h-3.5 text-saqel-cyan" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"></path></svg>
<span>اتصال مشفر بتكنولوجيا Zero-Trust وبصمة الجهاز</span>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- VIEW 2: STUDENT DASHBOARD WORKSPACE (Once Authenticated) -->
<!-- ============================================================= -->
<div x-show="isLoggedIn" class="w-full space-y-8" x-cloak>
<!-- Dashboard Welcome Banner with Exam Readiness -->
<div class="bg-gradient-to-r from-saqel-card to-saqel-cardHover border border-saqel-border rounded-3xl p-6 sm:p-8 shadow-xl relative overflow-hidden">
<div class="flex flex-col md:flex-row md:items-center justify-between gap-6 relative z-10">
<div>
<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-saqel-cyan/10 border border-saqel-cyan/30 text-saqel-cyan text-xs font-bold mb-3">
<span class="w-2 h-2 rounded-full bg-saqel-cyan animate-ping"></span>
<span>دفعة التوجيهي 2007/2008</span>
</div>
<h2 class="text-2xl sm:text-3xl font-black text-white" x-text="'أهلاً بك، ' + (studentData.name || 'طالبنا المتميز') + ' 🚀'"></h2>
<p class="text-sm text-saqel-textMuted mt-1">رحلتك لصقل الفهم وتحقيق أعلى معدل وزاري تبدأ هنا.</p>
</div>
<!-- Exam Readiness Gauge -->
<div class="bg-saqel-dark/80 border border-saqel-border p-4 rounded-2xl flex items-center gap-4 min-w-[240px]">
<div class="w-14 h-14 rounded-full border-4 border-saqel-cyan flex items-center justify-center font-black text-lg text-saqel-cyan glow-cyan">
84%
</div>
<div>
<span class="text-xs font-bold text-saqel-textMuted block">مؤشر الجاهزية للوزاري</span>
<span class="text-xs text-emerald-400 font-semibold">ممتاز — مسارك مستقر</span>
</div>
</div>
</div>
</div>
<!-- Features Grid (Courses & In-Video Quiz Demo) -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<!-- Card 1: Tawjihi Math -->
<div class="bg-saqel-card border border-saqel-border rounded-2xl p-5 hover:border-saqel-cyan/50 transition group cursor-pointer">
<div class="flex items-center justify-between mb-3">
<span class="text-xs font-bold px-2.5 py-1 rounded-lg bg-blue-500/10 text-blue-400 border border-blue-500/20">علمي</span>
<span class="text-xs text-saqel-textMuted">18 درس • كويزات تفاعلية</span>
</div>
<h3 class="font-extrabold text-white text-lg group-hover:text-saqel-cyan transition">الرياضيات العلمي — المستوى الثالث</h3>
<p class="text-xs text-saqel-textMuted mt-2 line-clamp-2">شرح تفاعلي لمفاهيم الاشتقاق والنهايات مع أسئلة وزارية محاكية.</p>
<div class="mt-4 pt-3 border-t border-saqel-border/50 flex items-center justify-between text-xs">
<span class="text-saqel-cyan font-bold">متابعة الدرس 4 ←</span>
<span class="text-slate-400">مكتمل 45%</span>
</div>
</div>
<!-- Card 2: Physics -->
<div class="bg-saqel-card border border-saqel-border rounded-2xl p-5 hover:border-saqel-gold/50 transition group cursor-pointer">
<div class="flex items-center justify-between mb-3">
<span class="text-xs font-bold px-2.5 py-1 rounded-lg bg-amber-500/10 text-amber-400 border border-amber-500/20">علمي</span>
<span class="text-xs text-saqel-textMuted">14 درس • تجارب تفاعلية</span>
</div>
<h3 class="font-extrabold text-white text-lg group-hover:text-saqel-gold transition">الفيزياء — الميكانيكا والطاقة</h3>
<p class="text-xs text-saqel-textMuted mt-2 line-clamp-2">صقل مفاهيم الزخم الخطي والتصادمات وتطبيقاتها في الامتحانات.</p>
<div class="mt-4 pt-3 border-t border-saqel-border/50 flex items-center justify-between text-xs">
<span class="text-saqel-gold font-bold">بدء التعلم ←</span>
<span class="text-slate-400">جديد</span>
</div>
</div>
<!-- Card 3: Interactive Voice Notes Demo -->
<div class="bg-saqel-card border border-saqel-border rounded-2xl p-5 hover:border-saqel-cyan/50 transition group">
<div class="flex items-center justify-between mb-3">
<span class="text-xs font-bold px-2.5 py-1 rounded-lg bg-purple-500/10 text-purple-400 border border-purple-500/20">ميزة ذكية</span>
<span class="text-xs text-saqel-cyan font-bold">Whisper AI</span>
</div>
<h3 class="font-extrabold text-white text-lg">الملاحظات الصوتية والتفريغ</h3>
<p class="text-xs text-saqel-textMuted mt-2">سجل أي ملاحظة بصوتك أثناء الحصة، والذكاء الاصطناعي يفرغها لنص فوري.</p>
<div class="mt-4 pt-3 border-t border-saqel-border/50 flex items-center justify-between text-xs">
<span class="text-saqel-cyan font-bold">دفتر الملاحظات (3) ←</span>
</div>
</div>
</div>
<!-- Interactive In-Video Quiz Demo Section -->
<div class="bg-saqel-card/90 border border-saqel-cyan/40 rounded-3xl p-6 sm:p-8 shadow-2xl relative overflow-hidden">
<div class="max-w-2xl">
<div class="flex items-center gap-2 text-saqel-cyan text-xs font-bold mb-2">
<span class="px-2 py-0.5 rounded bg-saqel-cyan/10 border border-saqel-cyan/30">تجربة تفاعلية (Coursera Model)</span>
</div>
<h3 class="text-xl font-extrabold text-white">كيف يعمل الكويز الصدمي داخل الفيديو؟</h3>
<p class="text-xs text-saqel-textMuted mt-1 mb-6">يتوقف الفيديو تلقائياً عند لحظة قياس الفهم. إذا أخطأت، يعيدك المشغل 45 ثانية لمشاهدة شرح المفهوم مجدداً.</p>
<!-- Interactive Demo Box -->
<div class="bg-saqel-dark p-5 rounded-2xl border border-saqel-border" x-data="{ selectedOpt: null, answered: false, isCorrect: false }">
<div class="text-xs text-saqel-gold font-bold mb-2">سؤال اللحظة (الدقيقة 08:30 من درس الاشتقاق):</div>
<p class="text-sm font-bold text-white mb-4">ما هو مشتق اقتران الجيب $f(x) = \sin(x)$ بالنسبة لـ $x$؟</p>
<div class="space-y-2.5">
<button @click="selectedOpt = 1; answered = true; isCorrect = true"
:class="answered && selectedOpt === 1 ? 'bg-emerald-500/20 border-emerald-400 text-emerald-300' : 'bg-saqel-card border-saqel-border text-slate-200 hover:border-saqel-cyan'"
class="w-full text-right p-3 rounded-xl border text-xs font-bold transition flex items-center justify-between">
<span>أ) $\cos(x)$</span>
<span x-show="answered && selectedOpt === 1" class="text-emerald-400">✓ إجابة صحيحة! استئناف الفيديو</span>
</button>
<button @click="selectedOpt = 2; answered = true; isCorrect = false"
:class="answered && selectedOpt === 2 ? 'bg-red-500/20 border-red-400 text-red-300' : 'bg-saqel-card border-saqel-border text-slate-200 hover:border-saqel-cyan'"
class="w-full text-right p-3 rounded-xl border text-xs font-bold transition flex items-center justify-between">
<span>ب) $-\cos(x)$</span>
<span x-show="answered && selectedOpt === 2" class="text-red-400">✗ خطأ — سيتم إرجاعك 45 ثانية للشرح</span>
</button>
</div>
</div>
</div>
</div>
<!-- Dynamic Watermark Overlay Simulator -->
<div class="fixed bottom-4 left-4 z-50 pointer-events-none opacity-40 watermark-anim select-none">
<div class="bg-black/60 backdrop-blur-sm px-3 py-1 rounded border border-white/20 text-[10px] font-mono text-saqel-cyan">
<span x-text="'SAQEL-DRM • ' + (studentData.phone || '079XXXXXXX')"></span>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="border-t border-saqel-border/40 py-6 text-center text-xs text-saqel-textMuted">
<div class="max-w-6xl mx-auto px-4 flex flex-col sm:flex-row items-center justify-between gap-3">
<span>منصة صَقِل التعليمية — الجيل الثاني للتعليم التفاعلي © 2026</span>
<div class="flex items-center gap-4">
<a href="/teacher" class="hover:text-saqel-cyan transition">بوابة المعلم</a>
<span class="text-slate-700">•</span>
<span class="text-emerald-400">الخادم متصل ومشفر 🔒</span>
</div>
</div>
</footer>
<!-- Alpine.js Application Logic -->
<script>
function studentAuth() {
return {
isLoggedIn: false,
authStep: 'phone', // 'phone' | 'otp'
phone: '',
fullName: '',
otpCode: '',
phoneDisplay: '',
loading: false,
errorMessage: '',
successMessage: '',
timer: 0,
timerInterval: null,
deviceFingerprint: '',
studentData: {},
async initApp() {
this.deviceFingerprint = await this.generateDeviceFingerprint();
const token = localStorage.getItem('saqel_student_jwt');
if (token) {
await this.fetchProfile(token);
}
},
async generateDeviceFingerprint() {
const raw = [
navigator.userAgent,
navigator.language,
screen.width + 'x' + screen.height,
Intl.DateTimeFormat().resolvedOptions().timeZone
].join('###');
const msgUint8 = new TextEncoder().encode(raw);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
},
async sendOtp() {
this.loading = true;
this.errorMessage = '';
this.successMessage = '';
try {
const res = await fetch('/api/auth/otp/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
role: 'student',
full_name: this.fullName
})
});
const data = await res.json();
if (res.ok) {
this.authStep = 'otp';
this.phoneDisplay = data.data?.phone_masked || this.phone;
this.successMessage = data.message;
if (data.debug_otp) {
this.otpCode = data.debug_otp; // Auto-fill in dev mode
}
this.startTimer(60);
} else {
this.errorMessage = data.message || 'فشل إرسال رمز التحقق';
}
} catch (e) {
this.errorMessage = 'حدث خطأ في الاتصال بالخادم';
} finally {
this.loading = false;
}
},
async verifyOtp() {
this.loading = true;
this.errorMessage = '';
try {
const res = await fetch('/api/auth/otp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
otp: this.otpCode,
role: 'student',
full_name: this.fullName,
device_fingerprint: this.deviceFingerprint
})
});
const data = await res.json();
if (res.ok && data.data?.token) {
localStorage.setItem('saqel_student_jwt', data.data.token);
this.studentData = data.data.user;
this.isLoggedIn = true;
this.successMessage = 'تم تسجيل الدخول بنجاح!';
} else {
this.errorMessage = data.message || 'رمز التحقق غير صحيح';
}
} catch (e) {
this.errorMessage = 'حدث خطأ في التحقق من الرمز';
} finally {
this.loading = false;
}
},
async fetchProfile(token) {
try {
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await res.json();
if (res.ok && data.data) {
this.studentData = {
name: data.data.full_name,
phone: data.data.phone_number,
role: data.data.role
};
this.isLoggedIn = true;
} else {
localStorage.removeItem('saqel_student_jwt');
this.isLoggedIn = false;
}
} catch (e) {
this.isLoggedIn = false;
}
},
logout() {
const token = localStorage.getItem('saqel_student_jwt');
if (token) {
fetch('/api/auth/logout', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token }
});
}
localStorage.removeItem('saqel_student_jwt');
this.isLoggedIn = false;
this.authStep = 'phone';
this.otpCode = '';
},
startTimer(seconds) {
this.timer = seconds;
clearInterval(this.timerInterval);
this.timerInterval = setInterval(() => {
if (this.timer > 0) {
this.timer--;
} else {
clearInterval(this.timerInterval);
}
}, 1000);
}
}
}
</script>
</body>
</html>
HTML;
}
}
+465
View File
@@ -0,0 +1,465 @@
<?php
namespace App\Views;
class TeacherPortal
{
public static function render(): string
{
return <<<'HTML'
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>بوابة المعلم — استوديو صَقِل التعليمي</title>
<!-- Google Fonts: Cairo -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
saqel: {
dark: '#0B132B',
card: '#1C2541',
cardHover: '#222F55',
cyan: '#00F5D4',
gold: '#FFD166',
goldGlow: '#FFD16633',
border: '#2E3D66',
textMuted: '#94A3B8'
}
},
fontFamily: {
cairo: ['Cairo', 'sans-serif'],
}
}
}
}
</script>
<!-- Alpine.js -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<style>
body { font-family: 'Cairo', sans-serif; }
[x-cloak] { display: none !important; }
.glow-gold { box-shadow: 0 0 25px -5px rgba(255, 209, 102, 0.35); }
.bg-grid {
background-size: 30px 30px;
background-image: linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
}
</style>
</head>
<body class="bg-saqel-dark text-slate-100 min-h-screen bg-grid antialiased flex flex-col justify-between selection:bg-saqel-gold selection:text-saqel-dark"
x-data="teacherAuth()" x-init="initApp()">
<!-- Top Navigation Bar -->
<header class="border-b border-saqel-border/60 bg-saqel-dark/80 backdrop-blur-md sticky top-0 z-40">
<div class="max-w-6xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-saqel-gold to-amber-500 p-[2px] flex items-center justify-center glow-gold">
<div class="w-full h-full bg-saqel-dark rounded-[10px] flex items-center justify-center text-saqel-gold font-black text-xl">
صـ
</div>
</div>
<div>
<span class="font-extrabold text-lg text-white tracking-wide">صَقِل</span>
<span class="text-xs px-2 py-0.5 rounded-full bg-saqel-gold/10 text-saqel-gold border border-saqel-gold/30 mr-2">استوديو المعلمين</span>
</div>
</div>
<!-- Header Right Controls -->
<div class="flex items-center gap-3">
<template x-if="isLoggedIn">
<div class="flex items-center gap-3">
<span class="text-sm text-saqel-textMuted hidden sm:inline" x-text="'أهلاً، ' + (teacherData.name || 'أستاذنا')"></span>
<button @click="logout()" class="text-xs px-3 py-1.5 rounded-lg border border-red-500/40 text-red-400 hover:bg-red-500/10 transition">
تسجيل الخروج
</button>
</div>
</template>
<template x-if="!isLoggedIn">
<a href="/student" class="text-xs sm:text-sm text-saqel-textMuted hover:text-saqel-cyan transition flex items-center gap-1">
<span>أنت طالب؟</span>
<span class="text-saqel-cyan font-bold">بوابة الطلاب ←</span>
</a>
</template>
</div>
</div>
</header>
<!-- Main Content Container -->
<main class="flex-1 max-w-6xl mx-auto px-4 sm:px-6 py-8 w-full flex items-center justify-center">
<!-- ============================================================= -->
<!-- VIEW 1: TEACHER AUTHENTICATION FLOW -->
<!-- ============================================================= -->
<div x-show="!isLoggedIn" class="w-full max-w-md" x-cloak>
<!-- Card Header -->
<div class="text-center mb-8">
<div class="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-saqel-card border border-saqel-gold/30 text-saqel-gold mb-4 glow-gold">
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
</svg>
</div>
<h1 class="text-2xl sm:text-3xl font-black text-white">استوديو صَقِل للمعلمين</h1>
<p class="text-sm text-saqel-textMuted mt-2">منصة تصنع المعلم الرقمي الأول — حماية محتواك وأرباح متنامية</p>
</div>
<!-- Auth Box -->
<div class="bg-saqel-card/90 border border-saqel-border rounded-2xl p-6 sm:p-8 shadow-2xl backdrop-blur-xl relative overflow-hidden">
<!-- Glow Accent -->
<div class="absolute top-0 left-0 w-32 h-32 bg-saqel-gold/10 rounded-full blur-2xl pointer-events-none"></div>
<!-- Alert Messages -->
<div x-show="errorMessage" x-cloak class="mb-5 p-3.5 rounded-xl bg-red-500/10 border border-red-500/30 text-red-300 text-sm flex items-start gap-2">
<svg class="w-5 h-5 text-red-400 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
<span x-text="errorMessage"></span>
</div>
<div x-show="successMessage" x-cloak class="mb-5 p-3.5 rounded-xl bg-saqel-gold/10 border border-saqel-gold/30 text-saqel-gold text-sm flex items-start gap-2">
<svg class="w-5 h-5 text-saqel-gold shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
<span x-text="successMessage"></span>
</div>
<!-- STEP 1: PHONE NUMBER INPUT -->
<div x-show="authStep === 'phone'">
<form @submit.prevent="sendOtp()">
<!-- Full Name -->
<div class="mb-4">
<label class="block text-xs font-bold text-saqel-textMuted mb-2">اسم المعلم / الأستاذ</label>
<input type="text" x-model="fullName" placeholder="مثال: الأستاذ حمزة النجار"
class="w-full bg-saqel-dark/90 border border-saqel-border focus:border-saqel-gold focus:ring-1 focus:ring-saqel-gold rounded-xl px-4 py-3 text-sm text-white placeholder:text-slate-600 outline-none transition">
</div>
<!-- Phone Number -->
<div class="mb-6">
<label class="block text-xs font-bold text-saqel-textMuted mb-2">رقم الهاتف (الواتساب) <span class="text-red-400">*</span></label>
<div class="relative flex items-center" dir="ltr">
<span class="absolute left-3.5 text-sm font-bold text-saqel-gold bg-saqel-dark px-2 py-1 rounded-md border border-saqel-border">
🇯🇴 +962
</span>
<input type="tel" x-model="phone" required placeholder="790000000"
class="w-full bg-saqel-dark/90 border border-saqel-border focus:border-saqel-gold focus:ring-1 focus:ring-saqel-gold rounded-xl pl-28 pr-4 py-3 text-sm text-white placeholder:text-slate-600 outline-none transition font-mono tracking-wider">
</div>
<span class="text-[11px] text-saqel-textMuted block mt-1.5">يُشترط رقم مسجل ومعتمد لدى إدارة المنصة.</span>
</div>
<!-- Submit Button -->
<button type="submit" :disabled="loading"
class="w-full py-3.5 px-4 bg-gradient-to-r from-saqel-gold to-amber-500 text-saqel-dark font-extrabold rounded-xl hover:opacity-95 transition shadow-lg glow-gold flex items-center justify-center gap-2 disabled:opacity-50">
<template x-if="loading">
<svg class="animate-spin h-5 w-5 text-saqel-dark" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg>
</template>
<span x-text="loading ? 'جارٍ التحقق...' : 'دخول استوديو المعلم (OTP) ←'"></span>
</button>
</form>
</div>
<!-- STEP 2: OTP VERIFICATION -->
<div x-show="authStep === 'otp'" x-cloak>
<div class="text-center mb-6">
<span class="text-xs text-saqel-textMuted">تم إرسال الرمز للواتساب:</span>
<div class="font-mono font-bold text-saqel-gold text-sm mt-0.5" x-text="phoneDisplay"></div>
</div>
<form @submit.prevent="verifyOtp()">
<!-- 6 Digits OTP Input -->
<div class="mb-6">
<label class="block text-xs font-bold text-saqel-textMuted mb-2 text-center">أدخل رمز التحقق (6 أرقام)</label>
<input type="text" x-model="otpCode" maxlength="6" autofocus placeholder="• • • • • •"
class="w-full bg-saqel-dark/90 border border-saqel-gold/50 focus:border-saqel-gold focus:ring-2 focus:ring-saqel-gold/30 rounded-xl px-4 py-3.5 text-center text-2xl font-mono tracking-[0.5em] text-saqel-gold placeholder:text-slate-700 outline-none transition">
</div>
<!-- Submit Verification -->
<button type="submit" :disabled="loading || otpCode.length < 6"
class="w-full py-3.5 px-4 bg-gradient-to-r from-saqel-gold to-amber-500 text-saqel-dark font-extrabold rounded-xl hover:opacity-95 transition shadow-lg glow-gold flex items-center justify-center gap-2 disabled:opacity-50">
<template x-if="loading">
<svg class="animate-spin h-5 w-5 text-saqel-dark" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg>
</template>
<span x-text="loading ? 'جارٍ التحقق...' : 'تأكيد الدخول للاستوديو 🎓'"></span>
</button>
<!-- Actions -->
<div class="flex items-center justify-between text-xs mt-5 pt-4 border-t border-saqel-border/50 text-saqel-textMuted">
<button type="button" @click="authStep = 'phone'" class="hover:text-white transition">← تعديل الرقم</button>
<template x-if="timer > 0">
<span class="text-slate-500" x-text="'إعادة الإرسال بعد (' + timer + 'ث)'"></span>
</template>
<template x-if="timer === 0">
<button type="button" @click="sendOtp()" class="text-saqel-gold hover:underline font-bold">إعادة إرسال الرمز ↺</button>
</template>
</div>
</form>
</div>
<!-- Footer Partner Notice -->
<div class="mt-6 pt-4 border-t border-saqel-border/40 text-center text-[11px] text-slate-500">
<span>حماية محتوى DRM كاملة + تقاسم أرباح 45%–50% شفاف ومؤتمت</span>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- VIEW 2: TEACHER STUDIO WORKSPACE -->
<!-- ============================================================= -->
<div x-show="isLoggedIn" class="w-full space-y-8" x-cloak>
<!-- Teacher Summary Header -->
<div class="bg-gradient-to-r from-saqel-card to-saqel-cardHover border border-saqel-border rounded-3xl p-6 sm:p-8 shadow-xl">
<div class="flex flex-col md:flex-row md:items-center justify-between gap-6">
<div>
<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-saqel-gold/10 border border-saqel-gold/30 text-saqel-gold text-xs font-bold mb-3">
<span>استوديو المعلم المعتمد</span>
</div>
<h2 class="text-2xl sm:text-3xl font-black text-white" x-text="'أهلاً بك، ' + (teacherData.name || 'أستاذنا الفاضل') + ' 👨‍🏫'"></h2>
<p class="text-sm text-saqel-textMuted mt-1">إدارة دوراتك، إدراج كويزات الفيديو التفاعلية، ومتابعة نمو طلابك.</p>
</div>
<!-- Teacher Earnings Summary -->
<div class="flex items-center gap-4">
<div class="bg-saqel-dark/80 border border-saqel-border p-4 rounded-2xl text-center min-w-[130px]">
<span class="text-xs text-saqel-textMuted block font-bold">إجمالي الطلاب</span>
<span class="text-2xl font-black text-saqel-cyan">1,240</span>
</div>
<div class="bg-saqel-dark/80 border border-saqel-gold/40 p-4 rounded-2xl text-center min-w-[150px] glow-gold">
<span class="text-xs text-saqel-textMuted block font-bold">أرباحك المتراكمة</span>
<span class="text-2xl font-black text-saqel-gold">19,530 د.أ</span>
</div>
</div>
</div>
</div>
<!-- In-Video Quiz Creator Tool (Coursera Engine) -->
<div class="bg-saqel-card border border-saqel-border rounded-3xl p-6 sm:p-8 shadow-xl">
<div class="flex items-center justify-between mb-6">
<div>
<h3 class="text-lg font-black text-white">إضافة كويز تفاعلي داخل الفيديو 🎬</h3>
<p class="text-xs text-saqel-textMuted mt-1">حدد الثانية الزمنية في الفيديو التي سيتوقف عندها الشرح لفحص فهم الطالب.</p>
</div>
<span class="text-xs px-3 py-1 rounded-lg bg-saqel-cyan/10 text-saqel-cyan border border-saqel-cyan/30 font-bold">Bunny Stream Synced</span>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 bg-saqel-dark/80 p-5 rounded-2xl border border-saqel-border">
<div>
<label class="block text-xs font-bold text-saqel-textMuted mb-2">اختر الدورة والدرس</label>
<select class="w-full bg-saqel-card border border-saqel-border rounded-xl px-4 py-2.5 text-xs text-white outline-none">
<option>الرياضيات العلمي — الدرس 4: قواعد الاشتقاق الأساسية</option>
<option>الرياضيات العلمي — الدرس 5: الاشتقاق الضمني</option>
</select>
<div class="mt-4">
<label class="block text-xs font-bold text-saqel-textMuted mb-2">توقيت ظهور الكويز (بالدقيقة والثانية)</label>
<input type="text" value="08:30" class="w-full bg-saqel-card border border-saqel-border rounded-xl px-4 py-2.5 text-xs text-saqel-cyan font-mono outline-none">
</div>
<div class="mt-4">
<label class="block text-xs font-bold text-saqel-textMuted mb-2">عقوبة الخطأ (الإرجاع العلاجي)</label>
<select class="w-full bg-saqel-card border border-saqel-border rounded-xl px-4 py-2.5 text-xs text-white outline-none">
<option>إرجاع الطالب 45 ثانية للخلف (مستحسن)</option>
<option>إرجاع الطالب 60 ثانية للخلف</option>
<option>إعادة مشاهدة المقطع بالكامل</option>
</select>
</div>
</div>
<div>
<label class="block text-xs font-bold text-saqel-textMuted mb-2">نص السؤال التفاعلي</label>
<textarea rows="3" placeholder="اكتب السؤال الذي سيظهر أمام الطالب..." class="w-full bg-saqel-card border border-saqel-border rounded-xl p-3 text-xs text-white outline-none resize-none"></textarea>
<div class="mt-3 space-y-2">
<input type="text" placeholder="الخيار الأول (الصحيح)" class="w-full bg-saqel-card border border-emerald-500/40 rounded-xl px-3 py-2 text-xs text-emerald-300 outline-none">
<input type="text" placeholder="الخيار الثاني (الخاطئ)" class="w-full bg-saqel-card border border-saqel-border rounded-xl px-3 py-2 text-xs text-slate-300 outline-none">
</div>
<button class="mt-4 w-full py-2.5 bg-saqel-gold text-saqel-dark font-extrabold text-xs rounded-xl hover:opacity-90 transition">
حفظ الكويز داخل الفيديو ✓
</button>
</div>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="border-t border-saqel-border/40 py-6 text-center text-xs text-saqel-textMuted">
<div class="max-w-6xl mx-auto px-4 flex flex-col sm:flex-row items-center justify-between gap-3">
<span>منصة صَقِل التعليمية — نظام استوديو المعلمين © 2026</span>
<div class="flex items-center gap-4">
<a href="/student" class="hover:text-saqel-gold transition">بوابة الطلاب</a>
<span class="text-slate-700">•</span>
<span class="text-emerald-400">حماية المحتوى مشفرة 🔒</span>
</div>
</div>
</footer>
<!-- Alpine.js Application Logic -->
<script>
function teacherAuth() {
return {
isLoggedIn: false,
authStep: 'phone',
phone: '',
fullName: '',
otpCode: '',
phoneDisplay: '',
loading: false,
errorMessage: '',
successMessage: '',
timer: 0,
timerInterval: null,
deviceFingerprint: '',
teacherData: {},
async initApp() {
this.deviceFingerprint = await this.generateDeviceFingerprint();
const token = localStorage.getItem('saqel_teacher_jwt');
if (token) {
await this.fetchProfile(token);
}
},
async generateDeviceFingerprint() {
const raw = [
navigator.userAgent,
screen.width + 'x' + screen.height,
Intl.DateTimeFormat().resolvedOptions().timeZone
].join('###');
const msgUint8 = new TextEncoder().encode(raw);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
},
async sendOtp() {
this.loading = true;
this.errorMessage = '';
this.successMessage = '';
try {
const res = await fetch('/api/auth/otp/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
role: 'teacher',
full_name: this.fullName
})
});
const data = await res.json();
if (res.ok) {
this.authStep = 'otp';
this.phoneDisplay = data.data?.phone_masked || this.phone;
this.successMessage = data.message;
if (data.debug_otp) {
this.otpCode = data.debug_otp;
}
this.startTimer(60);
} else {
this.errorMessage = data.message || 'فشل إرسال رمز التحقق';
}
} catch (e) {
this.errorMessage = 'حدث خطأ في الاتصال بالخادم';
} finally {
this.loading = false;
}
},
async verifyOtp() {
this.loading = true;
this.errorMessage = '';
try {
const res = await fetch('/api/auth/otp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
otp: this.otpCode,
role: 'teacher',
full_name: this.fullName,
device_fingerprint: this.deviceFingerprint
})
});
const data = await res.json();
if (res.ok && data.data?.token) {
localStorage.setItem('saqel_teacher_jwt', data.data.token);
this.teacherData = data.data.user;
this.isLoggedIn = true;
this.successMessage = 'تم تسجيل الدخول بنجاح!';
} else {
this.errorMessage = data.message || 'رمز التحقق غير صحيح أو غير مصرح للمعلم';
}
} catch (e) {
this.errorMessage = 'حدث خطأ في التحقق من الرمز';
} finally {
this.loading = false;
}
},
async fetchProfile(token) {
try {
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await res.json();
if (res.ok && data.data && (data.data.role === 'teacher' || data.data.role === 'super_admin')) {
this.teacherData = {
name: data.data.full_name,
phone: data.data.phone_number,
role: data.data.role
};
this.isLoggedIn = true;
} else {
localStorage.removeItem('saqel_teacher_jwt');
this.isLoggedIn = false;
}
} catch (e) {
this.isLoggedIn = false;
}
},
logout() {
const token = localStorage.getItem('saqel_teacher_jwt');
if (token) {
fetch('/api/auth/logout', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token }
});
}
localStorage.removeItem('saqel_teacher_jwt');
this.isLoggedIn = false;
this.authStep = 'phone';
this.otpCode = '';
},
startTimer(seconds) {
this.timer = seconds;
clearInterval(this.timerInterval);
this.timerInterval = setInterval(() => {
if (this.timer > 0) {
this.timer--;
} else {
clearInterval(this.timerInterval);
}
}, 1000);
}
}
}
</script>
</body>
</html>
HTML;
}
}
+24 -4
View File
@@ -19,7 +19,22 @@ $router = new Router();
// 3. Define Global Middleware
$router->use(\App\Middlewares\SecurityMiddleware::class);
// 4. Define API Routes
// 4. Define Web and API Routes
// Root Redirect to Student Portal
$router->get('/', function ($request, $response) {
header('Location: /student');
exit;
});
// Web Portals (HTML + Alpine.js)
$router->get('/student', function ($request, $response) {
$response->html(\App\Views\StudentPortal::render());
});
$router->get('/teacher', function ($request, $response) {
$response->html(\App\Views\TeacherPortal::render());
});
// Health Check
$router->get('/api/health', function ($request, $response) {
@@ -31,12 +46,17 @@ $router->get('/api/health', function ($request, $response) {
]);
});
// Authentication Routes (Rate-limited: 5 attempts per 60 seconds per IP)
// OTP Authentication Routes (WhatsApp via Nabeh Gateway + Device Fingerprinting)
$router->post('/api/auth/otp/request', [\App\Controllers\AuthController::class, 'requestOtp'], [\App\Middlewares\RateLimitMiddleware::class]);
$router->post('/api/auth/otp/verify', [\App\Controllers\AuthController::class, 'verifyOtp'], [\App\Middlewares\RateLimitMiddleware::class]);
$router->post('/api/auth/logout', [\App\Controllers\AuthController::class, 'logout'], [\App\Middlewares\AuthMiddleware::class]);
$router->get('/api/auth/me', [\App\Controllers\AuthController::class, 'me'], [\App\Middlewares\AuthMiddleware::class]);
// Legacy / Direct Auth
$router->post('/api/auth/register', [\App\Controllers\AuthController::class, 'register'], [\App\Middlewares\RateLimitMiddleware::class]);
$router->post('/api/auth/login', [\App\Controllers\AuthController::class, 'login'], [\App\Middlewares\RateLimitMiddleware::class]);
$router->get('/api/auth/me', [\App\Controllers\AuthController::class, 'me'], [\App\Middlewares\AuthMiddleware::class]);
// Teacher Routes
// Teacher Studio Routes
$router->post('/api/teacher/courses', [\App\Controllers\TeacherController::class, 'addCourse'], [\App\Middlewares\AuthMiddleware::class]);
$router->post('/api/teacher/lessons', [\App\Controllers\TeacherController::class, 'addLesson'], [\App\Middlewares\AuthMiddleware::class]);