# SYSTEM_ARCHITECTURE.md — Full System Architecture

## Layer Architecture

```
┌────────────────────────────────────────────────────────────────────┐
│   UI LAYER (Flutter Widgets)                                       │
│                                                                     │
│  siro_rider:                                                        │
│    Routes: /, /shareApp, /wallet, /profile, /contactSupport         │
│    Screens: SplashScreen, LoginPage, MapPagePassenger, Wallet, etc. │
│                                                                     │
│  siro_driver:                                                       │
│    Routes: /, /OrderRequestPage, /passenger-location-map            │
│    Screens: SplashScreen, LoginPage, PassengerLocationMapPage, etc. │
│                                                                     │
│  siro_admin:                                                        │
│    Routes: /login, /admin/dashboard, /admin/captain, /admin/rides   │
│                                                                     │
│  siro_service:                                                      │
│    Service agent app for driver registration & management           │
└──────────────────────┬─────────────────────────────────────────────┘
                       │ GetX (Get.find, Get.put, Obx)
┌──────────────────────┴─────────────────────────────────────────────┐
│   STATE LAYER (GetX Controllers)                                    │
│                                                                     │
│  Controllers are registered in: AppBindings (permanent)             │
│                                                                     │
│  Rider:                                                             │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ MapEngineController    → Map rendering, camera, markers      │   │
│  │ MapSocketController    → WebSocket lifecycle management      │   │
│  │ RideLifecycleController → Ride state machine (RideState enum)│   │
│  │ LocationSearchController → Place search & autocomplete       │   │
│  │ NearbyDriversController → Nearby driver list management      │   │
│  │ UiInteractionsController → Bottom sheets, dialogs            │   │
│  │ LoginController        → Auth & JWT management               │   │
│  │ PaymentController      → Payment processing                  │   │
│  │ SplashScreenController → App init & auth check               │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
│  Driver:                                                            │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │ HomeCaptainController    → Online/offline, ride management   │   │
│  │ MapSocketController      → WebSocket ride offers             │   │
│  │ NavigationController     → Turn-by-turn navigation           │   │
│  │ BackgroundServiceHelper  → Android foreground service        │   │
│  │ LocationController       → GPS tracking                      │   │
│  └─────────────────────────────────────────────────────────────┘   │
└──────────────────────┬─────────────────────────────────────────────┘
                       │ Dependency Injection via GetX
┌──────────────────────┴─────────────────────────────────────────────┐
│   REPOSITORY LAYER (CRUD + Services)                                 │
│                                                                     │
│  CRUD class (siro_rider/lib/controller/functions/crud.dart)         │
│    - post()         → Main API POST with JWT + Device-FP headers   │
│    - get()          → API GET (POST method) with retry logic        │
│    - postWallet()   → Payment server POST with JWT + HMAC + FP     │
│    - getWallet()    → Payment server GET with JWT + HMAC + FP      │
│    - sendWhatsAppAuth() → WhatsApp OTP delivery                    │
│    - getAgoraToken()     → Agora voice/video call tokens           │
│    - getLlama()          → Llama AI data extraction                │
│    - getChatGPT()        → OpenAI GPT data extraction              │
│    - arabicTextExtractByVisionAndAI() → Azure OCR                  │
│    - getGoogleApi()       → Google Maps API wrapper                │
│    - getHereMap()         → Here Maps API wrapper                  │
│    - getMapSaas()/postMapSaas() → Custom map service               │
│    - sendVerificationRequest() → Twilio verification               │
│    - postPayMob()         → PayMob payment gateway                 │
│                                                                     │
│  NetGuard (network/connection_check.dart) → Internet monitoring    │
└──────────────────────┬─────────────────────────────────────────────┘
                       │ HTTP Calls
┌──────────────────────┴─────────────────────────────────────────────┐
│   SERVICE LAYER (PHP Backend)                                        │
│                                                                     │
│  Main API: api.intaleq.xyz/siro_v3                               │
│  Ride API: rides.intaleq.xyz/siro                                │
│  Location API: location.intaleq.xyz/siro/ride/location           │
│  Payment API: walletintaleq.intaleq.xyz/v2/main                     │
│  Map SaaS: map-saas.intaleqapp.com/api                              │
│  OSRM Route: routec.intaleq.xyz / routesy.intaleq.xyz               │
└──────────────────────┬─────────────────────────────────────────────┘
                       │ MySQL + WebSocket
┌──────────────────────┴─────────────────────────────────────────────┐
│   DATA LAYER (MySQL Databases)                                      │
│                                                                     │
│  Database: intaleqDB1 (primary)                                     │
│  Database: intaleq-ridesDB (ride-specific)                          │
│  Tables: 60+ tables covering users, rides, payments, etc.           │
└─────────────────────────────────────────────────────────────────────┘
```

