user->role ?? 'viewer'; if (!in_array($currentUserRole, ['super_admin', 'admin'])) { Response::error('ليس لديك صلاحية لعرض المستخدمين', 'FORBIDDEN', 403); return; } try { $tenantId = $request->tenantId; $db = Database::getInstance(); $stmt = $db->prepare("SELECT id, name, email, role, is_active, created_at FROM users WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at DESC"); $stmt->execute([$tenantId]); $users = $stmt->fetchAll(); Response::json([ 'success' => true, 'data' => $users ]); } catch (Throwable $e) { Response::error('Failed to load users: ' . $e->getMessage(), 'USERS_FETCH_ERROR', 500); } } public function create(Request $request): void { $currentUserRole = $request->user->role ?? 'viewer'; $currentAssignedCompanyId = $request->user->assigned_company_id ?? null; if (!in_array($currentUserRole, ['super_admin', 'admin'])) { Response::error('ليس لديك صلاحية لإضافة مستخدمين', 'FORBIDDEN', 403); return; } $name = $request->input('name'); $email = $request->input('email'); $password = $request->input('password'); $role = $request->input('role', 'accountant'); $assignedCompanyId = $request->input('assigned_company_id'); // Admin can only create accountants and employees. Only super_admin can create admins. if ($currentUserRole === 'admin') { if (in_array($role, ['admin', 'super_admin'])) { Response::error('لا تملك الصلاحية لإضافة مدراء', 'FORBIDDEN', 403); return; } // Admin automatically assigns their own company to the new user $assignedCompanyId = $currentAssignedCompanyId; } // Validate valid roles $validRoles = ['super_admin', 'admin', 'accountant', 'employee', 'viewer']; if (!in_array($role, $validRoles)) { Response::error('صلاحية غير صالحة', 'VALIDATION_ERROR', 422); return; } if (!$name || !$email || !$password) { Response::error('الاسم والبريد وكلمة المرور مطلوبة', 'VALIDATION_ERROR', 422); return; } try { // Check if email exists if ($this->userModel->findByEmail($email)) { Response::error('البريد الإلكتروني مستخدم بالفعل', 'EMAIL_EXISTS', 409); return; } $userId = \Ramsey\Uuid\Uuid::uuid4()->toString(); $this->userModel->create([ 'id' => $userId, 'tenant_id' => $request->tenantId, 'name' => $name, 'email' => $email, 'password_hash' => password_hash($password, PASSWORD_BCRYPT), 'role' => $role, 'assigned_company_id' => $assignedCompanyId, 'is_active' => 1 ]); Response::json([ 'success' => true, 'message' => 'تم إنشاء المستخدم بنجاح', 'data' => ['id' => $userId] ]); } catch (Throwable $e) { Response::error($e->getMessage(), 'USER_CREATE_ERROR', 500); } } }