# Admin API Reference (Updated)

> Base URL: `{{base_url}}/api/v1/admin`  
> All protected routes require: `Authorization: Bearer {token}`  
> All requests/responses use `Content-Type: application/json`  
> Locale is controlled via `Accept-Language: ar` or `Accept-Language: en`

---

## 🆕 NEW FEATURES

### Roles & Permissions Management

> Super admins can create and manage admin roles with granular permissions. Each role is typed as 'admin' and can be assigned to admin users.

#### List Admin Roles

**`GET /roles`** — 🔒 Protected

Lists all admin roles. Only roles with `type = 'admin'` are returned.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    {
      "id": 5,
      "name": "مدير المحتوى",
      "type": "admin", 
      "provider_id": null,
      "permissions_count": 8,
      "users_count": 3,
      "created_at": 1725198388,
      "updated_at": 1725284788
    },
    {
      "id": 6,
      "name": "مشرف الطلبات",
      "type": "admin",
      "provider_id": null, 
      "permissions_count": 12,
      "users_count": 2,
      "created_at": 1725198500
    }
  ],
  "links": {...},
  "meta": {...}
}
```

#### Create Admin Role

**`POST /roles`** — 🔒 Protected (Super Admin Only)

Creates a new admin role with selected permissions.

**Request:**
```json
{
  "name": "مدير المحتوى",
  "permissions": [1, 3, 7, 12, 15, 18, 22, 25]
}
```

**Field Reference:**
| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | ✅ | Role name (3-255 chars) |
| `permissions` | array | ✅ | Array of permission IDs (admin permissions only) |

**Response:**
```json
{
  "status": "success",
  "message": "Role created successfully", 
  "data": {
    "id": 5,
    "name": "مدير المحتوى",
    "type": "admin",
    "provider_id": null,
    "permissions": [
      {
        "id": 1,
        "name": "admin.categories.index",
        "display_name": "عرض الفئات",
        "group": "Content Management"
      },
      {
        "id": 3,
        "name": "admin.categories.store", 
        "display_name": "إنشاء فئة",
        "group": "Content Management"
      }
    ],
    "created_at": 1725198388
  }
}
```

#### Show Role Details

**`GET /roles/{id}`** — 🔒 Protected

Shows full role details with permissions list.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": {
    "id": 5,
    "name": "مدير المحتوى",
    "type": "admin",
    "provider_id": null,
    "permissions": [
      {
        "id": 1,
        "name": "admin.categories.index",
        "display_name": "عرض الفئات", 
        "group": "Content Management"
      },
      {
        "id": 3,
        "name": "admin.categories.store",
        "display_name": "إنشاء فئة",
        "group": "Content Management" 
      }
    ],
    "users": [
      {
        "id": 12,
        "full_name": "أحمد المدير",
        "email": "ahmed@example.com"
      }
    ],
    "created_at": 1725198388,
    "updated_at": 1725284788
  }
}
```

#### Update Role

**`PUT /roles/{id}`** — 🔒 Protected (Super Admin Only)

Updates role name and/or permissions.

```json
{
  "name": "مدير المحتوى المحدث",
  "permissions": [1, 3, 7, 12, 18, 22]
}
```

#### Delete Role 

**`DELETE /roles/{id}`** — 🔒 Protected (Super Admin Only)

Deletes a role. Cannot delete if role is assigned to any users.

```json
{
  "status": "success",
  "message": "Role deleted successfully"
}
```

#### List Available Admin Permissions

**`GET /permissions`** — 🔒 Protected