---

## Dependency Graph

```
Rider App (siro_rider) ───→ Main API ─────→ intaleqDB1
  ├──→ Map SaaS ───────→ Custom Map Service
  ├──→ OSRM ───────────→ OpenStreetMap
  ├──→ Payment API ────→ Wallet DB
  ├──→ Firebase ───────→ FCM
  ├──→ WebSocket ──────→ Ride Socket Server
  └──→ Google Maps ────→ Google APIs

Driver App (siro_driver) ───→ Main API ─────→ intaleqDB1
  ├──→ Location API ───→ car_locations
  ├──→ Payment API ────→ Wallet DB
  ├──→ WebSocket ──────→ Driver Socket Server
  ├──→ Firebase ───────→ FCM
  └──→ Google Maps ────→ Google APIs

Admin App (siro_admin) ────→ Main API ─────→ intaleqDB1
  ├──→ Payment API
  ├──→ Firebase
  └──→ Internal Services

Socket Server (socket_intaleq) ──→ MySQL
  ├──→ driver_socket.php ──→ Driver Socket.IO
  └──→ passenger_socket.php ──→ Passenger Socket.IO

Ride Server (rides.intaleq.xyz) ──→ MySQL (intaleq-ridesDB)
Location Server (location.intaleq.xyz) ──→ MySQL (car_locations)
Payment Server (walletintaleq.intaleq.xyz) ──→ Wallet MySQL
```

---

## External Services

| Service | Integration Point | Auth Method | Purpose |
|---------|-----------------|-------------|---------|
| **Google Maps** | `https://maps.googleapis.com/maps/api/` | API Key | Map rendering, geocoding |
| **Here Maps** | `https://autosuggest.search.hereapi.com/v1/autosuggest` | API Key | Place autocomplete |
| **Map SaaS** | `https://map-saas.intaleqapp.com/api/` | x-api-key | Custom routing, geocoding |
| **OSRM Server** | `https://routec.intaleq.xyz/route` | None | OpenStreetMap routing |
| **Firebase** | Firebase SDK | google-services.json | FCM, Analytics, Crashlytics |
| **PayMob** | PayMob SDK | API Key + HMAC | Payment gateway (Visa/Mastercard) |
| **Twilio** | Twilio Verify API | Account SID + Auth Token | SMS OTP verification |
| **WhatsApp Cloud** | Graph API | OAuth Token | WhatsApp OTP delivery |
| **Azure OCR** | `https://ocrhamza.cognitiveservices.azure.com/` | Subscription Key | Document text extraction |
| **OpenAI** | OpenAI API | API Key | Document data extraction (GPT-3.5) |
| **Llama AI** | Llama API | Bearer Token | Document data extraction |
| **Agora** | Agora SDK | App Certificate | Voice/video calls |
| **SMS Kazumi** | `https://sms.kazumi.me/api/` | API Key | SMS provider (Egypt) |

---

## Security Architecture

### Authentication
| Mechanism | Implementation |
|-----------|---------------|
| **JWT** | Custom JWT tokens issued at login, validated on each request |
| **Fingerprint** | Device fingerprint hashed with SHA-256, stored in JWT payload |
| **HMAC** | HMAC authentication for payment server requests |
| **Bearer Tokens** | Standard Bearer token in Authorization header |
| **Social Auth** | Google Sign-In, Apple Sign-In |

### Authorization
- **Role-based**: Passenger, Driver, Admin, Service Agent
- **Device Binding**: X-Device-FP header verified against JWT fingerprint claim
- **Wallet Auth**: Separate JWT + HMAC for payment operations

