# Backend Architecture Documentation

## Overview

This is a **Laravel 13.0** based food delivery backend API built with **PHP 8.3**. The system follows a **Service Layer Architecture** pattern with RESTful API design, supporting multiple user roles (Clients, Drivers, Restaurants, Admins) for a comprehensive food delivery platform.

---

## Tech Stack

### Core Framework
- **Laravel 13.0** - PHP Framework
- **PHP 8.3** - Runtime Environment

### Key Dependencies
- **Laravel Sanctum 4.0** - API Authentication
- **Laravel Reverb 1.0** - Real-time WebSocket Events
- **Spatie Laravel Permission 7.2** - Role-based Access Control
- **Kreait Laravel Firebase 7.2** - Firebase Integration
- **Laravel Notification Channels FCM 6.1** - Push Notifications
- **Livewire 4.2** - Dynamic UI Components
- **Maatwebsite Excel 3.1** - Data Export/Import
- **Tarfin Labs Laravel Spatial 3.2** - Geographic/Location Data
- **Carlos Meneses Laravel mPDF 2.1** - PDF Generation

### Database
- **MySQL 8.4** - Primary Database
- **SQLite** - Testing Database

### Development Tools
- **Laravel Sail** - Docker Development Environment
- **PHPUnit 12.5** - Testing Framework
- **Laravel Pail** - Log Monitoring
- **Laravel Pint** - Code Formatting

---

## Architecture Pattern

### Service Layer Architecture

The application follows a **Service Layer Pattern** to separate business logic from controllers:

```
Request → Controller → Service → Model → Database
                    ↓
                 Resources
```

**Benefits:**
- Separation of concerns
- Reusable business logic
- Easier testing
- Clean controllers

---

## Directory Structure

```
resto-backend/
├── app/
│   ├── Channels/           # Broadcasting channels
│   ├── Console/            # Artisan commands
│   ├── Enums/              # PHP 8.1 Enums
│   ├── Exports/            # Excel exports
│   ├── Helpers/            # Utility functions
│   ├── Http/
│   │   ├── Controllers/
│   │   │   └── Api/V1/     # API Controllers (versioned)
│   │   ├── Requests/       # Form Request Validation
│   │   └── Resources/      # API Resource Transformers
│   ├── Jobs/               # Queue jobs
│   ├── Livewire/           # Livewire components
│   ├── Mail/               # Email classes
│   ├── Models/             # Eloquent models
│   ├── Notifications/      # Notification classes
│   ├── Providers/          # Service providers
│   └── Services/           # Business logic layer
├── config/                 # Configuration files
├── database/
│   ├── factories/          # Model factories
│   ├── migrations/         # Database migrations
│   └── seeders/            # Database seeders
├── public/                 # Public entry point
├── resources/              # Frontend assets
├── routes/
│   ├── api.php            # API routes
│   ├── channels.php       # Broadcasting channels
│   ├── console.php        # Console routes
│   └── web.php            # Web routes
├── storage/                # Application storage
├── tests/                  # Test files
├── compose.yaml            # Docker Compose configuration
├── composer.json           # PHP dependencies
└── artisan                 # Laravel CLI tool
```

---

## Core Modules

### 1. Authentication Module

**Controller:** `AuthController`
**Service:** `AuthService`

**Features:**
- Multi-role authentication (Client, Driver, Restaurant)
- Identity is scoped per restaurant: client, driver and staff accounts carry a
  `users.restaurant_id`, and email/phone are unique per tenant rather than
  globally, so the same person can hold an account in several white-label apps.
  Admin and restaurant-owner accounts have a null tenant and stay unique
  platform-wide. See `App\Support\Tenant`.
- JWT-like token authentication via Sanctum
- Password reset with verification codes
- FCM token management
- Terms & conditions tracking

**Endpoints:**
- `POST /api/v1/auth/clients/login`
- `POST /api/v1/auth/drivers/login`
- `POST /api/v1/auth/restaurants/login`
- `POST /api/v1/auth/logout`
- `POST /api/v1/forgot-password`
- `POST /api/v1/verify-code`
- `POST /api/v1/reset-password`

---

### 2. User Management Module