Lists all permissions available to admin roles, grouped by functionality.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    {
      "group": "Content Management", 
      "permissions": [
        {
          "id": 1,
          "name": "admin.categories.index",
          "display_name": "عرض الفئات"
        },
        {
          "id": 2,
          "name": "admin.categories.show", 
          "display_name": "تفاصيل الفئة"
        },
        {
          "id": 3,
          "name": "admin.categories.store",
          "display_name": "إنشاء فئة"
        }
      ]
    },
    {
      "group": "User Management",
      "permissions": [
        {
          "id": 15,
          "name": "admin.clients.index",
          "display_name": "عرض العملاء"
        },
        {
          "id": 16,
          "name": "admin.clients.store", 
          "display_name": "إنشاء عميل"
        }
      ]
    },
    {
      "group": "Emergency Modules",
      "permissions": [
        {
          "id": 45,
          "name": "admin.emergency.authorities.index",
          "display_name": "عرض الجهات" 
        },
        {
          "id": 46,
          "name": "admin.emergency.case-types.index",
          "display_name": "عرض أنواع الحالات"
        }
      ]
    },
    {
      "group": "Ready Templates",
      "permissions": [
        {
          "id": 50,
          "name": "admin.ready-templates.index",
          "display_name": "عرض النماذج"
        },
        {
          "id": 51,
          "name": "admin.ready-templates.store",
          "display_name": "إنشاء نموذج"
        }
      ]
    }
  ]
}
```

### Admin Users Management

> Super admins can create and manage admin user accounts with role assignments.

#### List Admin Users

**`GET /admins`** — 🔒 Protected (Super Admin Only)

Lists all admin users in the system.

```json
{
  "status": "success", 
  "message": "Data retrieved successfully",
  "data": [
    {
      "id": 12,
      "full_name": "أحمد المدير",
      "email": "ahmed@example.com", 
      "user_type": "admin",
      "roles": [
        {
          "id": 5,
          "name": "مدير المحتوى"
        }
      ],
      "is_active": true,
      "is_admin_active": true,
      "last_login_at": 1725284788,
      "created_at": 1725198388
    }
  ],
  "links": {...},
  "meta": {...}
}
```

#### Create Admin User

**`POST /admins`** — 🔒 Protected (Super Admin Only)

Creates a new admin user account with role assignments.

**Request:**
```json
{
  "full_name": "أحمد المدير",
  "email": "ahmed@example.com",
  "password": "Secret@123",
  "password_confirmation": "Secret@123", 
  "roles": [5, 6],
  "locale": "ar",
  "allow_notifications": true
}
```

**Field Reference:**
| Field | Type | Required | Description |
|---|---|---|---|
| `full_name` | string | ✅ | Admin full name (3-100 chars) |
| `email` | string | ✅ | Unique email address |
| `password` | string | ✅ | Min 8 chars, requires confirmation |
| `password_confirmation` | string | ✅ | Must match password |
| `roles` | array | ❌ | Array of role IDs to assign |
| `locale` | string | ❌ | "ar" or "en" (default: "ar") |
| `allow_notifications` | boolean | ❌ | Default: true |

#### Update Admin User

**`PUT /admins/{id}`** — 🔒 Protected (Super Admin Only) 

Updates admin user details and roles.

```json
{
  "full_name": "أحمد المدير المحدث",
  "email": "ahmed.updated@example.com",
  "roles": [5],
  "locale": "en"
}
```

#### Delete Admin User

**`DELETE /admins/{id}`** — 🔒 Protected (Super Admin Only)

Soft deletes an admin user account.

#### Toggle Admin Status

**`PATCH /admins/{id}/status`** — 🔒 Protected (Super Admin Only)

Toggles `is_admin_active` status to activate/deactivate admin account.

---

### Cancel Reasons Management

> Manage predefined cancellation reasons that clients can select when cancelling orders.

#### List Cancel Reasons

**`GET /cancel-reasons`** — 🔒 Protected

Lists all cancellation reasons ordered by display order.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    {
      "id": 1,
      "is_active": true,
      "order": 1,
      "translations": {
        "ar": {
          "reason": "تغيير في المتطلبات"
        },
        "en": {
          "reason": "Change in requirements"
        }
      },
      "created_at": 1725198388,
      "updated_at": 1725284788
    },
    {
      "id": 2, 
      "is_active": true,
      "order": 2,
      "translations": {
        "ar": {
          "reason": "وجدت مقدم خدمة أفضل"
        },
        "en": {
          "reason": "Found a better service provider" 
        }
      },
      "created_at": 1725198500
    }
  ],
  "links": {...},
  "meta": {...}
}
```

