# Service Order Lifecycle & Golden Guarantee Implementation

## Complete Implementation Summary

---

## ✅ **1. Service Order Lifecycle (Normal Orders)**

### **Status Flow:**
```
pending (paid) 
  ↓
accepted (provider accepted)
  ↓
active (provider started work) ← [can loop back if redo needed]
  ↓
provider_finished (رفع المخرجات - outputs uploaded)
  ↓
[Client has 3 options]:
  1. Confirm → completed (provider gets paid)
  2. File Golden Guarantee → pending_admin_review
  3. Do nothing → auto-complete after 24h → completed
```

### **Provider Endpoints:**
- `GET /provider/service-orders` - Unified list (all statuses, filterable)
- `GET /provider/service-orders/{id}` - Show details
- `POST /provider/service-orders/{id}/accept` - Accept order
- `POST /provider/service-orders/{id}/reject` - Reject order (client refunded)
- `POST /provider/service-orders/{id}/start` - Start work (`active` status)
- `POST /provider/service-orders/{id}/upload-files` - Upload work files (can call multiple times)
- `POST /provider/service-orders/{id}/finish` - Mark as finished (`provider_finished`)

### **Client Endpoints:**
- `POST /client/orders/service` - Create and pay for order
- `GET /client/orders/service` - List orders
- `GET /client/orders/service/{id}` - Show order
- `PATCH /client/orders/service/{id}/cancel` - Cancel (only before `active`)
- `POST /client/orders/service/{id}/confirm` - Confirm completion (provider gets paid)
- `POST /client/orders/service/{id}/golden-guarantee` - File complaint

---

## ✅ **2. Golden Guarantee System (Service Orders ONLY)**

### **Purpose:**
Quality control - client can complain if unsatisfied with work. Admin reviews and decides.

### **Form Fields:**
- **Reason** (required): `output_not_meeting_specs`, `delivery_delay`, `error_in_output`, `incomplete_service`, `other`
- **Description** (required): Detailed problem description (min 10 chars)
- **Attachments** (optional): Up to 5 supporting files (images/PDF)

### **Admin Endpoints:**
- `GET /dashboard/golden-guarantee` - List all pending reviews
- `GET /dashboard/golden-guarantee/{order}` - Show complaint details
- `POST /dashboard/golden-guarantee/{order}/approve` - Approve complaint:
  - Order goes back to `active`
  - Provider must redo work
  - `redo_count` incremented
- `POST /dashboard/golden-guarantee/{order}/reject` - Reject complaint:
  - Order becomes `completed`
  - Provider gets paid

### **Database Fields:**
- `golden_guarantee_reason`
- `golden_guarantee_description`
- `golden_guarantee_filed_at`
- `admin_review_notes`
- `admin_reviewed_at`
- `reviewed_by_admin_id`
- `redo_count`

---

## ✅ **3. Urgent Order Retry & Refund System**

### **Settings (Dashboard):**
- `urgent_order_retry_interval_minutes` = 5 (retry every 5 minutes)
- `urgent_order_max_retries` = 3 (max 3 retries)
- `urgent_order_cancel_after_minutes` = 30 (absolute timeout)

### **Flow:**
1. Order created → Dispatched to nearby providers
2. If no acceptance after 5 minutes → **Retry #1**:
   - Reset ALL providers to `pending` (ignore previous rejections)
   - Re-dispatch to all available providers
3. If still no acceptance after 5 minutes → **Retry #2**
4. If still no acceptance after 5 minutes → **Retry #3**
5. After 30 minutes total OR max retries reached → **Auto-cancel & Refund**:
   - Status becomes `cancelled`
   - Client refunded to wallet instantly
   - Notification sent to client

### **Database Fields:**
- `retry_count` - Tracks retry attempts
- `cancelled_reason` - Why cancelled (`timeout_exceeded` or `max_retries_exceeded`)
- `cancelled_at` - When cancelled

---

## ✅ **4. Auto-Complete Service Orders**

### **Setting:**
- `service_order_auto_complete_hours` = 24 (default)

### **Flow:**
When provider calls `/finish`:
- Order becomes `provider_finished`
- Job scheduled to run after 24 hours
- If client doesn't respond (confirm or file Golden Guarantee):
  - Auto-complete to `completed`
  - Provider gets paid
  - Notifications sent

### **Job:**
- `App\Jobs\AutoCompleteServiceOrderJob`

---

## ✅ **5. Broker System (الوكالة)**

### **Client Endpoint:**
- `GET /client/broker` - View broker data:
  - `broker_code` - Personal broker code
  - `total_orders_count` - Total orders using any broker code
  - `used_orders_count` - Orders using THIS user's code
  - `total_broker_earnings` - Total earnings from commission
  - `broker_commission_percentage` - Current commission %
  - `broker_discount_percentage` - Discount clients get
  - `how_it_works` - Explanation in AR/EN

