# Integrated Cases Feature Implementation Guide

## Overview
This document explains how integrated case services work, including audio file uploads, provider percentages, and the payment flow.

---

## 1. Audio File Upload for Service Forms

### How It Works
When a client creates a service order with form fields that have `field_type = 'file'`, they can upload ANY file type including audio.

### Upload Flow

#### Step 1: Mobile Uploads File
**Endpoint**: `POST /api/general/attachments`

**Request** (multipart/form-data):
```json
{
  "file": "<audio file>",           // The actual audio file
  "media_type": "audio",             // Type: image, video, audio, pdf, file
  "option": "dynamic_form_attachment", // Option identifier
  "model": null,                     // Leave null for unattached media
  "model_id": null                   // Leave null for unattached media
}
```

**Response**:
```json
{
  "data": {
    "id": 123,                       // THIS ID is what mobile sends in form_data
    "path": "https://example.com/storage/audio/file.mp3",
    "type": "audio",
    "option": "dynamic_form_attachment",
    "model": null,
    "model_id": null,
    "model_type": null,
    "is_single": false
  }
}
```

**Media Table Record Created**:
```php
[
  'id' => 123,
  'model_id' => null,                    // Not attached yet
  'model_type' => null,
  'is_attached' => false,
  'option' => 'dynamic_form_attachment',
  'uploaded_by' => <user_id>,
  'name' => 'audio_file_name.mp3',
  'type' => 'audio',                     // Detected from MIME type
  'path' => 'audio',                     // Directory
  'size' => 2048000,                     // In bytes
  'extension' => 'mp3',
  'duration' => 180,                     // For audio/video files (seconds)
  'metadata' => ['duration' => 180],     // Additional metadata
]
```

#### Step 2: Mobile Submits Service Order with Media ID

**Endpoint**: `POST /api/client/service-orders`

**Request**:
```json
{
  "service_id": 5,
  "provider_id": 10,
  "form_data": [
    {
      "field_key": "audio_recording",
      "answer": 123                  // The media ID from Step 1
    },
    {
      "field_key": "case_description",
      "answer": "Text description here"
    }
  ],
  "scheduled_date": "2026-09-25",
  "scheduled_time": "14:00"
}
```

#### Step 3: Backend Links Media to Order
The `attachMediaFromFormData()` method automatically:
- Scans all `form_data` for numeric values (media IDs)
- Updates those media records:
  ```php
  UPDATE media 
  SET model_id = <service_order_id>,
      model_type = 'App\Models\ServiceOrder',
      is_attached = true
  WHERE id IN (123) 
  AND model_id IS NULL
  ```

### Supported Audio Formats
- MP3 (.mp3)
- WAV (.wav)
- OGG (.ogg)
- AAC (.aac, .m4a)
- WEBM (.webm)
- FLAC (.flac)

**Max Size**: 25MB

---

## 2. Integrated Case Service Configuration

### Database Schema

#### `services` table:
```sql
is_integrated_case BOOLEAN DEFAULT false  -- Set by admin
```

#### `service_offers` table:
```sql
provider_percentage DECIMAL(5,2) NULL  -- e.g., 10.50 = 10.5%
```

#### `service_orders` table:
```sql
is_integrated_case BOOLEAN DEFAULT false              -- Copied from service
completion_amount DECIMAL(10,2) NULL                  -- Amount provider claims case ended with
provider_percentage DECIMAL(5,2) NULL                 -- Provider's agreed percentage
calculated_provider_payment DECIMAL(10,2) NULL        -- completion_amount * provider_percentage / 100
provider_completion_claimed_at TIMESTAMP NULL         -- When provider submitted completion amount
```

### Admin Dashboard - Service Configuration

**Endpoint**: `POST /api/dashboard/admin/services`

**Request**:
```json
{
  "ar": {"title": "خدمة قضايا متكاملة"},
  "en": {"title": "Integrated Case Service"},
  "subcategory_id": 3,
  "is_integrated_case": true,           // Enable integrated case feature
  "icon": 456,
  "is_active": true
}
```

---

## 3. Provider Offer Flow (with Percentage)

### Submitting Offer

**Endpoint**: `POST /api/provider/service-order-requests/{order_id}/offer`

**For Regular Services**:
```json
{
  "price": 1000.00,
  "duration_value": 7,
  "duration_unit": "days",
  "notes": "I can complete this work in 7 days"
}
```

**For Integrated Case Services** (provider_percentage is REQUIRED):
```json
{
  "price": 1000.00,
  "duration_value": 7,
  "duration_unit": "days",
  "provider_percentage": 10.5,       // REQUIRED for integrated cases
  "notes": "I will take 10.5% of the final case amount as مؤخر"
}
```

**Validation**:
- `provider_percentage` is REQUIRED only when `service.is_integrated_case = true`
- Range: 0 - 100
- Client sees this percentage in provider details

### When Client Accepts Offer
The order is created with:
```php
[
  'is_integrated_case' => true,              // Copied from service
  'provider_percentage' => 10.5,             // From accepted offer
  'status' => 'pending_payment',             // Standard flow
  'base_price' => 1000.00,                   // Initial price (for service fee)
  // calculated_provider_payment is NULL until provider finishes
]
```

---

## 4. Service Completion Flow (المؤخر Payment)

### Step 1: Provider Marks Order as Finished

**Endpoint**: `POST /api/provider/service-orders/{order_id}/finish`

**For Regular Services**:
```json
{
  "completion_note": "Work completed successfully"
}
```