#### Create Cancel Reason

**`POST /cancel-reasons`** — 🔒 Protected

Creates a new cancellation reason.

**Request:**
```json
{
  "order": 1,
  "is_active": true,
  "ar": {
    "reason": "تغيير في المتطلبات"
  },
  "en": {
    "reason": "Change in requirements"
  }
}
```

#### Show Cancel Reason

**`GET /cancel-reasons/{id}`** — 🔒 Protected

Shows single cancellation reason details.

#### Update Cancel Reason

**`PUT /cancel-reasons/{id}`** — 🔒 Protected

Updates cancellation reason.

```json
{
  "order": 2,
  "is_active": true,
  "ar": {
    "reason": "تغيير في المتطلبات المحدث"
  },
  "en": {
    "reason": "Updated change in requirements"
  }
}
```

#### Delete Cancel Reason

**`DELETE /cancel-reasons/{id}`** — 🔒 Protected

Deletes a cancellation reason.

#### Toggle Cancel Reason Status

**`PATCH /cancel-reasons/{id}/status`** — 🔒 Protected

Toggles `is_active` status.

---

### Enhanced Service Orders with Chat

> Service orders now include chat integration for real-time communication tracking.

#### Updated Order Response

When listing or showing orders, each order now includes a `chat_id` field:

```json
{
  "id": 1,
  "order_number": "NK-S0001",
  "status": "active",
  "chat_id": "chat_order_1",
  
  "service_price": 400.00,
  "total_price": 464.00,
  "vat_amount": 60.00,
  "app_fee_amount": 4.00,
  
  "client_data": {
    "id": 10,
    "full_name": "أحمد محمد",
    "email": "ahmed@example.com",
    "phone": "512345678"
  },
  
  "provider_data": {
    "id": 42,
    "full_name": "محمد المحامي", 
    "email": "mohammed@lawyer.com",
    "phone": "512345679"
  },
  
  "service_data": {
    "id": 5,
    "title": "استشارة قانونية"
  },
  
  "form_data": [...],
  "work_files": [...],
  
  "paid_at": 1725379200,
  "accepted_at": 1725379300,
  "started_at": 1725379500,
  "provider_finished_at": null,
  "completed_at": null,
  "created_at": 1725379200
}
```

#### Chat Integration Details

- Each service order automatically gets a chat room created
- `chat_id` is a unique identifier for the chat room  
- Chat enables real-time communication between admin, provider, and client
- Chat history is maintained throughout the order lifecycle
- Admins can monitor conversations for quality assurance

### Enhanced Urgent Orders with Chat

> Urgent orders also include chat integration for better communication tracking.

```json
{
  "id": 1,
  "order_number": "NK-U0001", 
  "status": "in_progress",
  "chat_id": "chat_urgent_1",
  
  "total_price": 500.00,
  "provider_id": 42,
  
  "client_data": {
    "id": 10,
    "full_name": "أحمد محمد"
  },
  
  "provider_data": {
    "id": 42,
    "full_name": "محمد المحامي"
  },
  
  "emergency_authority": {
    "id": 1,
    "name": "الشرطة"
  },
  
  "emergency_case_type": {
    "id": 1,
    "name": "قبض"  
  },
  
  "lat": 24.7136,
  "lng": 46.6753,
  "location": "الرياض، المملكة العربية السعودية",
  "phone_number": "966512345678",
  "description": "تم القبض على أخي في الرياض",
  
  "created_at": 1725379200,
  "accepted_at": 1725379300,
  "completed_at": null
}
```

---

## Updated Authentication & Profile

> Enhanced admin authentication with role-based permissions.

### Login Response

Login now includes role information:

