# Integrated Case Agreement & Policy Implementation

## Overview
This document outlines the implementation of an Agreement page specific to integrated case services. This page along with the existing Privacy Policy must be displayed to clients and providers and require acceptance before proceeding with integrated case orders.

---

## 1. New Page Type Added

### PageTypeEnum Updates

Added one new page type to `app/Enums/PageTypeEnum.php`:

```php
case IntegratedCaseAgreement = 'integrated_case_agreement'; // Agreement for integrated cases
```

**Note**: We use the existing `Privacy` page type for privacy policy, no need for a separate integrated case policy.

---

## 2. Admin Dashboard - Page Management

### Existing Pages CRUD

The admin dashboard already has a Pages CRUD system that supports:
- **Privacy Policy** (`privacy`)
- **About Us** (`about`)
- **Terms & Conditions** (`terms`)
- **Refund Policy** (`refund`)
- **Off Platform** (`off_platform`)
- **Urgent Order Info** (`urgent_order_info`)
- **Urgent Order Prior Agency** (`urgent_order_prior_agency`)
- **Urgent Order New Agency** (`urgent_order_new_agency`)

### Adding New Page

Admins can now create/manage the new page type:
- **Integrated Case Agreement** (`integrated_case_agreement`)

**Note**: The existing **Privacy Policy** (`privacy`) will be used for privacy concerns.

---

### Admin Endpoints

**Existing Pages API** (already implemented):

| Method | Endpoint | Description | Permission |
|--------|----------|-------------|------------|
| `GET` | `/api/v1/admin/pages` | List all pages | `pages.index` |
| `POST` | `/api/v1/admin/pages` | Create a new page | `pages.store` |
| `GET` | `/api/v1/admin/pages/{id}` | Get page details | `pages.show` |
| `PUT` | `/api/v1/admin/pages/{id}` | Update page | `pages.update` |
| `DELETE` | `/api/v1/admin/pages/{id}` | Delete page | `pages.destroy` |

---

### Create Integrated Case Agreement Page

**Request**: `POST /api/v1/admin/pages`

```json
{
  "type": "integrated_case_agreement",
  "ar": {
    "title": "اتفاقية القضايا المتكاملة",
    "desc": "<p>محتوى الاتفاقية باللغة العربية...</p><ul><li>البند الأول</li><li>البند الثاني</li></ul>"
  },
  "en": {
    "title": "Integrated Case Agreement",
    "desc": "<p>Agreement content in English...</p><ul><li>First clause</li><li>Second clause</li></ul>"
  },
  "image": 456
}
```

**Field Description:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `type` | `string` | Yes | Page type: `integrated_case_agreement` |
| `ar.title` | `string` | Yes | Arabic page title |
| `ar.desc` | `text` | Yes | Arabic page content (supports HTML) |
| `en.title` | `string` | Yes | English page title |
| `en.desc` | `text` | Yes | English page content (supports HTML) |
| `image` | `integer` | No | Optional image media ID |

---

### Fetch Privacy Policy (Existing)

Clients and providers also need to accept the existing privacy policy:

```http
GET /api/v1/client/pages/privacy
GET /api/v1/provider/pages/privacy
```

---

## 3. Client & Provider Access to Pages

### Fetching Static Pages

**Endpoint**: `GET /api/v1/{role}/pages/{type}`

Where `{role}` is:
- `client` - For client app/web
- `provider` - For provider app/web

---

### Examples:

#### Client Fetching Agreement:
```http
GET /api/v1/client/pages/integrated_case_agreement
```

#### Provider Fetching Privacy:
```http
GET /api/v1/provider/pages/privacy
```

#### Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Page retrieved successfully",
  "data": {
    "id": 12,
    "type": "integrated_case_agreement",
    "title": "Integrated Case Agreement | اتفاقية القضايا المتكاملة",
    "desc": "<p>Agreement content...</p>",
    "image": {
      "id": 456,
      "url": "https://cdn.example.com/pages/agreement-banner.jpg"
    },
    "created_at": 1726850400,
    "updated_at": 1726936800
  }
}
```

---

### All Available Page Types for Clients/Providers:

```http
GET /api/v1/client/pages/privacy
GET /api/v1/client/pages/about
GET /api/v1/client/pages/terms
GET /api/v1/client/pages/refund
GET /api/v1/client/pages/integrated_case_agreement

