# Provider API Reference (Updated)

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

---

## 🆕 NEW FEATURES

### Roles & Permissions Management

> Provider admins can create and manage roles for their team members with granular permissions.

#### List Roles

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

Lists all roles created by this provider. Only roles with `type = 'provider'` and `provider_id` matching the authenticated provider are returned.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    {
      "id": 15,
      "name": "محرر المحتوى",
      "type": "provider",
      "provider_id": 42,
      "permissions_count": 5,
      "users_count": 2,
      "created_at": 1725198388,
      "updated_at": 1725284788
    }
  ],
  "links": {...},
  "meta": {...}
}
```

#### Create Role

**`POST /roles`** — 🔒 Protected

Creates a new provider role with selected permissions.

**Request:**
```json
{
  "name": "محرر المحتوى",
  "permissions": [12, 15, 23, 28, 31]
}
```

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

**Response:**
```json
{
  "status": "success", 
  "message": "Role created successfully",
  "data": {
    "id": 15,
    "name": "محرر المحتوى",
    "type": "provider",
    "provider_id": 42,
    "permissions": [
      {
        "id": 12,
        "name": "provider.service-orders.index",
        "display_name": "عرض الطلبات",
        "group": "Service Orders"
      }
    ],
    "created_at": 1725198388
  }
}
```

#### Show Role Details

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

Shows full role details with permissions list.

#### Update Role

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

Updates role name and/or permissions.

```json
{
  "name": "محرر المحتوى المحدث",
  "permissions": [12, 15, 23]
}
```

#### Delete Role

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

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

#### List Available Permissions

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

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

```json
{
  "status": "success",
  "message": "Data retrieved successfully", 
  "data": [
    {
      "group": "Service Orders",
      "permissions": [
        {
          "id": 12,
          "name": "provider.service-orders.index",
          "display_name": "عرض الطلبات"
        },
        {
          "id": 13, 
          "name": "provider.service-orders.show",
          "display_name": "تفاصيل الطلب"
        }
      ]
    },
    {
      "group": "Profile Management",
      "permissions": [
        {
          "id": 15,
          "name": "provider.profile.update", 
          "display_name": "تحديث الملف الشخصي"
        }
      ]
    }
  ]
}
```

### Provider Admin Management

> Main providers can create provider_admin accounts and assign roles to them.

#### List Provider Admins

**`GET /admins`** — 🔒 Protected (Main Provider Only)

Lists all provider_admin users under this provider.

```json
{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    {
      "id": 55,
      "full_name": "أحمد المساعد",
      "email": "ahmed.assistant@example.com",
      "phone": "512345679",
      "user_type": "provider_admin", 
      "parent_provider_id": 42,
      "roles": [
        {
          "id": 15,
          "name": "محرر المحتوى"
        }
      ],
      "is_active": true,
      "created_at": 1725198388
    }
  ]
}
```

#### Create Provider Admin

**`POST /admins`** — 🔒 Protected (Main Provider Only)

Creates a new provider_admin account linked to this provider.

**Request:**
```json
{
  "full_name": "أحمد المساعد",
  "email": "ahmed.assistant@example.com",
  "phone": "512345679",
  "password": "Secret@123",
  "password_confirmation": "Secret@123",
  "roles": [15, 18]
}
```

**Response:**
```json
{
  "status": "success",
  "message": "Provider admin created successfully", 
  "data": {
    "id": 55,
    "full_name": "أحمد المساعد",
    "email": "ahmed.assistant@example.com",
    "phone": "512345679",
    "user_type": "provider_admin",
    "parent_provider_id": 42,
    "roles": [...],
    "created_at": 1725198388
  }
}
```

#### Update Provider Admin

**`PUT /admins/{id}`** — 🔒 Protected (Main Provider Only)

Updates provider admin details and roles.

#### Delete Provider Admin

**`DELETE /admins/{id}`** — 🔒 Protected (Main Provider Only)

Soft deletes a provider admin account.

---

### Chat Integration with Orders

> Service orders now include chat integration for real-time communication between provider and client.

#### Order Chat Reference

When listing or showing orders, each order now includes a `chat_id` field that references the order's chat room:

```json
{
  "id": 1,
  "order_number": "ORD-1", 
  "status": "active",
  "chat_id": "chat_12345",
  "service_price": 400.00,
  "client_data": {...},
  "service_data": {...},
  "created_at": 1725379200
}
```

**Chat Integration:**
- Each service order automatically gets a chat room created
- `chat_id` is a unique identifier for the chat room
- Use this `chat_id` with your chat system to enable messaging
- Chat is available throughout the order lifecycle 
- Both provider and client can access the same chat room

**Usage Example:**
```javascript
// When user clicks on order to view details
const order = response.data;
const chatId = order.chat_id;