**Models:** `User`, `Client`, `Driver`, `Restaurant`
**Controllers:** `ClientController`, `DriverController`, `RestaurantController`
**Services:** `ClientService`, `DriverService`, `RestaurantService`, `UsersService`

**User Types (Enum):**
- **Admin** - System administrator
- **Client** - End customers
- **Driver** - Delivery drivers
- **Restaurant** - Restaurant owners/staff

**Features:**
- Profile management
- Account activation/deactivation
- Status management
- Profile updates
- Product favorites

---

### 3. Restaurant Module

**Model:** `Restaurant`
**Controller:** `RestaurantController`
**Service:** `RestaurantService`

**Features:**
- Restaurant registration and management
- Geographic location (spatial data)
- Opening hours management
- Availability status
- Wallet system
- Product management
- Order management
- Reviews and ratings
- Analytics and overview

**Key Relationships:**
- Has many Products
- Has many Orders
- Has many Subscriptions
- Has many Sliders
- Has many OpeningHours
- Has one Wallet

---

### 4. Product Module

**Model:** `Product`
**Controller:** `ProductController`
**Service:** `ProductService`

**Features:**
- Product CRUD operations
- Category association
- Media management
- Availability toggle
- Best sellers tracking
- Search and filtering
- Reviews and ratings

**Key Relationships:**
- Belongs to Restaurant
- Belongs to Category
- Has many Media
- Has many OrderProducts
- Has many Reviews

---

### 5. Category Module

**Model:** `Category`
**Controller:** `CategoryController`
**Service:** `CategoryService`

**Features:**
- Category hierarchy
- Icon management
- Product categorization

---

### 6. Order Module

**Model:** `Order`, `OrderProduct`
**Controller:** `OrderController`
**Service:** `OrderService`

**Order Status Flow (Enum):**
```
pending → accepted → preparing → ready_for_pickup → on_the_way → delivered
                ↓
             declined
```

**Features:**
- Order creation
- Order status management
- Driver assignment (manual/auto)
- Restaurant acceptance/decline
- Delivery tracking
- Order fees calculation
- Preparation & delivery time tracking
- Peak hour pricing
- Demand fees

**Key Relationships:**
- Belongs to Client
- Belongs to Restaurant
- Belongs to Driver (optional)
- Has many OrderProducts
- Has many WalletTransactions

---

### 7. Driver Module

**Model:** `Driver`
**Controller:** `DriverController`
**Service:** `DriverService`

**Features:**
- Driver registration
- Work status management (online/offline)
- Real-time location tracking
- Order acceptance
- Wallet system
- Transaction history
- Reviews and ratings
- Subscription management

**Key Relationships:**
- Belongs to User
- Has many Orders
- Has one Wallet
- Has many Subscriptions

---

### 8. Notification Module

**Model:** `Notification`
**Controller:** `NotificationController`
**Service:** `NotificationService`

**Notification Types:**
- `NewOrderNotification` - Restaurant receives new order
- `OrderAcceptNotification` - Client notified of acceptance
- `OrderDeclineNotification` - Client notified of decline
- `DriverAcceptOrderNotification` - Restaurant notified
- `DriverAssignedOrderNotification` - Driver notified
- `NewDeliveryRequestNotification` - Driver receives delivery request
- `OrderDeliveredNotification` - Order completion
- `NoDriverAcceptedNotification` - Timeout scenario
- `OrderRejectedAutomaticallyNotification` - Auto-rejection
- `RestaurantDidNotAcceptOrderNotification` - Timeout scenario
- `SubscriptionExpiredNotification` - Subscription expiry
- `NewJoiningDriverNotification` - Admin notified
- `NewJoiningRestaurantNotification` - Admin notified

**Channels:**
- FCM (Push Notifications)
- Database (In-app notifications)
- Broadcast (Real-time via Reverb)

---

### 9. Review Module

**Model:** `Review`
**Controller:** `ReviewController`
**Service:** `ReviewService`

**Features:**
- Restaurant reviews
- Product reviews
- Driver reviews
- Rating system
- Review aggregation

---

### 10. Wallet Module

**Models:** `Wallet`, `WalletTransaction`
**Services:** `TransactionService`

**Features:**
- Multi-wallet system (Restaurant, Driver)
- Transaction tracking
- Revenue management
- Order revenue vs delivery revenue