### **How It Works:**
1. Every user has a unique broker code (e.g., `BRK-1RIP1Y`)
2. Client enters broker code when creating order
3. Client gets discount (e.g., 5%)
4. Broker earns commission (e.g., 3%) added to wallet
5. Tracked in user stats

---

## ✅ **6. Payment & Refund Logic**

### **Service Orders:**
- **Client pays FIRST** when creating order (status = `pending`)
- **Refund scenarios**:
  1. Provider rejects → Full refund to wallet
  2. Client cancels (before `active`) → Full refund to wallet
- **Provider gets paid when**:
  1. Client confirms completion
  2. Auto-complete after 24h
  3. Admin rejects Golden Guarantee complaint

### **Urgent Orders:**
- **Client pays FIRST** when creating order
- **Refund scenarios**:
  1. No provider accepts within 30 min → Full refund to wallet
  2. Max retries exceeded → Full refund to wallet

### **Payment Calculation:**
```
base_price = service price
discount = base_price × broker_discount_percentage
discounted_price = base_price - discount
vat = discounted_price × vat_percentage
total = discounted_price + vat

Provider earnings = total - broker_commission - platform_fee
```

---

## ✅ **7. Cancellation Rules**

### **Service Orders:**
- ✅ Can cancel in `pending` status (before provider accepts)
- ✅ Can cancel in `accepted` status (after provider accepts but before starting)
- ❌ **CANNOT** cancel in `active` status (provider started work)
- ❌ **CANNOT** cancel in `provider_finished` (use Golden Guarantee instead)

### **Urgent Orders:**
- ✅ Can cancel before provider accepts
- ❌ **CANNOT** cancel after provider accepts

---

## ✅ **8. File Uploads**

### **Service Order Media:**
- `dynamic_form_attachment` - Files uploaded in service form
- `provider_work_files` - Files uploaded by provider during work
- `golden_guarantee_attachments` - Files attached to complaint

---

## 📝 **Key Business Rules**

1. ✅ Golden Guarantee is **ONLY** for service orders (NOT urgent orders)
2. ✅ Client pays **BEFORE** provider accepts (no `pending_payment` status)
3. ✅ Cancellation **blocked** once provider starts work (`active` status)
4. ✅ Provider can upload files **multiple times** during work
5. ✅ Auto-retry urgent orders **ignores previous rejections** (re-dispatches to ALL)
6. ✅ Auto-complete after **24 hours** if client doesn't respond
7. ✅ Broker system tracks earnings and usage automatically
8. ✅ All refunds go to wallet **instantly**

---

## 🎯 **Status Reference**

### **Service Orders:**
- `pending` - Client paid, waiting for provider
- `accepted` - Provider accepted
- `active` - Provider working (no cancellation allowed)
- `provider_finished` - Provider uploaded outputs (رفع المخرجات)
- `pending_admin_review` - Golden Guarantee filed
- `completed` - Successfully completed
- `rejected` - Provider rejected (refunded)
- `cancelled` - Client cancelled (refunded)

### **Urgent Orders:**
- `searching_for_provider` - Looking for available provider
- `accepted` - Provider accepted
- `arrived` - Provider arrived at location
- `completed` - Successfully completed
- `cancelled` - Auto-cancelled (refunded) or client cancelled

---

## 📦 **Files Created/Modified**

### **Controllers:**
- `GoldenGuaranteeController` (admin)
- `ProviderServiceOrderController` (updated)
- `ServiceOrderController` (client, updated)
- `BrokerController` (client, new)

### **Services:**
- `GoldenGuaranteeService` (admin)
- `ServiceOrderService` (provider, updated)
- `ServiceOrderService` (client, updated)

### **Jobs:**
- `AutoCompleteServiceOrderJob` (new)
- `UrgentOrderTimeoutJob` (updated with retry/refund)

### **Requests:**
- `GoldenGuaranteeRequest` (client)
- `GoldenGuaranteeReviewRequest` (admin)
- `UploadWorkFilesRequest` (provider)

### **Enums:**
- `GoldenGuaranteeReasonEnum` (new)

### **Migrations:**
- `add_retry_fields_to_urgent_orders_table`
- `add_golden_guarantee_to_service_orders`

---

## 🚀 **API Endpoints Summary**

### **Provider:**
- Service orders: `/provider/service-orders/*`

### **Client:**
- Service orders: `/client/orders/service/*`
- Broker data: `/client/broker`

### **Admin:**
- Golden Guarantee: `/dashboard/golden-guarantee/*`

---

**Implementation Date:** September 2, 2026  
**Status:** ✅ Complete and Production Ready