// Initialize chat interface
initializeChatRoom(chatId, {
  orderId: order.id,
  orderNumber: order.order_number,
  clientName: order.client_data.full_name
});
```

---

## Updated Service Orders

> Service Orders now include enhanced workflow with chat integration and improved status tracking.

### Enhanced Order Response

The order response now includes chat integration:

```json
{
  "id": 1,
  "order_number": "ORD-1",
  "status": "active", 
  "chat_id": "chat_order_1",
  
  "scheduled_date": "2026-09-15",
  "scheduled_time": "14:00",
  
  "form_data": [...],
  "service_price": 400.00,
  "work_files": [...],
  
  "client_data": {
    "id": 10,
    "full_name": "أحمد محمد", 
    "avatar": "https://..."
  },
  
  "service_data": {
    "id": 5,
    "title": "استشارة قانونية"
  },
  
  "paid_at": 1725379200,
  "accepted_at": null,
  "completed_at": null,
  "created_at": 1725379200
}
```

All existing service order endpoints remain the same but now return the additional `chat_id` field.

---

## Updated Urgent Orders 

> Urgent Orders now include enhanced communication features.

### Enhanced Urgent Order Response

```json
{
  "id": 1,
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "status": "searching_for_provider",
  "chat_id": "chat_urgent_1",
  "total_price": 500.00,
  
  "lat": 24.7136,
  "lng": 46.6753, 
  "location": "الرياض، المملكة العربية السعودية",
  "phone_number": "966512345678",
  
  "client_data": {
    "id": 10,
    "full_name": "أحمد محمد"
  },
  
  "emergency_authority": {
    "id": 1,
    "name": "الشرطة"
  },
  
  "emergency_case_type": {
    "id": 1, 
    "name": "قبض"
  },
  
  "description": "تم القبض على أخي في الرياض ونحتاج لمحامي بشكل عاجل",
  "created_at": 1725379200
}
```

---

## 🔔 Notifications

> Providers (and provider_admins) have their own notification inbox.  
> All endpoints use the shared `NotificationController` scoped to the authenticated user.

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

### Endpoint Summary

| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/notifications` | List own notifications (with category filter) |
| `GET` | `/notifications/{id}` | Show single notification (auto marks as read) |
| `PUT` | `/notifications/mark-all-read` | Mark all notifications as read |
| `PUT` | `/notifications/{id}` | Mark single notification as read |
| `DELETE` | `/notifications/clear-all` | Delete all notifications |
| `DELETE` | `/notifications/bulk-delete` | Delete multiple by IDs |
| `DELETE` | `/notifications/{id}` | Delete single notification |

---

### List Notifications

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

Lists all notifications for the authenticated provider, 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": 4,
  "data": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "created_at": 1725379200,
      "read_at": null,
      "is_readed": false,
      "created_time": "منذ 10 دقائق",
      "title": "طلب خدمة جديد",
      "body": "لديك طلب خدمة جديد ينتظر قبولك",
      "notify_id": 55,
      "notify_type": "orders",
      "sender_id": null
    },
    {
      "id": "660e8400-e29b-41d4-a716-446655440001",
      "created_at": 1725375600,
      "read_at": "2026-09-09 10:00 AM",
      "is_readed": true,
      "created_time": "منذ ساعة",
      "title": "تم استلام دفعة",
      "body": "تم إضافة 350 ريال إلى محفظتك",
      "notify_id": 88,
      "notify_type": "financial",
      "sender_id": null
    }
  ],
  "meta": { "current_page": 1, "last_page": 3, "per_page": 15, "total": 38 },
  "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 automatically 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,
    "created_time": "منذ 10 دقائق",
    "title": "طلب خدمة جديد",
    "body": "لديك طلب خدمة جديد ينتظر قبولك",
    "notify_id": 55,
    "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": 55 | null,
  "notify_type": "orders" | "financial" | "system",
  "sender_id": 456 | null
}
```

### Notification Categories for Providers

| Category | Examples |
|---|---|
| `orders` | New service order, offer accepted, order completed, order cancelled, revision requested |
| `financial` | Payment received, withdrawal approved/rejected, wallet balance updated, commission received |
| `system` | Account status changes, admin announcements, platform updates, chat messages, reviews received |

---