# Admin Dashboard — Integration Notes & Changelog

---

## 1. Service Types — Complete Migration from Boolean Fields

### What Changed
**All services now rely fully on `service_type` enum instead of old boolean classification keys.**

### Old vs New Approach

**❌ OLD (deprecated):**
```php
'is_agency_service' => true,
'is_integrated_case' => false,
'is_nafath_required' => true,
// Multiple boolean flags
```

**✅ NEW (current):**
```php
'service_type' => 'agency'
// Single enum value drives all logic
```

### `ServiceContractTypeEnum` — Complete Values

| Value | Label | Description | Contract Features |
|---|---|---|---|
| `standard` | Standard Service | Regular service with dynamic form | Form data only |
| `integrated_case` | قضية متكاملة | Integrated case with provider percentage | Form data + completion amounts |
| `integrated_contract` | عقد متكامل | Contract with parties & attachment | Parties + contract file |
| `interactive_contract` | عقد تفاعلي | Multi-stage interactive contract | Parties + stages + confirmations |
| `agency` | Agency Service | Government agency service | Form data + special handling |

### Service Response Structure
**All service resources now consistently return:**
```json
{
  "service_type": "interactive_contract",
  "is_agency_service": false,     // Helper (computed)
  "is_integrated_case": false,    // Helper (computed)
  // service_type is the source of truth
}
```

### ⚠️ Service Creation & Dynamic Forms

**When creating or editing services in the admin panel:**

| Service Type | Dynamic Form Fields | Notes |
|---|---|---|
| `standard` | ✅ **Required** | Configure form fields for client input |
| `integrated_case` | ✅ **Required** | Configure form fields for client input |
| `agency` | ✅ **Required** | Configure form fields for client input |
| `integrated_contract` | ❌ **Do NOT configure** | Uses parties + contract file instead |
| `interactive_contract` | ❌ **Do NOT configure** | Uses parties + stages + contract file instead |

> **🚨 Important for Admin UI:**
> - When `service_type` is `integrated_contract` or `interactive_contract`:
>   - **Hide or disable** the "Form Fields" configuration section
>   - Show a warning: "Contract-based services do not use dynamic forms"
>   - These services use specialized contract mechanisms (parties, stages, attachments)
> - Form fields configured for contract types **will be ignored** by client apps

---

## 2. Service Orders — Enhanced Type-Driven Logic

### Service Type Location
**`service_type` is now consistently inside the `service_data` object:**
```json
{
  "service_data": {
    "id": 12,
    "title": "Legal Contract Service",
    "service_type": "integrated_contract",
    "image": "..."
  }
}
```

### Order Display Logic by Service Type

| `service_type` | Form Data | Parties | Stages | Contract File | Provider % |
|---|---|---|---|---|---|
| `standard` | ✅ | ❌ | ❌ | ❌ | ❌ |
| `integrated_case` | ✅ | ❌ | ❌ | ❌ | ✅ |
| `integrated_contract` | ❌ | ✅ | ❌ | ✅ | ❌ |
| `interactive_contract` | ❌ | ✅ | ✅ | ✅ | ❌ |
| `agency` | ✅ | ❌ | ❌ | ❌ | ❌ |

> **⚠️ Important:** `integrated_contract` and `interactive_contract` services **do NOT use dynamic forms**. These contract-based services use a specialized mechanism:
> - Clients submit **parties** (contract signatories) instead of form answers
> - A **contract file attachment** is required
> - Interactive contracts also include **stages** with party confirmations
> - When creating/editing these service types in admin, **do not configure form fields** — they will be ignored by the client apps.

### New Contract Fields

| Field | Description | Present When |
|---|---|---|
| `contract_terms` | Contract terms text (max 5000 chars) | All contract types |
| `parties_data` | Array of contract signatories | `integrated_contract`, `interactive_contract` |
| `stages_data` | Interactive contract stages | `interactive_contract` only |

---

## 3. Service Order Filtering

### Available Filters
Add these filter options to the admin service orders list:

| Filter | Parameter | Values | Description |
|---|---|---|---|
| **Service Type** | `filters[service_type]` | See enum values above | Filter by contract type |
| **Order Status** | `filters[status]` | `pending`, `active`, `completed`, etc. | Filter by order status |
| **Date Range** | `filters[date_from]`, `filters[date_to]` | `YYYY-MM-DD` | Filter by creation date |
| **Provider Type** | `filters[provider_type]` | `individual`, `team` | Filter by provider type |