**Transaction Types (Enum):**
- Credit
- Debit

**Transaction Reasons (Enum):**
- Order payment
- Delivery fee
- Subscription payment
- Refund
- Withdrawal

---

### 11. Subscription Module

**Model:** `Subscription`
**Controller:** `SubscriptionController`
**Service:** `SubscriptionService`

**Features:**
- Driver subscriptions
- Restaurant subscriptions
- Slider-based promotions
- Subscription expiry tracking

---

### 12. Location Module

**Models:** `Country`, `State`, `Municipality`
**Controller:** `StateController`
**Service:** `StateService`

**Features:**
- Geographic hierarchy
- State/city management
- Location-based filtering

---

### 13. Slider Module

**Model:** `Slider`
**Controller:** `SliderController`
**Service:** `SliderService`

**Features:**
- Promotional banners
- Restaurant-specific sliders
- Subscription association

---

### 14. Settings Module

**Model:** `Setting`
**Controller:** `SettingsController`
**Service:** `SettingsService`

**Features:**
- Application-wide settings
- Fee configuration
- Distance settings
- Timeout settings
- Revenue percentages

---

### 15. Analytics Module

**Service:** `AnalyticsService`

**Features:**
- Restaurant overview
- Sales analytics
- Performance metrics
- Order statistics

---

## Database Schema

### Core Tables

**Users & Authentication:**
- `users` - Base user table with role types, plus the account's tenant
- `clients` - Client-specific data, scoped to one restaurant
- `drivers` - Driver-specific data
- `personal_access_tokens` - Sanctum tokens
- `password_reset_codes` - Password reset codes

**Restaurant Management:**
- `restaurants` - Restaurant profiles (with spatial location)
- `categories` - Product categories
- `products` - Product catalog
- `media` - Media storage
- `opening_hours` - Restaurant operating hours
- `sliders` - Promotional banners

**Orders:**
- `orders` - Order management
- `order_product` - Order-product pivot
- `reviews` - Reviews and ratings

**Location:**
- `countries` - Country data
- `states` - State/province data
- `municipalities` - City/municipality data

**Financial:**
- `wallets` - User wallets
- `wallet_transactions` - Transaction history
- `subscriptions` - User subscriptions
- `demand_fees` - Peak hour pricing
- `peak_hours` - Peak hour definitions

**System:**
- `settings` - Application settings
- `notifications` - Notification history
- `favorites` - Product favorites (client ↔ product)
- `jobs` - Queue jobs
- `cache` - Cache storage

**Permissions:**
- `permissions` - Permission definitions
- `roles` - Role definitions
- `model_has_permissions` - Model-permission pivot
- `model_has_roles` - Model-role pivot
- `role_has_permissions` - Role-permission pivot

---

## API Design

### Versioning
All API routes are versioned under `/api/v1/`

### Authentication
- **Sanctum** for API authentication
- Token-based authentication
- Middleware: `auth:sanctum`

### Response Format
Standardized JSON responses using Laravel API Resources

### Rate Limiting
Configured via Laravel's rate limiting middleware

---

## Real-time Features

### Laravel Reverb (WebSocket)
- Real-time order updates
- Live driver location tracking
- Instant notifications
- Order status changes

### Broadcasting Channels
- Order channels
- Notification channels
- Driver location channels

---

## Background Jobs

### Queue System
- **Database Queue** - Default queue driver
- **Redis Queue** - Available for production

### Job Types:
- Email sending
- Push notifications
- PDF generation
- Data exports
- Analytics processing

---

## Security Features

### Authentication
- Laravel Sanctum for API tokens
- Password hashing (bcrypt)
- Token revocation on logout

### Authorization
- Spatie Laravel Permission for RBAC
- Role-based access control
- Permission-based API access

### Validation
- Form Request validation
- Input sanitization
- SQL injection prevention (Eloquent ORM)

### CORS
- Configured CORS policy
- Origin whitelisting

---

## Deployment

### Docker Configuration
**Services:**
- **Laravel Application** (PHP 8.5)
- **MySQL 8.4** - Database
- **Redis** - Cache/Queue (optional)

**Environment:**
- Laravel Sail for local development
- Docker Compose for orchestration