GET /api/v1/provider/pages/privacy
GET /api/v1/provider/pages/about
GET /api/v1/provider/pages/terms
GET /api/v1/provider/pages/refund
GET /api/v1/provider/pages/integrated_case_agreement
```

---

## 4. Integration with Integrated Case Flow

### When to Show Agreement & Privacy Policy

#### For Clients:
1. **Before Creating Integrated Case Order**
   - When client selects an integrated case service
   - Before payment screen
   - Display both Agreement and Privacy Policy
   - Client must check "I agree" checkboxes for both
   - Store acceptance in order

2. **Order Creation with Acceptance**

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

```json
{
  "service_id": 7,
  "provider_id": 123,
  "form_data": [...],
  "scheduled_date": "2026-09-25",
  "scheduled_time": "14:00",
  "integrated_case_agreement_accepted": true,
  "privacy_policy_accepted": true
}
```

**Validation:**
- If `service.is_integrated_case = true`:
  - `integrated_case_agreement_accepted` must be `true`
  - `integrated_case_policy_accepted` must be `true`
- If either is missing or false, return validation error

---

#### For Providers:
1. **Before Offering Integrated Case Service**
   - When provider selects integrated case service during registration
   - Before setting provider percentage
   - Display both Agreement and Privacy Policy
   - Provider must accept both before proceeding

2. **Provider Service Selection with Acceptance**

**Request**: `POST /api/provider/register` (during registration)

```json
{
  "services": [
    {
      "service_id": 7,
      "price": 2000.00,
      "provider_percentage": 10.5,
      "integrated_case_agreement_accepted": true,
      "integrated_case_policy_accepted": true
    }
  ]
}
```

**Validation:**
- If `service.is_integrated_case = true`:
  - `integrated_case_agreement_accepted` must be `true`
  - `integrated_case_policy_accepted` must be `true`
- If either is missing or false, return validation error

---

## 5. UI/UX Flow

### Client Order Creation Flow:

```
1. Client selects integrated case service
   ↓
2. Fills service order form
   ↓
3. Selects provider
   ↓
4. System detects is_integrated_case = true
   ↓
5. Display Agreement & Policy screens
   ┌────────────────────────────────┐
   │ Integrated Case Agreement      │
   │ ────────────────────────────── │
   │ [Agreement content here...]    │
   │                                │
   │ ☐ I have read and agree to     │
   │   the terms above              │
   │                                │
   │ [Continue]                     │
   └────────────────────────────────┘
   ↓
   ┌────────────────────────────────┐
   │ Integrated Case Policy         │
   │ ────────────────────────────── │
   │ [Policy content here...]       │
   │                                │
   │ ☐ I have read and agree to     │
   │   the policy above             │
   │                                │
   │ [Continue to Payment]          │
   └────────────────────────────────┘
   ↓
6. Proceed to payment
```

---

### Provider Service Selection Flow:

```
1. Provider selects integrated case service
   ↓
2. System detects is_integrated_case = true
   ↓
3. Display Agreement & Policy screens
   ┌────────────────────────────────┐
   │ Provider Agreement             │
   │ ────────────────────────────── │
   │ [Agreement content here...]    │
   │                                │
   │ ☐ I agree to provide services  │
   │   under these terms            │
   │                                │
   │ [Continue]                     │
   └────────────────────────────────┘
   ↓
   ┌────────────────────────────────┐
   │ Provider Policy                │
   │ ────────────────────────────── │
   │ [Policy content here...]       │
   │                                │
   │ ☐ I understand and accept      │
   │   this policy                  │
   │                                │
   │ [Continue]                     │
   └────────────────────────────────┘
   ↓
4. Set service price and provider percentage
```

---

## 6. Database Changes (if needed)

### Option 1: Store Acceptance in service_orders table

Add columns to `service_orders` table:

```php
Schema::table('service_orders', function (Blueprint $table) {
    $table->boolean('integrated_case_agreement_accepted')->default(false);
    $table->boolean('integrated_case_policy_accepted')->default(false);
    $table->timestamp('integrated_case_acceptance_at')->nullable();
});
```

### Option 2: Store Acceptance in provider_service pivot table

Add columns to `provider_service` table:

```php
Schema::table('provider_service', function (Blueprint $table) {
    $table->boolean('integrated_case_agreement_accepted')->default(false);
    $table->boolean('integrated_case_policy_accepted')->default(false);
    $table->timestamp('integrated_case_acceptance_at')->nullable();
});
```

---

## 7. Validation Rules

### Client Order Creation Validation:

```php
// In CreateServiceOrderRequest.php

public function rules(): array
{
    $service = Service::find($this->service_id);
    
    $rules = [
        'service_id' => ['required', 'exists:services,id'],
        'provider_id' => ['required', 'exists:users,id'],
        // ... other fields
    ];
    
    // For integrated cases, acceptance is required
    if ($service && $service->is_integrated_case) {
        $rules['integrated_case_agreement_accepted'] = ['required', 'accepted'];
        $rules['integrated_case_policy_accepted'] = ['required', 'accepted'];
    }
    
    return $rules;
}

public function messages(): array
{
    return [
        'integrated_case_agreement_accepted.required' => __('You must accept the integrated case agreement'),
        'integrated_case_agreement_accepted.accepted' => __('You must accept the integrated case agreement'),
        'integrated_case_policy_accepted.required' => __('You must accept the integrated case policy'),
        'integrated_case_policy_accepted.accepted' => __('You must accept the integrated case policy'),
    ];
}
```

---

### Provider Service Selection Validation:

```php
// In ProviderStep2Request.php or ProviderRegistrationRequest.php