```json
{
  "status": "success",
  "message": "Logged in successfully",
  "data": {
    "id": 1,
    "uuid": "...",
    "full_name": "أحمد المدير",
    "email": "ahmed@example.com", 
    "user_type": "admin",
    "locale": "ar",
    "allow_notifications": true,
    "is_active": true,
    "token": "eyJ...",
    
    "roles": [
      {
        "id": 5,
        "name": "مدير المحتوى",
        "permissions": [
          "admin.categories.index",
          "admin.categories.store", 
          "admin.services.index"
        ]
      }
    ],
    
    "permissions": [
      "admin.categories.index",
      "admin.categories.store",
      "admin.services.index"
    ],
    
    "last_login_at": 1725284788,
    "created_at": 1725198388
  }
}
```

**Permission System:**
- `roles` array contains all assigned roles with their permissions
- `permissions` is a flattened array of all permissions from all roles
- Use `permissions` array to check access in frontend
- Super admin automatically has all permissions (bypass)

---

## Permission Groups Reference

### Content Management
- `admin.categories.index` - عرض الفئات
- `admin.categories.show` - تفاصيل الفئة  
- `admin.categories.store` - إنشاء فئة
- `admin.categories.update` - تعديل فئة
- `admin.categories.destroy` - حذف فئة
- `admin.services.index` - عرض الخدمات
- `admin.services.store` - إنشاء خدمة
- `admin.services.update` - تعديل خدمة
- `admin.services.destroy` - حذف خدمة

### User Management  
- `admin.clients.index` - عرض العملاء
- `admin.clients.show` - تفاصيل العميل
- `admin.clients.store` - إنشاء عميل
- `admin.clients.update` - تعديل عميل
- `admin.clients.destroy` - حذف عميل
- `admin.providers.index` - عرض مقدمي الخدمات
- `admin.providers.show` - تفاصيل مقدم الخدمة
- `admin.provider-requests.index` - طلبات التسجيل
- `admin.provider-requests.accept` - قبول طلب التسجيل
- `admin.provider-requests.reject` - رفض طلب التسجيل

### Order Management
- `admin.service-orders.index` - عرض طلبات الخدمات
- `admin.service-orders.show` - تفاصيل الطلب
- `admin.urgent-orders.index` - عرض الطلبات العاجلة
- `admin.urgent-orders.show` - تفاصيل الطلب العاجل

### Emergency Modules
- `admin.emergency.authorities.index` - عرض الجهات
- `admin.emergency.authorities.store` - إنشاء جهة
- `admin.emergency.authorities.update` - تعديل جهة
- `admin.emergency.authorities.destroy` - حذف جهة
- `admin.emergency.case-types.index` - عرض أنواع الحالات
- `admin.emergency.case-types.store` - إنشاء نوع حالة
- `admin.emergency.case-types.update` - تعديل نوع حالة
- `admin.emergency.case-types.destroy` - حذف نوع حالة

### Ready Templates
- `admin.ready-templates.index` - عرض النماذج
- `admin.ready-templates.show` - تفاصيل النموذج
- `admin.ready-templates.store` - إنشاء نموذج
- `admin.ready-templates.update` - تعديل نموذج
- `admin.ready-templates.destroy` - حذف نموذج
- `admin.ready-templates.categories.index` - عرض فئات النماذج
- `admin.ready-templates.categories.store` - إنشاء فئة نماذج

### System Settings
- `admin.cancel-reasons.index` - عرض أسباب الإلغاء
- `admin.cancel-reasons.store` - إنشاء سبب إلغاء
- `admin.cancel-reasons.update` - تعديل سبب إلغاء
- `admin.cancel-reasons.destroy` - حذف سبب إلغاء

---

## Updated Existing Endpoints

> All existing admin endpoints remain the same but now support role-based access control.

### Provider Types, Languages, Regions

**All existing CRUD operations:**
- `GET /provider-types` - List provider types
- `POST /provider-types` - Create provider type  
- `PUT /provider-types/{id}` - Update provider type
- `DELETE /provider-types/{id}` - Delete provider type
- `PATCH /provider-types/{id}/status` - Toggle status