### Token Handling
| Token | Storage | Expiry | Refresh |
|-------|---------|--------|---------|
| JWT (main) | GetStorage | 1 hour (default) | `getJWT()` auto-refresh on 401 |
| JWT (wallet) | GetStorage | 1 hour | `getJwtWallet()` auto-refresh |
| FCM Token | GetStorage + DB | Firebase-managed | On app start |
| Refresh Token | FlutterSecureStorage | Long-lived | On login |

### Encryption
- **AES-256-CBC**: Custom encrypt/decrypt for sensitive data
- **SHA-256**: Device fingerprint hashing
- **Base64**: Basic auth credentials encoding
- **SSL/TLS**: All API calls over HTTPS

### Secure Storage
| Data | Storage Method |
|------|---------------|
| JWT tokens | GetStorage (encrypted box) |
| Refresh tokens | FlutterSecureStorage (Keychain/Keystore) |
| Fingerprint | GetStorage (encrypted) |
| HMAC keys | GetStorage (encrypted) |

### Session Management
- Auto-logout on token expiry (401 response)
- Fingerprint migration tools in admin panel
- Login attempt rate limiting (`login_attempts` table)

---

## Caching Strategy

| Cache Type | Implementation | Data Cached |
|-----------|---------------|-------------|
| **GetStorage** (Local) | Key-value store in app sandbox | JWT, user ID, preferences, ride state |
| **FlutterSecureStorage** | OS-level encrypted storage | Refresh tokens, sensitive data |
| **SQLite (DbSql)** | Local SQLite database | Offline maps, ride history |
| **Memory Cache** | GetX controller state | Active ride data, driver list, map markers |
| **Server Cache** | MySQL + Query Cache | Driver locations (car_locations), places |
| **In-Memory (NetGuard)** | Singleton notification state | Network error debouncing |

---

## WebSocket Architecture

```
┌──────────────┐         ┌──────────────────┐         ┌──────────────┐
│  Rider App   │◄───────►│  Passenger Socket │◄───────►│  MySQL DB   │
│              │         │  (PHP)            │         │              │
└──────────────┘         └──────────────────┘         └──────────────┘
                              │
                              │ (Internal IPC)
                              │
┌──────────────┐         ┌──────────────────┐         ┌──────────────┐
│  Driver App  │◄───────►│  Driver Socket    │◄───────►│  MySQL DB   │
│              │         │  (PHP)            │         │              │
└──────────────┘         └──────────────────┘         └──────────────┘
```

**Socket Events:**
- `driver_location_update` — Real-time driver GPS to passenger
- `ride_accepted` — Driver accepted notification
- `ride_cancelled` — Ride cancellation event
- `ride_finished` — Ride completion event
- `passenger_location` — Passenger location (for driver)
- `driver_online` / `driver_offline` — Online status changes

---

## Admin Module Structure

| Module | Controller | Views |
|--------|-----------|-------|
| Dashboard | `DashboardController`, `DashboardV2Controller` | `admin_home_page.dart` |
| Captain Management | `CaptainAdminController` | `captain.dart`, `captain_details.dart` |
| Passenger Management | `PassengerAdminController` | `passenger.dart`, `passenger_details_page.dart` |
| Ride Management | `RideAdminController`, `RideLookupController` | `rides.dart`, `ride_lookup_page.dart` |
| Financial | `FinancialV2Controller` | `financial_v2_page.dart` |
| Analytics | `AnalyticsV2Controller`, `StaticController` | `advanced_analytics_page.dart` |
| Complaints | `ComplaintController` | `complaint_list_page.dart` |
| Pricing/Kazan | `KazanController` | `kazan_editor_page.dart` |
| Promotions | `PromoController` | `promo_management_page.dart` |
| Wallet | `WalletAdminController` | `wallet.dart` |
| Driver Docs | `DriverDocsController` | `driver_documents_review_page.dart` |
| Security | `SecurityV2Controller` | `audit_logs_page.dart` |
| Quality | `QualityController` | `blacklist_page.dart`, `driver_scorecard_page.dart` |
| Staff | `StaffController` | `add_staff_page.dart`, `pending_admins_page.dart` |
| Server Monitor | `ServerMonitorController` | `monitor_server_page.dart` |
| Invoices | `GetAllInvoiceController` | `invoice_list_page.dart` |