### Composer Scripts
- `composer setup` - Initial setup
- `composer dev` - Development server with hot reload
- `composer test` - Run tests

---

## Development Workflow

### Local Development
```bash
# Setup
composer setup

# Development
composer dev

# Testing
composer test

# Code formatting
./vendor/bin/pint
```

### API Documentation
API endpoints documented in `/api` directory with individual markdown files for each endpoint.

---

## Key Features Summary

1. **Multi-Role System** - Admin, Client, Driver, Restaurant
2. **Real-time Tracking** - Driver location, order status
3. **Push Notifications** - FCM integration
4. **Geographic Features** - Spatial queries, location-based filtering
5. **Financial System** - Wallets, transactions, revenue sharing
6. **Review System** - Multi-entity reviews and ratings
7. **Subscription System** - Driver/restaurant subscriptions
8. **Analytics** - Restaurant performance metrics
9. **Flexible Ordering** - Manual/auto driver assignment
10. **Peak Hour Pricing** - Dynamic demand-based pricing

---

## External Integrations

1. **Firebase Cloud Messaging (FCM)** - Push notifications
2. **Google Maps** - Location services (via GoogleMapsService)
3. **mPDF** - PDF generation for receipts/invoices

---

## Performance Considerations

- **Database Indexing** - Strategic indexes on frequently queried columns
- **Caching** - Redis for cache layer
- **Queue System** - Background job processing
- **Spatial Indexes** - Optimized geographic queries
- **API Resources** - Efficient data transformation
- **Eager Loading** - Prevent N+1 queries

---

## Testing Strategy

- **PHPUnit** for unit and feature tests
- **Database SQLite** for testing
- **Factories** for test data generation
- **Seeders** for test database setup

---

## Configuration Management

- **Environment Variables** - `.env` file
- **Config Files** - `config/` directory
- **Settings Table** - Dynamic application settings

---

## Logging

- **Laravel Pail** - Real-time log monitoring
- **Log Channels** - Single, daily, syslog
- **Log Levels** - Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency

---

## Future Scalability Considerations

1. **Microservices** - Potential to split into services
2. **Event Sourcing** - For complex order workflows
3. **Read Replicas** - For read-heavy operations
4. **CDN Integration** - For media delivery
5. **Load Balancing** - For horizontal scaling
6. **Circuit Breakers** - For external service resilience

---

## Architecture Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                         Client Apps                          │
│  (Mobile App - Client | Driver | Restaurant | Admin)       │
└─────────────────────────────┬───────────────────────────────┘
                              │ HTTPS/REST
┌─────────────────────────────▼───────────────────────────────┐
│                      API Gateway Layer                       │
│                    (Laravel Sanctum Auth)                    │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│                    Controller Layer                          │
│              (API V1 Controllers - 12 controllers)          │
└─────────────────────────────┬───────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────┐
│                    Service Layer                            │
│              (20 Services - Business Logic)                 │
└─────────────────────────────┬───────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
┌───────▼───────┐    ┌────────▼────────┐    ┌──────▼──────┐
│   Models      │    │   External      │    │   Queue     │
│   (25 Models) │    │   Services      │    │   Jobs      │
└───────┬───────┘    └────────┬────────┘    └──────┬──────┘
        │                     │                     │
┌───────▼───────┐    ┌────────▼────────┐    ┌──────▼──────┐
│   Database    │    │   Firebase      │    │   Redis     │
│   MySQL 8.4   │    │   Google Maps   │    │   Cache     │
└───────────────┘    └─────────────────┘    └─────────────┘
                              │
                    ┌─────────▼─────────┐
                    │   Laravel Reverb  │
                    │   (WebSocket)     │
                    └───────────────────┘
```

---

## Summary

This backend architecture provides a robust, scalable foundation for a food delivery platform with:
- **Clean architecture** through service layer pattern
- **Multi-role support** for different user types
- **Real-time capabilities** via WebSockets
- **Comprehensive business logic** for order management
- **Financial tracking** with wallet system
- **Location-based features** with spatial queries
- **Push notifications** for user engagement
- **Flexible deployment** via Docker

The system is designed for scalability, maintainability, and ease of development following Laravel best practices.