- `GET /languages` - List languages
- `POST /languages` - Create language
- `PUT /languages/{id}` - Update language 
- `DELETE /languages/{id}` - Delete language
- `PATCH /languages/{id}/status` - Toggle status

- `GET /regions` - List regions
- `GET /cities` - List cities
- `GET /districts` - List districts

### Categories & Services

**Enhanced with role permissions:**
- `GET /categories` - List categories
- `POST /categories` - Create category (requires: `admin.categories.store`)
- `PUT /categories/{id}` - Update category (requires: `admin.categories.update`)
- `DELETE /categories/{id}` - Delete category (requires: `admin.categories.destroy`)

- `GET /services` - List services
- `POST /services` - Create service (requires: `admin.services.store`)
- `PUT /services/{id}` - Update service (requires: `admin.services.update`)
- `DELETE /services/{id}` - Delete service (requires: `admin.services.destroy`)

### Client & Provider Management

**Enhanced with role permissions:**
- `GET /clients` - List clients (requires: `admin.clients.index`)
- `POST /clients` - Create client (requires: `admin.clients.store`)
- `PUT /clients/{id}` - Update client (requires: `admin.clients.update`)
- `DELETE /clients/{id}` - Delete client (requires: `admin.clients.destroy`)

- `GET /providers` - List providers (requires: `admin.providers.index`)
- `GET /providers/{id}` - Show provider (requires: `admin.providers.show`)
- `PUT /providers/{id}` - Update provider (requires: `admin.providers.update`)

### Provider Registration Requests

**Enhanced with role permissions:**
- `GET /provider-requests` - List requests (requires: `admin.provider-requests.index`)
- `GET /provider-requests/{id}` - Show request details
- `POST /provider-requests/{id}/accept` - Accept request (requires: `admin.provider-requests.accept`)
- `POST /provider-requests/{id}/reject` - Reject request (requires: `admin.provider-requests.reject`)

---

## Permission System Implementation

### Frontend Permission Checking

```javascript
// Check if user has specific permission
function hasPermission(permission) {
  const user = getCurrentUser();
  return user.permissions?.includes(permission) || user.user_type === 'super_admin';
}

// Example usage in components
if (hasPermission('admin.categories.store')) {
  // Show create category button
}

if (hasPermission('admin.clients.index')) {
  // Show clients menu item
}
```

### Role-based Menu System

```javascript
const menuItems = [
  {
    title: 'إدارة المحتوى',
    permission: 'admin.categories.index',
    submenu: [
      { title: 'الفئات', path: '/categories', permission: 'admin.categories.index' },
      { title: 'الخدمات', path: '/services', permission: 'admin.services.index' }
    ]
  },
  {
    title: 'إدارة المستخدمين', 
    permission: 'admin.clients.index',
    submenu: [
      { title: 'العملاء', path: '/clients', permission: 'admin.clients.index' },
      { title: 'مقدمو الخدمات', path: '/providers', permission: 'admin.providers.index' }
    ]
  },
  {
    title: 'الوحدات الطارئة',
    permission: 'admin.emergency.authorities.index', 
    submenu: [
      { title: 'الجهات', path: '/emergency/authorities', permission: 'admin.emergency.authorities.index' },
      { title: 'أنواع الحالات', path: '/emergency/case-types', permission: 'admin.emergency.case-types.index' }
    ]
  },
  {
    title: 'النماذج الجاهزة',
    permission: 'admin.ready-templates.index',
    submenu: [
      { title: 'النماذج', path: '/ready-templates', permission: 'admin.ready-templates.index' },
      { title: 'فئات النماذج', path: '/ready-templates/categories', permission: 'admin.ready-templates.categories.index' }
    ]
  }
];

// Filter menu items based on user permissions
const visibleMenuItems = menuItems.filter(item => 
  hasPermission(item.permission)
).map(item => ({
  ...item,
  submenu: item.submenu?.filter(subitem => hasPermission(subitem.permission))
}));
```

