# جدول المستخدمين - شرح شامل

## 📋 هيكل جدول Users

```
┌─────────────────────────────────────────────────────────────┐
│                        جدول المستخدمين                       │
├─────────────────┬──────────────────┬────────────────────────┤
│     الحقل       │      النوع       │       الوصف             │
├─────────────────┼──────────────────┼────────────────────────┤
│ id              │ INTEGER PK       │ معرّف فريد تلقائي       │
│ username        │ TEXT UNIQUE      │ اسم المستخدم (فريد)     │
│ password        │ TEXT             │ كلمة السر              │
│ name            │ TEXT NOT NULL    │ الاسم الكامل           │
│ email           │ TEXT             │ البريد الإلكتروني       │
│ role            │ TEXT DEFAULT     │ الدور (admin/user)     │
│ status          │ BOOLEAN DEFAULT  │ الحالة (1=نشط/0=غير)   │
│ last_login      │ DATETIME         │ آخر دخول              │
│ created_at      │ DATETIME DEFAULT │ تاريخ الإنشاء          │
│ updated_at      │ DATETIME DEFAULT │ تاريخ آخر تعديل        │
└─────────────────┴──────────────────┴────────────────────────┘
```

---

## 🔌 API Routes

### 1. الحصول على جميع المستخدمين

**الطلب:**
```http
GET /api/users
```

**الرد:**
```json
[
  {
    "id": 1,
    "username": "admin",
    "name": "مدير النظام",
    "email": "admin@example.com",
    "role": "admin",
    "status": 1,
    "last_login": "2026-01-10T14:30:00Z",
    "created_at": "2026-01-01T10:00:00Z"
  },
  {
    "id": 2,
    "username": "user1",
    "name": "أحمد محمد",
    "email": "ahmed@example.com",
    "role": "user",
    "status": 1,
    "last_login": "2026-01-10T12:00:00Z",
    "created_at": "2026-01-02T11:00:00Z"
  }
]
```

---

### 2. الحصول على مستخدم معين

**الطلب:**
```http
GET /api/users/1
```

**الرد:**
```json
{
  "id": 1,
  "username": "admin",
  "name": "مدير النظام",
  "email": "admin@example.com",
  "role": "admin",
  "status": 1,
  "last_login": "2026-01-10T14:30:00Z",
  "created_at": "2026-01-01T10:00:00Z"
}
```

---

### 3. إضافة مستخدم جديد

**الطلب:**
```http
POST /api/users
Content-Type: application/json

{
  "username": "user2",
  "password": "password123",
  "name": "محمد علي",
  "email": "mohammad@example.com",
  "role": "user",
  "status": true
}
```

**الرد:**
```json
{
  "id": 3,
  "username": "user2",
  "name": "محمد علي",
  "email": "mohammad@example.com",
  "role": "user",
  "status": 1
}
```

---

### 4. تعديل مستخدم

**الطلب:**
```http
PUT /api/users/2
Content-Type: application/json

{
  "username": "user1_updated",
  "password": "newpassword456",
  "name": "أحمد محمد محسن",
  "email": "ahmed.new@example.com",
  "role": "admin",
  "status": true
}
```

**الرد:**
```json
{
  "id": 2,
  "username": "user1_updated",
  "password": "newpassword456",
  "name": "أحمد محمد محسن",
  "email": "ahmed.new@example.com",
  "role": "admin",
  "status": 1
}
```

---

### 5. حذف مستخدم

**الطلب:**
```http
DELETE /api/users/3
```

**الرد:**
```json
{
  "success": true
}
```

---

### 6. تسجيل الدخول (Login)

**الطلب:**
```http
POST /api/users/login
Content-Type: application/json

{
  "username": "admin",
  "password": "password123"
}
```

**الرد (نجح):**
```json
{
  "id": 1,
  "username": "admin",
  "name": "مدير النظام",
  "email": "admin@example.com",
  "role": "admin",
  "status": 1
}
```

**الرد (فشل):**
```json
{
  "error": "بيانات دخول خاطئة"
}
```

---

### 7. تحديث آخر دخول

**الطلب:**
```http
PUT /api/users/1/login
```

**الرد:**
```json
{
  "success": true,
  "message": "تم تحديث آخر دخول"
}
```

---

## 💻 أمثلة استخدام JavaScript

### إضافة مستخدم جديد

```javascript
async function addUser() {
  const response = await fetch('http://localhost:3000/api/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: 'newuser',
      password: 'password123',
      name: 'اسم المستخدم',
      email: 'user@example.com',
      role: 'user',
      status: true
    })
  });

  const data = await response.json();
  console.log('تم الإضافة:', data);
}
```

### الحصول على جميع المستخدمين

