# Notification System Architecture - Law Platform

## Overview
Professional, event-driven notification system for a law service platform.

---

## Architecture: Event → Listener → Notification

```
┌─────────────┐      ┌──────────────┐      ┌──────────────────┐
│   Event     │  →   │  Listener    │  →   │  Notification    │
│  Happens    │      │  Catches     │      │  Sent to User    │
└─────────────┘      └──────────────┘      └──────────────────┘
```

### Example Flow:
```php
// 1. Event fired in Service/Controller
event(new ServiceOrderCreated($order));

// 2. Listener catches it automatically
class NotifyProvidersOfNewOrder implements ShouldQueue {
    public function handle(ServiceOrderCreated $event) {
        // 3. Send notification using NotificationBuilder
        $providers->each(fn($p) => 
            $p->notify(new NewServiceOrderNotification($event->order))
        );
    }
}
```

---

## Notification Categories

All notifications are grouped into **3 main types**:

### 1. **ORDERS** (`notify_type: "orders"`)
All service order related notifications:
- New order created
- Offer submitted/accepted/rejected
- Order activated/completed/cancelled
- Revision requested
- Golden guarantee filed

### 2. **FINANCIAL** (`notify_type: "financial"`)
All payment and wallet notifications:
- Payment received
- Withdrawal requested/approved/rejected
- Commission received
- Refund processed

### 3. **SYSTEM** (`notify_type: "system"`)
All platform, admin, and account notifications:
- Provider approved/rejected
- Platform updates (Terms, Privacy)
- Security alerts
- Rating reminders
- Reviews received
- Chat messages

---

## Current Structure

### **Events** (`app/Events/`)
```
ServiceOrders/
  ├─ ServiceOrderCreated.php
  ├─ ServiceOfferSubmitted.php
  ├─ ServiceOfferAccepted.php
  ├─ ServiceOfferRejected.php
  ├─ ServiceOrderActivated.php
  ├─ ServiceOrderCompleted.php
  └─ ServiceOrderAutoCancelled.php

Withdrawals/
  ├─ WithdrawalSubmitted.php
  ├─ WithdrawalApproved.php
  └─ WithdrawalRejected.php

Providers/
  ├─ ProviderApproved.php
  └─ ProviderRejected.php

Reviews/
  └─ ReviewReceived.php

Users/
  └─ UserRegistered.php

Pages/
  └─ ContactSubmitted.php
```

### **Listeners** (`app/Listeners/`)
```
ServiceOrders/
  ├─ NotifyProvidersOfNewOrder.php
  ├─ NotifyClientOfNewOffer.php
  ├─ NotifyProviderOfferAccepted.php
  ├─ NotifyProviderOfferRejected.php
  ├─ NotifyProviderOrderActivated.php
  ├─ NotifyClientOrderCompleted.php
  ├─ NotifyClientOrderAutoCancelled.php
  └─ NotifyAdminsCompletionFileUploaded.php

Withdrawals/
  ├─ NotifyAdminsOfWithdrawal.php
  ├─ NotifyProviderWithdrawalApproved.php
  └─ NotifyProviderWithdrawalRejected.php

Providers/
  ├─ NotifyProviderApproved.php
  └─ NotifyProviderRejected.php

Reviews/
  └─ NotifyProviderOfReview.php

Users/
  └─ NotifyAdminsOfNewUser.php

Pages/
  └─ NotifyAdminsOfContact.php
```

### **Notifications** (`app/Notifications/`)
```
ServiceOrders/
  ├─ NewServiceOrderNotification.php
  ├─ NewServiceOfferNotification.php
  ├─ ServiceOfferAcceptedNotification.php
  ├─ ServiceOfferRejectedNotification.php
  ├─ ServiceOrderActivatedNotification.php
  ├─ ServiceOrderCompletedNotification.php
  ├─ ServiceOrderAutoCancelledNotification.php
  └─ ServiceOrderCompletionUploadedNotification.php

Withdrawals/
  ├─ WithdrawalSubmittedNotification.php
  ├─ WithdrawalApprovedNotification.php
  └─ WithdrawalRejectedNotification.php

Providers/
  ├─ ProviderApprovedNotification.php
  └─ ProviderRejectedNotification.php

Reviews/
  └─ ReviewReceivedNotification.php

Users/
  └─ UserRegisteredNotification.php

System/
  ├─ PlatformUpdateNotification.php
  ├─ ReminderNotification.php
  └─ SecurityAlertNotification.php

Pages/
  └─ ContactSubmittedNotification.php
```