---

## 🔔 Notifications

> The admin has two notification roles:
> 1. **Sender** — push broadcast notifications to users (clients, providers, or specific targets)
> 2. **Receiver** — view and manage notifications the admin itself receives

---

### 📤 Admin Notification Sender (Broadcast)

Base prefix: `{{base_url}}/api/v1/admin/notifications`

#### List Sent Notifications

**`GET /notifications/sent`** — 🔒 Protected

Lists all notification groups previously sent/scheduled by admins, ordered by newest first.

**Query Parameters:**
| Parameter | Type | Description |
|---|---|---|
| `keyword` | string | Search by AR or EN title |
| `per_page` | integer | Items per page (default: 25) |

**Response:**
```json
{
  "status": "success",
  "message": "Notifications fetched",
  "data": [
    {
      "id": 1,
      "targeting_type": "all",
      "notifications_count": 1500,
      "release_at": "2026-09-10 10:00:00",
      "created_at": 1725198388,
      "content": {
        "ar": { "title": "إشعار مهم", "body": "نص الإشعار بالعربية" },
        "en": { "title": "Important Notice", "body": "Notification body in English" }
      }
    }
  ],
  "links": {...},
  "meta": {...}
}
```

---

#### Show Sent Notification Group

**`GET /notifications/sender/{sender}`** — 🔒 Protected

Returns details of a single sent notification group with delivery count.

**Response:**
```json
{
  "status": "success",
  "message": "Notification retrieved successfully",
  "data": {
    "id": 1,
    "targeting_type": "specific_clients",
    "targeting_ids": [10, 11, 12],
    "notifications_count": 3,
    "release_at": null,
    "created_at": 1725198388,
    "content": {
      "ar": { "title": "عرض خاص", "body": "استفد من العرض الحصري" },
      "en": { "title": "Special Offer", "body": "Benefit from the exclusive deal" }
    }
  }
}
```

---

#### Send Notification (Broadcast)

**`POST /notifications/send`** — 🔒 Protected

Creates and dispatches a notification to the selected audience. Supports immediate or scheduled delivery.

**Request Body:**
```json
{
  "content": {
    "ar": {
      "title": "عنوان الإشعار",
      "body": "نص الإشعار بالتفصيل"
    },
    "en": {
      "title": "Notification Title",
      "body": "Detailed notification body text"
    }
  },
  "type": "all",
  "ids": null,
  "release_at": null
}
```

**Field Reference:**
| Field | Type | Required | Description |
|---|---|---|---|
| `content` | object | ✅ | Bilingual content object |
| `content.ar.title` | string | ✅ | Arabic title (max 255 chars) |
| `content.ar.body` | string | ✅ | Arabic body (max 2000 chars) |
| `content.en.title` | string | ✅ | English title (max 255 chars) |
| `content.en.body` | string | ✅ | English body (max 2000 chars) |
| `type` | string | ✅ | Targeting type (see below) |
| `ids` | array | Conditional | Required when `type` is `specific_clients` or `specific_providers` |
| `release_at` | datetime | ❌ | Schedule future delivery (must be after now). Null = immediate |

**Targeting Types (`type`):**
| Value | Description |
|---|---|
| `all` | All active clients **and** providers |
| `clients` | All active clients only |
| `providers` | All active providers only |
| `specific_clients` | Specific clients — `ids` array required |
| `specific_providers` | Specific providers — `ids` array required |

**Immediate send example:**
```json
{
  "content": {
    "ar": { "title": "تحديث المنصة", "body": "تم تحديث المنصة بميزات جديدة" },
    "en": { "title": "Platform Update", "body": "Platform updated with new features" }
  },
  "type": "all"
}
```