### Service Type Filter Usage
```
GET /api/dashboard/admin/orders/service?filters[service_type]=integrated_contract
GET /api/dashboard/admin/orders/service?filters[service_type]=interactive_contract
```

---

## 4. Categories & Questions — Separate CRUD System

### What Changed
- **Question management has been completely separated from category management**
- Categories and questions are now independent CRUD operations
- Questions can only be added to parent (main-level) categories

### Categories CRUD
**Standard category management without questions embedded**

### Category Questions CRUD

#### Endpoints Structure
```
GET    /categories/{category}/questions          # List questions
POST   /categories/{category}/questions          # Create question
GET    /categories/{category}/questions/{question} # Show question
PUT    /categories/{category}/questions/{question} # Update question
DELETE /categories/{category}/questions/{question} # Delete question
PATCH  /categories/{category}/questions/{question}/status # Toggle status
```

#### Question Response Structure
```json
{
  "id": 1,
  "category": {
    "id": 5,
    "name": "Legal Services",
    "level": 0
  },
  "translations": {
    "ar": { "question": "ما هو نوع العقد المطلوب؟" },
    "en": { "question": "What type of contract is required?" }
  },
  "options": [
    {
      "id": 1,
      "order": 1,
      "is_correct": true,
      "is_active": true,
      "translations": {
        "ar": { "answer": "عقد عمل" },
        "en": { "answer": "Employment Contract" }
      }
    }
  ],
  "order": 1,
  "is_active": true
}
```

### Category Question Options CRUD

#### Endpoints Structure
```
GET    /category-questions/{question}/options          # List options
POST   /category-questions/{question}/options          # Create option
PUT    /category-questions/{question}/options/{option} # Update option
DELETE /category-questions/{question}/options/{option} # Delete option
PATCH  /category-questions/{question}/options/{option}/status # Toggle status
```

#### Validation Rules
- **Questions:** Minimum 2 options, exactly 1 correct option
- **Options:** Must belong to parent question
- **Translations:** Required for both Arabic and English
- **Unique Questions:** Question text must be unique per category + locale

---

## 5. Categories Lookup — Exam Filter

**Endpoint:** `GET /api/general/lookup/categories`

### Enhanced Filtering
| Parameter | Type | Description |
|---|---|---|
| `has_exam` | `boolean` | Only categories with ≥20 active questions |
| `level` | `integer` | Filter by category level (0=parent, 1=child) |
| `parent_id` | `integer` | Filter by parent category |

### Exam Requirements
When `has_exam=1`:
- Category must have **≥20 active questions**
- Each question must have **≥2 active options**
- Each question must have **exactly 1 correct option**

```
GET /api/general/lookup/categories?has_exam=1&level=0
```

---

## 6. Interactive Contract — Party Confirmations

### Party Confirmation Endpoints

#### Stage Confirmation Flow
```
POST /client/orders/service/{id}/stages/{stage}/party-confirm  # Party confirms stage
POST /client/orders/service/{id}/stages/{stage}/client-confirm # Client confirms stage
```

### Access Control
- **Party Confirm:** Must be listed in `service_order_parties` table
- **Client Confirm:** Must be the order's main client (`order.client_id`)
- **Stage Requirements:** Previous stages must be client-confirmed

### Confirmation Data Structure
```json
{
  "stages_data": [
    {
      "id": 1,
      "name": "Initial Planning",
      "end_date": "2024-12-31",
      "amount": 5000.00,
      "order": 1,
      "is_completed": false,
      "client_confirmed_at": null,
      "party_confirmations": [
        {
          "id": 15,
          "full_name": "Ahmed Mohamed",
          "confirmed_at": 1672531200
        }
      ]
    }
  ]
}
```

---

## 7. Static Pages — New Contract Terms Page

### New Page Type Added
```php
case IntegratedContractTerms = 'integrated_contract_terms'; // بنود عقد متكامل
```

### Complete Page Types