**For Integrated Case Services** (completion_amount is REQUIRED):
```json
{
  "completion_amount": 50000.00,     // REQUIRED: Amount the case ended with
  "completion_note": "Case resolved successfully with 50,000 SAR settlement"
}
```

**Backend Calculation**:
```php
if ($order->is_integrated_case && $completionAmount > 0) {
    $calculatedPayment = ($completionAmount * $order->provider_percentage) / 100;
    
    $order->update([
        'status' => 'provider_finished',
        'completion_amount' => 50000.00,
        'calculated_provider_payment' => 5250.00,  // 50000 * 10.5 / 100
        'provider_completion_claimed_at' => now(),
    ]);
}
```

**IMPORTANT**: For integrated cases, auto-completion is **DISABLED**. Client MUST manually confirm.

### Step 2: Client Confirms & Pays المؤخر

**Endpoint**: `POST /api/client/service-orders/{order_id}/confirm`

**For Regular Services**:
- No payment required
- Provider gets paid from initial order payment

**For Integrated Case Services**:
- Client must pay `calculated_provider_payment` amount
- This is the المؤخر (deferred payment)

**Request**:
```json
{
  "completion_amount": 50000.00,      // Client confirms or adjusts the amount
  "payment_method": "wallet"          // Client pays the calculated amount
}
```

**Flow**:
1. Client sees: "Provider claims case ended with 50,000 SAR. You must pay 5,250 SAR (10.5%)"
2. Client confirms amount (or disputes it)
3. Client pays 5,250 SAR
4. Order status → `completed`
5. Provider receives the 5,250 SAR payment
6. Chat closes

---

## 5. Payment Calculation Differences

### Regular Service Flow:
```
Client pays upfront → Provider completes work → Provider gets paid from initial payment
```

### Integrated Case Flow:
```
Client pays initial fee (service charge) → 
Provider completes work → 
Provider claims completion amount → 
Client confirms & pays المؤخر (calculated_provider_payment) → 
Provider gets paid
```

### Example Calculation:

**Service Setup**:
- Service: `is_integrated_case = true`
- Provider offers: `provider_percentage = 10.5%`

**Initial Payment**:
- Base price: 1,000 SAR (service fee)
- VAT: 150 SAR
- App fee: 50 SAR
- **Client pays**: 1,200 SAR

**At Completion**:
- Provider claims: `completion_amount = 50,000 SAR`
- Calculated payment: `50,000 * 10.5% = 5,250 SAR`
- **Client must pay**: 5,250 SAR (المؤخر)
- **Provider receives**: 5,250 SAR (not the initial 1,000)

---

## 6. Key Differences from Regular Orders

| Feature | Regular Service | Integrated Case Service |
|---------|----------------|-------------------------|
| Provider percentage | Not used | Required in offer |
| Completion amount | Not used | Required when finishing |
| Auto-completion | Enabled (24 hours) | **DISABLED** |
| Client confirmation | Optional | **REQUIRED** |
| Payment at completion | No additional payment | Client pays المؤخر |
| Provider earnings | From initial payment | From completion payment |

---

## 7. Validation Rules Summary

### Service Creation (Admin):
- `is_integrated_case`: boolean, optional (default: false)

### Provider Offer:
- `provider_percentage`: 
  - Required when `service.is_integrated_case = true`
  - Range: 0-100
  - Decimal (5,2)

### Provider Finish Order:
- `completion_amount`:
  - Required when `order.is_integrated_case = true`
  - Numeric, min: 0
  - Decimal (10,2)

### Client Confirmation:
- For integrated cases: Payment of `calculated_provider_payment` is required
- Order cannot be completed without this payment

---

## 8. API Endpoints Modified

1. **Admin Services**: Added `is_integrated_case` field
   - `POST /api/dashboard/admin/services`
   - `PUT /api/dashboard/admin/services/{id}`

2. **Provider Offers**: Added `provider_percentage` validation
   - `POST /api/provider/service-order-requests/{id}/offer`

3. **Provider Finish**: Added `completion_amount` handling
   - `POST /api/provider/service-orders/{id}/finish`

4. **Client Confirm**: Modified to require payment for integrated cases
   - `POST /api/client/service-orders/{id}/confirm`

---

## 9. Migration Files Created

1. `2026_09_22_000001_add_is_integrated_case_to_services_table.php`
2. `2026_09_22_000002_add_integrated_case_fields_to_service_offers_table.php`
3. `2026_09_22_000003_add_integrated_case_completion_fields_to_service_orders_table.php`

**To run**: 
```bash
php artisan migrate
```

---

## 10. Frontend Display Guidelines

### Provider Details (for Client):
Show the provider_percentage prominently:
```
Provider: Ahmad Al-Salem
Experience: 5 years
Rating: 4.8 ⭐
Commission: 10.5% of case settlement amount (مؤخر)
```

### Order Completion Screen (for Client):
```
Provider completed the case
Claimed Settlement Amount: 50,000 SAR
Your Payment Due (10.5%): 5,250 SAR

[Confirm & Pay] [Dispute]
```

### Provider Finish Screen:
```
Enter the final settlement amount for this case:
Amount: [_______] SAR

Your commission (10.5%): Will be calculated automatically

[Mark as Finished]
```

---

## Implementation Complete ✅

All features are now implemented:
1. ✅ Slider CRUD with date filtering
2. ✅ Audio file support for service forms
3. ✅ Integrated case service flag (`is_integrated_case`)
4. ✅ Provider percentage in offers
5. ✅ Completion amount flow
6. ✅ Payment calculation for المؤخر
7. ✅ Disabled auto-completion for integrated cases
8. ✅ Required client confirmation with payment