**Scheduled send example:**
```json
{
  "content": {
    "ar": { "title": "تذكير", "body": "لا تنسَ إكمال ملفك الشخصي" },
    "en": { "title": "Reminder", "body": "Don't forget to complete your profile" }
  },
  "type": "providers",
  "release_at": "2026-09-15 08:00:00"
}
```

**Specific users example:**
```json
{
  "content": {
    "ar": { "title": "رسالة خاصة", "body": "مرحباً، لديك تحديث مهم" },
    "en": { "title": "Personal Message", "body": "Hello, you have an important update" }
  },
  "type": "specific_clients",
  "ids": [10, 11, 42]
}
```

**Response:**
```json
{
  "status": "success",
  "message": "Notification sent successfully"
}
```

---

#### Delete Sent Notification Group

**`DELETE /notifications/sender/{sender}`** — 🔒 Protected

Deletes a notification group (the broadcast record, not individual user notifications).

**Response:**
```json
{
  "status": "success",
  "message": "Notification deleted successfully"
}
```

---

### 📥 Admin Own Notifications (Received)

Base prefix: `{{base_url}}/api/v1/admin/notifications`

Admins can receive system notifications. The following endpoints manage the admin's own inbox.

#### List Admin Notifications

**`GET /notifications`** — 🔒 Protected

Lists all notifications received by the authenticated admin with optional category filtering.

**Query Parameters:**
| Parameter | Type | Description |
|---|---|---|
| `category` | string | `all` \| `orders` \| `financial` \| `system` (default: all) |
| `per_page` | integer | Items per page (1–100, default: 15) |

**Response:**
```json
{
  "status": "success",
  "message": "",
  "unread_count": 3,
  "data": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "created_at": 1725379200,
      "read_at": null,
      "is_readed": false,
      "created_time": "منذ ساعة",
      "title": "طلب جديد",
      "body": "تم تقديم طلب خدمة جديد يحتاج مراجعتك",
      "notify_id": 123,
      "notify_type": "orders",
      "sender_id": null
    }
  ],
  "meta": { "current_page": 1, "last_page": 2, "per_page": 15, "total": 20 },
  "links": { "first": "...", "last": "...", "prev": null, "next": "..." },
  "filter": {
    "current_category": "all",
    "available_categories": [
      { "value": "all", "label_ar": "الكل", "label_en": "All" },
      { "value": "orders", "label_ar": "الطلبات", "label_en": "Orders" },
      { "value": "financial", "label_ar": "المالية", "label_en": "Financial" },
      { "value": "system", "label_ar": "النظام", "label_en": "System" }
    ]
  }
}
```

---

#### Show Single Notification

**`GET /notifications/{notification_id}`** — 🔒 Protected

Returns a single notification and auto-marks it as read.

**Response:**
```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "created_at": 1725379200,
    "read_at": "2026-09-09 12:00 PM",
    "is_readed": true,
    "title": "طلب جديد",
    "body": "تم تقديم طلب خدمة جديد",
    "notify_id": 123,
    "notify_type": "orders",
    "sender_id": null
  }
}
```

---

#### Mark Single Notification as Read

**`PUT /notifications/{notification_id}`** — 🔒 Protected

**Response:**
```json
{ "status": "success", "message": "Notification marked as read" }
```

---

#### Mark All Notifications as Read

**`PUT /notifications/mark-all-read`** — 🔒 Protected

**Response:**
```json
{ "status": "success", "message": "All notifications marked as read" }
```

---

#### Delete Single Notification

**`DELETE /notifications/{notification_id}`** — 🔒 Protected

**Response:**
```json
{ "status": "success", "message": "Notification was deleted successfully" }
```

---

#### Bulk Delete Notifications

**`DELETE /notifications/bulk-delete`** — 🔒 Protected

**Request Body:**
```json
{ "ids": ["uuid-1", "uuid-2", "uuid-3"] }
```

**Response:**
```json
{ "status": "success", "message": "3 notifications were deleted successfully" }
```

---

#### Clear All Notifications

**`DELETE /notifications/clear-all`** — 🔒 Protected