| Case | Value | Admin Label |
|---|---|---|
| `Privacy` | `privacy` | Privacy Policy |
| `About` | `about` | About Us |
| `Terms` | `terms` | Terms & Conditions |
| `Refund` | `refund` | Refund Policy |
| `OffPlatform` | `off_platform` | Off-Platform Services |
| `UrgentOrderInfo` | `urgent_order_info` | Urgent Order Information |
| `UrgentOrderPrior` | `urgent_order_prior_agency` | Prior Agency Services |
| `UrgentOrderNew` | `urgent_order_new_agency` | New Agency Services |
| `IntegratedCaseAgreement` | `integrated_case_agreement` | Integrated Case Agreement |
| **`IntegratedContractTerms`** | **`integrated_contract_terms`** | **Contract Terms & Conditions** |

---

## 8. Contract Order Validation

### Phone Validation Enhancement
For `integrated_contract` and `interactive_contract` orders:
- **Phone codes** must be valid country codes
- **Phone numbers** must match country-specific length requirements
- Uses `PhoneValidationService` for strict validation

### Contract Terms
- New `contract_terms` field (nullable, max 5000 characters)
- Returned in all service order resources
- Available for all service types (not just contracts)

---

## Migration Notes

### For Frontend Developers
1. **Replace all boolean service type checks with `service_type` enum comparisons**
2. **Use `service_data.service_type` instead of root-level checks**
3. **Implement separate question/option management screens**
4. **Add service type filtering to order lists**
5. **Handle party confirmation flows for interactive contracts**

### For API Consumers
1. **`service_type` is the single source of truth for service classification**
2. **Old boolean helpers remain for backwards compatibility but are computed**
3. **Contract-specific fields are only present for relevant service types**
4. **Questions and categories are separate resources with independent CRUDs**


---

## 9. Chat System — Attachment Support

### Overview
Messages can now include attachments (images, audio files, documents) in addition to or instead of text.

### Attachment Upload Flow
**Step 1:** Upload file to media endpoint
```http
POST /api/general/attachments
Content-Type: multipart/form-data

{
  "file": <binary>,
  "media_type": "image",        // or "audio", "file"
  "model": "Message",
  "model_id": null,              // null for unattached upload
  "option": "chat_attachment",
  "is_single": false
}
```

**Response:**
```json
{
  "id": 123,
  "url": "https://example.com/storage/images/filename.jpg",
  "type": "image",
  "option": "chat_attachment",
  "is_single": false
}
```

**Step 2:** Send message with attachment
```http
POST /dashboard/chats/{chat}/messages

{
  "message": "Optional text message",   // nullable
  "attachment_id": 123                  // nullable
}
```

### Validation Rules
- At least one of `message` or `attachment_id` is required
- Cannot send empty message without attachment
- `attachment_id` must reference valid media record
- Supported types: `image`, `audio`, `file`

### Chat List Response (with attachment indicators)
```json
{
  "id": 1,
  "unread_count": 3,
  "latest_message": {
    "id": 456,
    "message": "Check this file",
    "created_at": 1672531200,
    "has_attachment": true,
    "attachment_type": "image"    // or "audio", "file"
  }
}
```

### Message Detail Response
```json
{
  "id": 456,
  "message": "Check this file",
  "sender_data": {
    "id": 789,
    "full_name": "Ahmed Mohamed"
  },
  "created_at": 1672531200,
  "read_at": 1672535000,
 "attachment_data": {
                "url": "http://127.0.0.1:8000/storage/files/59a9cd6f-d37c-4d8b-8fe1-532eb500ee33.pdf",
                "type": "file"
            }
}
```

> **`message_type` values:** `text` (no attachment) · `image` · `audio` · `file`

### Attachment Types

| Type | Description | Common Extensions |
|---|---|---|
| `image` | Image files | jpg, png, gif, webp |
| `audio` | Audio files | mp3, wav, m4a, ogg |
| `file` | Documents and other files | pdf, docx, xlsx, zip, etc. |

### Admin Chat Endpoints

**List all chats:**
```http
GET /dashboard/chats?per_page=15&user_id={optional}&keyword={optional}
```

**View chat messages:**
```http
GET /dashboard/chats/{chat}?per_page=20
```

### Notes
- Messages can have text only, attachment only, or both
- `attachment_data` is `null` if no attachment
- Attachment type is determined from media table, not stored separately
- Chat list shows `has_attachment` and `attachment_type` in latest message for quick UI indicators