public function rules(): array
{
    $rules = [
        'services' => ['required', 'array', 'min:1'],
        'services.*.service_id' => ['required', 'exists:services,id'],
        'services.*.price' => ['required', 'numeric', 'min:0'],
        // ... other fields
    ];
    
    // Validate integrated case acceptance
    foreach ($this->services ?? [] as $index => $serviceData) {
        $service = Service::find($serviceData['service_id'] ?? null);
        
        if ($service && $service->is_integrated_case) {
            $rules["services.{$index}.provider_percentage"] = ['required', 'numeric', 'min:0', 'max:100'];
            $rules["services.{$index}.integrated_case_agreement_accepted"] = ['required', 'accepted'];
            $rules["services.{$index}.integrated_case_policy_accepted"] = ['required', 'accepted'];
        }
    }
    
    return $rules;
}
```

---

## 8. Translation Keys

Add to `lang/ar.json` and `lang/en.json`:

```json
{
  "integrated_case_agreement": "اتفاقية القضايا المتكاملة | Integrated Case Agreement",
  "integrated_case_policy": "سياسة القضايا المتكاملة | Integrated Case Policy",
  "You must accept the integrated case agreement": "يجب عليك قبول اتفاقية القضايا المتكاملة",
  "You must accept the integrated case policy": "يجب عليك قبول سياسة القضايا المتكاملة",
  "Integrated case agreement and policy acceptance required": "مطلوب قبول اتفاقية وسياسة القضايا المتكاملة"
}
```

---

## 9. Implementation Checklist

### Backend:
- [x] Add new page types to `PageTypeEnum`
- [ ] Add translation keys for new page types
- [ ] Update `CreateServiceOrderRequest` validation for client acceptance
- [ ] Update provider registration request validation for provider acceptance
- [ ] Add database columns for storing acceptance (if needed)
- [ ] Update `ServiceOrderService::store()` to store acceptance
- [ ] Update `ProviderRegistrationService` to store acceptance

### Admin Dashboard:
- [ ] Create agreement page via Pages CRUD
- [ ] Create policy page via Pages CRUD
- [ ] Test page creation and updates
- [ ] Verify pages display correctly

### Client App:
- [ ] Fetch agreement page before order creation
- [ ] Fetch policy page before order creation
- [ ] Display agreement screen with checkbox
- [ ] Display policy screen with checkbox
- [ ] Send acceptance flags with order creation
- [ ] Handle validation errors for missing acceptance

### Provider App:
- [ ] Fetch agreement page during registration
- [ ] Fetch policy page during registration
- [ ] Display agreement screen with checkbox
- [ ] Display policy screen with checkbox
- [ ] Send acceptance flags with service selection
- [ ] Handle validation errors for missing acceptance

---

## 10. Testing Scenarios

### Scenario 1: Client Creates Integrated Case Order Without Acceptance

**Request:**
```json
POST /api/client/service-orders
{
  "service_id": 7,
  "provider_id": 123,
  "integrated_case_agreement_accepted": false
}
```

**Expected Response:**
```json
{
  "status": "error",
  "message": "Validation failed",
  "errors": {
    "integrated_case_agreement_accepted": [
      "You must accept the integrated case agreement"
    ]
  }
}
```

---

### Scenario 2: Client Creates Integrated Case Order With Acceptance

**Request:**
```json
POST /api/client/service-orders
{
  "service_id": 7,
  "provider_id": 123,
  "integrated_case_agreement_accepted": true,
  "integrated_case_policy_accepted": true
}
```

**Expected Response:**
```json
{
  "status": "success",
  "message": "Order created successfully",
  "data": {
    "id": "ORD-2026-0145",
    "status": "pending_payment",
    "integrated_case_agreement_accepted": true,
    "integrated_case_policy_accepted": true
  }
}
```

---

### Scenario 3: Provider Selects Integrated Case Without Acceptance

**Request:**
```json
POST /api/provider/register
{
  "services": [
    {
      "service_id": 7,
      "price": 2000.00,
      "provider_percentage": 10.5
    }
  ]
}
```

**Expected Response:**
```json
{
  "status": "error",
  "message": "Validation failed",
  "errors": {
    "services.0.integrated_case_agreement_accepted": [
      "You must accept the integrated case agreement"
    ],
    "services.0.integrated_case_policy_accepted": [
      "You must accept the integrated case policy"
    ]
  }
}
```

---

## 11. Summary

### What Was Added:
✅ Two new page types: `integrated_case_agreement` and `integrated_case_policy`  
✅ Admin can create/manage these pages via existing Pages CRUD  
✅ Clients can fetch these pages before creating integrated case orders  
✅ Providers can fetch these pages during registration  
✅ Validation enforces acceptance before proceeding  
✅ Acceptance is stored with orders and provider services  

### Key Points:
- **Agreement & Policy are REQUIRED** for integrated case services only
- **Both clients and providers** must accept before proceeding
- **Admin manages content** via the existing Pages CRUD
- **No new controllers needed** - uses existing Page management system
- **Bilingual support** - Arabic and English content
- **HTML content supported** - Rich text formatting allowed

---

## Conclusion

This implementation provides a complete agreement and policy system for integrated case services, ensuring legal compliance and user consent before proceeding with percentage-based payment transactions.