---

## NotificationBuilder

Centralized builder for consistent notification content.

### Usage:
```php
// In Notification class
public function toArray($notifiable): array {
    return NotificationBuilder::newServiceOrder(
        $this->order->id,
        $this->order->service->title
    );
}
```

### Available Methods:

#### **Orders:**
- `newServiceOrder($orderId, $serviceName)`
- `serviceOfferSubmitted($orderId, $providerName, $price)`
- `serviceOfferAccepted($orderId, $serviceName)`
- `serviceOfferRejected($orderId, $serviceName)`
- `orderActivated($orderId, $serviceName)`
- `orderCompleted($orderId, $serviceName)`
- `orderConfirmed($orderId, $amount)`
- `revisionRequested($orderId, $reason)`
- `orderCancelled($orderId, $serviceName, $reason)`
- `goldenGuaranteeFiled($orderId, $reason)`
- `urgentOrder($orderId, $location)`

#### **Financial:**
- `paymentReceived($amount, $source)`
- `withdrawalRequested($requestId, $amount)`
- `withdrawalApproved($requestId, $amount)`
- `withdrawalRejected($requestId, $amount, $reason)`
- `commissionReceived($amount, $source)`
- `refundProcessed($orderId, $amount)`

#### **System:**
- `providerApproved()`
- `providerRejected($reason)`
- `platformUpdate($pageNameAr, $pageNameEn, $pageType)`
- `ratingReminder($orderId, $serviceName)`
- `newDeviceLogin($deviceInfo, $location)`
- `adminAnnouncement($titleAr, $titleEn, $bodyAr, $bodyEn)`
- `reviewReceived($orderId, $rating, $reviewText)`
- `chatMessage($chatId, $senderName, $messagePreview)`

---

## API Endpoints

### Client Routes: `/api/v1/client/notifications`

```
GET    /                      # List all (with filtering)
GET    /{id}                  # Show single (auto mark as read)
PUT    /mark-all-read         # Mark all as read
PUT    /{id}                  # Mark single as read
DELETE /clear-all             # Delete all
DELETE /bulk-delete           # Delete multiple (body: {ids: []})
DELETE /{id}                  # Delete single
```

### Query Parameters:
- `category`: `all`, `orders`, `financial`, `system`
- `per_page`: 1-100 (default: 15)

---

## Best Practices

### ✅ DO:
- Fire events from services/controllers
- Use `NotificationBuilder` for content
- Implement `ShouldQueue` on listeners
- Keep notifications simple and clear
- Use bilingual content (Arabic/English)

### ❌ DON'T:
- Send notifications directly from controllers
- Hardcode notification content
- Block requests with notification sending
- Create custom notification structures
- Mix notification types

---

## Adding New Notification

### Step 1: Create Event
```php
// app/Events/ServiceOrders/NewEvent.php
class NewEvent {
    public function __construct(public readonly Order $order) {}
}
```

### Step 2: Create Listener
```php
// app/Listeners/ServiceOrders/HandleNewEvent.php
class HandleNewEvent implements ShouldQueue {
    public function handle(NewEvent $event) {
        $users->each(fn($u) => 
            $u->notify(new NewNotification($event->order))
        );
    }
}
```

### Step 3: Create Notification
```php
// app/Notifications/ServiceOrders/NewNotification.php
class NewNotification extends AppNotification {
    public function toArray($notifiable): array {
        return NotificationBuilder::newMethod(...);
    }
}
```

### Step 4: Add to NotificationBuilder (if needed)
```php
public static function newMethod($orderId): array {
    return self::make()
        ->title('...', '...')
        ->body('...', '...')
        ->type(NotificationTypeEnum::ORDERS)
        ->notifyId($orderId)
        ->build();
}
```

### Step 5: Fire Event
```php
// In Service/Controller
event(new NewEvent($order));
```

---

## Testing

```php
// Test event is fired
Event::fake();
$service->createOrder($data);
Event::assertDispatched(ServiceOrderCreated::class);

// Test notification is sent
Notification::fake();
event(new ServiceOrderCreated($order));
Notification::assertSentTo($provider, NewServiceOrderNotification::class);
```

---

## Removed (Old Project - Ads System)
The following were removed as they belonged to the old ads-based project:
- ❌ `app/Events/Ads/*`
- ❌ `app/Listeners/Ads/*`
- ❌ `app/Notifications/Ads/*`
- ❌ `app/Notifications/Ad/*`

Current project focuses on **legal services and orders**, not ads.