```javascript
async function getUsers() {
  const response = await fetch('http://localhost:3000/api/users');
  const users = await response.json();
  console.log('المستخدمين:', users);
}
```

### تسجيل الدخول

```javascript
async function login(username, password) {
  const response = await fetch('http://localhost:3000/api/users/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: username,
      password: password
    })
  });

  const data = await response.json();
  if (response.ok) {
    console.log('تسجيل دخول ناجح:', data);
    localStorage.setItem('user', JSON.stringify(data));
  } else {
    console.error('فشل تسجيل الدخول:', data.error);
  }
}
```

### تعديل مستخدم

```javascript
async function updateUser(id, userData) {
  const response = await fetch(`http://localhost:3000/api/users/${id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData)
  });

  const data = await response.json();
  console.log('تم التحديث:', data);
}
```

### حذف مستخدم

```javascript
async function deleteUser(id) {
  const response = await fetch(`http://localhost:3000/api/users/${id}`, {
    method: 'DELETE'
  });

  const data = await response.json();
  console.log('تم الحذف:', data);
}
```

---

## 🛡️ أفضل الممارسات الأمنية

### ⚠️ ملاحظات أمان مهمة:

1. **تشفير كلمة السر:**
   ```javascript
   // استخدم bcrypt لتشفير كلمة السر (مثال)
   const bcrypt = require('bcrypt');
   const hashedPassword = await bcrypt.hash(password, 10);
   ```

2. **التحقق من التصاريح:**
   - تحقق من `role` المستخدم قبل السماح بعمليات معينة
   - استخدم middleware للتحقق من الدخول

3. **عدم إرسال كلمة السر:**
   - لا تُرسل كلمة السر في الرد (تم تطبيقه في GET)

4. **استخدام JWT Tokens:**
   ```javascript
   // مثال على JWT
   const jwt = require('jsonwebtoken');
   const token = jwt.sign(
     { userId: user.id, role: user.role },
     'secret_key',
     { expiresIn: '24h' }
   );
   ```

5. **معالجة الجلسات:**
   - احفظ معلومات المستخدم في JWT أو Session
   - أنهِ الجلسة عند تسجيل الخروج

---

## 📝 أمثلة مستقدمة

### البحث عن مستخدم

```javascript
async function searchUser(username) {
  const response = await fetch('http://localhost:3000/api/users');
  const users = await response.json();
  const user = users.find(u => u.username === username);
  return user;
}
```

### إنشاء عدة مستخدمين

```javascript
async function createMultipleUsers() {
  const users = [
    { username: 'user1', password: 'pass1', name: 'مستخدم 1' },
    { username: 'user2', password: 'pass2', name: 'مستخدم 2' },
    { username: 'user3', password: 'pass3', name: 'مستخدم 3' }
  ];

  for (const user of users) {
    await fetch('http://localhost:3000/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(user)
    });
  }
}
```

### تعطيل مستخدم

```javascript
async function deactivateUser(id) {
  const response = await fetch(`http://localhost:3000/api/users/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ status: false })
  });
  
  const data = await response.json();
  console.log('تم تعطيل المستخدم:', data);
}
```

---

## 🧪 اختبار باستخدام cURL

```bash
# الحصول على جميع المستخدمين
curl http://localhost:3000/api/users

# إضافة مستخدم جديد
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "password": "test123",
    "name": "مستخدم اختبار",
    "email": "test@example.com"
  }'

# تسجيل دخول
curl -X POST http://localhost:3000/api/users/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "password123"
  }'

# تعديل مستخدم
curl -X PUT http://localhost:3000/api/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "مدير النظام الجديد"}'

# حذف مستخدم
curl -X DELETE http://localhost:3000/api/users/3
```

---

## 📊 إحصائيات وتقارير

### عدد المستخدمين النشطين

```javascript
async function getActiveUsersCount() {
  const users = await fetch('http://localhost:3000/api/users')
    .then(r => r.json());
  return users.filter(u => u.status === 1).length;
}
```

### آخر المستخدمين المضافين

```javascript
async function getRecentUsers(limit = 5) {
  const users = await fetch('http://localhost:3000/api/users')
    .then(r => r.json());
  return users.slice(0, limit);
}
```

---

## ✨ الخطوات التالية

1. ✅ جدول المستخدمين تم إنشاؤه
2. ✅ API Routes تم إضافتها
3. ⏭️ أضفِ تشفير كلمة السر (bcrypt)
4. ⏭️ أضفِ نظام JWT للتحقق من الجلسات
5. ⏭️ أنشئ واجهة تسجيل دخول

---

**تم الإنشاء بنجاح! النظام جاهز للاستخدام** ✅