**Response:**
```json
{ "status": "success", "message": "All notifications were deleted successfully" }
```

---

### Notification Object Structure

```json
{
  "id": "uuid",
  "created_at": 1725379200,
  "read_at": "2026-09-09 12:00 PM" | null,
  "is_readed": true | false,
  "created_time": "منذ ساعتين",
  "title": "Localized Title",
  "body": "Localized Body",
  "notify_id": 123 | null,
  "notify_type": "orders" | "financial" | "system",
  "sender_id": 456 | null
}
```

---

## Error Handling

### Permission Denied Response

When a user tries to access an endpoint without proper permissions:

```json
{
  "status": "fail",
  "message": "Access denied. You don't have permission to perform this action.",
  "data": {
    "required_permission": "admin.categories.store",
    "user_permissions": ["admin.categories.index", "admin.services.index"]
  }
}
```

### Role Assignment Validation

When creating/updating roles with invalid permissions:

```json
{
  "status": "fail", 
  "message": "Invalid permissions provided",
  "data": {
    "permissions": ["Permission IDs 45, 67 do not exist or are not admin permissions"]
  }
}
```

---

## Migration Notes

### Database Changes

1. **roles table**: Added `type` and `provider_id` columns
2. **users table**: Added `parent_provider_id` column for provider_admin linking
3. **New seeders**: ProviderPermissionSeeder with actual route permissions
4. **Updated seeders**: PermissionSeeder cleaned up obsolete permissions

### Backward Compatibility

- All existing API endpoints work unchanged
- New `chat_id` field added to order responses (non-breaking)
- Role system is additive - existing admins retain full access
- Super admin bypasses all permission checks automatically

### Required Frontend Updates

1. Update login handling to store user roles and permissions
2. Implement permission checking in menu/button visibility  
3. Add role management interface for super admins
4. Update order displays to include chat integration
5. Add cancel reasons management interface

---

## Testing Examples

### Role Creation Test

```bash
# Create admin role
curl -X POST {{base_url}}/api/v1/admin/roles \
-H "Authorization: Bearer {super_admin_token}" \
-H "Content-Type: application/json" \
-d '{
  "name": "مدير المحتوى",
  "permissions": [1, 3, 7, 12, 15]
}'
```

### Permission Check Test

```bash  
# Try accessing categories without permission (should fail)
curl -X GET {{base_url}}/api/v1/admin/categories \
-H "Authorization: Bearer {limited_admin_token}"

# Response: 403 Access Denied
```

### Admin User Creation Test

```bash
# Create admin with roles
curl -X POST {{base_url}}/api/v1/admin/admins \
-H "Authorization: Bearer {super_admin_token}" \
-H "Content-Type: application/json" \
-d '{
  "full_name": "أحمد المدير",
  "email": "ahmed@example.com", 
  "password": "Secret@123",
  "password_confirmation": "Secret@123",
  "roles": [5, 6]
}'
```

---

## Summary of New Features

### ✅ Roles & Permissions System
- Admin roles with granular permissions
- Provider roles with separate permission set
- Role-based access control on all endpoints  
- Super admin bypass for full system access

### ✅ Admin User Management  
- Create/update admin users with role assignments
- Toggle admin account activation status
- Role assignment validation and security

### ✅ Provider Admin Management
- Provider can create provider_admin accounts
- Link provider_admins to parent provider
- Role-based permissions for provider team members

### ✅ Cancel Reasons CRUD
- Manage predefined cancellation reasons
- Multilingual support (AR/EN)
- Order-based display control

### ✅ Enhanced Order Chat Integration  
- Auto-generated chat rooms for all orders
- `chat_id` field in order responses
- Real-time communication tracking
- Chat history maintenance

### ✅ Permission Seeders
- Provider permissions based on actual routes
- Admin permissions based on actual routes  
- Cleaned up obsolete permissions
- Proper permission grouping

This comprehensive update maintains backward compatibility while adding powerful new role-based access control and enhanced communication features.