# Architecture Overview

## System Architecture

```
+-------------------+    +-------------------+    +-------------------+
|     Clients       |    |      Nginx        |    |    PHP-FPM 8.3    |
| Browser / Mobile  |--->| SSL / Proxy /     |--->| Worker Processes  |
| API Consumers     |    | Cache / Static    |    |                   |
+-------------------+    +-------------------+    +-------------------+
                                |                         |
                                v                         v
+-------------------+    +-------------------+    +-------------------+
|    Redis          |    |  Laravel 12+      |    |    MySQL 8.0      |
| Cache / Queue /  |<-->| Application       |<-->| Database          |
| Session          |    |                   |    |                   |
+-------------------+    +-------------------+    +-------------------+
                                |
                                v
                        +-------------------+
                        |   Supervisor      |
                        | Queue Workers     |
                        | Scheduler         |
                        +-------------------+
```

## Layered Architecture

The application follows a layered architecture pattern:

### 1. Presentation Layer
- **Blade Views**: Server-side rendered templates
- **Livewire Components**: Interactive UI components
- **API Resources**: JSON response formatting

### 2. Application Layer
- **Controllers**: Handle HTTP requests
- **Services**: Business logic encapsulation
- **Form Requests**: Input validation
- **API Resources**: Response transformation

### 3. Domain Layer
- **Models**: Eloquent ORM models
- **Events**: Domain events
- **Listeners**: Event handlers
- **Jobs**: Queue jobs

### 4. Infrastructure Layer
- **Repositories**: Data access abstraction
- **External Services**: Third-party integrations
- **Mail**: Email services
- **Storage**: File storage

## Folder Structure

```
exim-erp/
+-- app/
|   +-- Http/
|   |   +-- Controllers/      # Request handlers
|   |   +-- Middleware/        # Request/Response middleware
|   |   +-- Requests/         # Form validation
|   +-- Models/               # Eloquent models
|   +-- Services/             # Business logic
|   +-- Events/               # Domain events
|   +-- Listeners/            # Event listeners
|   +-- Jobs/                 # Queue jobs
|   +-- Mail/                 # Email classes
|   +-- Providers/            # Service providers
+-- bootstrap/                # Application bootstrap
+-- config/                   # Configuration files
+-- database/
|   +-- migrations/           # Database migrations
|   +-- seeders/              # Database seeders
+-- deployment/               # Deployment configurations
|   +-- nginx/                # Nginx configs
|   +-- php/                  # PHP configs
|   +-- supervisor/           # Supervisor configs
|   +-- scripts/              # Deployment scripts
|   +-- cron/                 # Cron jobs
+-- public/                   # Web root
+-- resources/
|   +-- views/                # Blade templates
|   +-- js/                   # JavaScript
|   +-- css/                  # Stylesheets
+-- routes/                   # Route definitions
+-- storage/                  # Application storage
+-- tests/                    # Test files
```

## Design Patterns

### Repository Pattern
Data access is abstracted through repositories:

```php
// Interface
interface OrderRepositoryInterface
{
    public function findById(int $id): ?Order;
    public function create(array $data): Order;
    public function update(int $id, array $data): Order;
}

// Implementation
class EloquentOrderRepository implements OrderRepositoryInterface
{
    public function findById(int $id): ?Order
    {
        return Order::find($id);
    }
}
```

### Service Layer Pattern
Business logic is encapsulated in services:

```php
class OrderService
{
    public function __construct(
        private OrderRepositoryInterface $repository,
        private InvoiceService $invoiceService
    ) {}

    public function createOrder(array $data): Order
    {
        $order = $this->repository->create($data);
        $this->invoiceService->generateInvoice($order);
        return $order;
    }
}
```

### Observer Pattern
Model events are handled through observers:

```php
class OrderObserver
{
    public function created(Order $order): void
    {
        event(new OrderCreated($order));
    }

    public function updated(Order $order): void
    {
        if ($order->isDirty('status')) {
            event(new OrderStatusChanged($order));
        }
    }
}
```

### Queue Pattern
Long-running tasks are processed via queues:

```php
class ProcessShipmentJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 300;

    public function handle(ShipmentService $service): void
    {
        $service->process($this->shipment);
    }
}
```

## Data Flow

### Order Processing Flow

```
1. Customer places order
   |
   v
2. OrderController::store()
   |
   v
3. OrderService::createOrder()
   |
   v
4. Order created (status: pending)
   |
   v
5. OrderCreated event dispatched
   |
   +---> SendOrderConfirmationJob
   +---> UpdateInventoryJob
   |
   v
6. Order processed
   |
   v
7. InvoiceService::generateInvoice()
   |
   v
8. Invoice created
   |
   v
9. Order status updated to processing
```

### Invoice Processing Flow

```
1. Invoice created
   |
   v
2. InvoiceCreated event
   |
   +---> SendInvoiceEmailJob
   +---> UpdateAccountingJob
   |
   v
3. Payment received
   |
   v
4. InvoiceService::markAsPaid()
   |
   v
5. Payment recorded
   |
   v
6. Order status updated
```

## Security Architecture

### Authentication
- Laravel Sanctum for API tokens
- Session-based authentication for web
- JWT tokens for mobile apps

### Authorization
- Role-Based Access Control (RBAC)
- Policies for resource authorization
- Gates for permission checks

### Data Protection
- CSRF protection on all forms
- XSS prevention through Blade escaping
- SQL injection prevention via Eloquent
- Rate limiting on API endpoints

### Infrastructure Security
- SSL/TLS encryption
- Security headers (HSTS, CSP, X-Frame-Options)
- IP whitelisting for admin access
- Database encryption at rest

## Caching Strategy

### Redis Cache Layers
1. **Configuration Cache**: Application config
2. **Route Cache**: Compiled routes
3. **View Cache**: Compiled Blade templates
4. **Query Cache**: Database query results
5. **Session Cache**: User sessions

### Cache Invalidation
```php
// Event-based invalidation
class OrderUpdated
{
    public function handle(Order $order): void
    {
        Cache::forget("order_{$order->id}");
        Cache::forget("orders_list");
        Cache::tags(['orders'])->flush();
    }
}
```

## Queue System

### Queue Types
1. **Default**: General background tasks
2. **Emails**: Email sending jobs
3. **Reports**: Report generation
4. **Exports**: Data export jobs

### Worker Configuration
- 4 worker processes per queue
- Auto-restart on memory limit
- Max execution time: 1 hour
- Retry attempts: 3

## Monitoring

### Health Checks
- Service status monitoring
- Database connection checks
- Redis connection checks
- Queue worker status

### Logging
- Application logs
- Error logs
- Access logs
- Queue logs

### Metrics
- Request response times
- Queue job processing times
- Database query performance
- Cache hit/miss rates

## Scalability

### Horizontal Scaling
- Load balancer support
- Stateless application servers
- Shared storage via NFS/S3
- Database replication

### Vertical Scaling
- PHP-FPM worker tuning
- Redis memory optimization
- MySQL query optimization
- Nginx worker configuration

## Backup Strategy

### Automated Backups
- Database: Daily at 2 AM
- Application files: Daily at 2 AM
- Configuration: Weekly
- Logs: Weekly cleanup

### Backup Retention
- Daily backups: 30 days
- Weekly backups: 12 weeks
- Monthly backups: 12 months

## Deployment Pipeline

### Stages
1. **Development**: Local development
2. **Staging**: Pre-production testing
3. **Production**: Live environment

### Deployment Process
1. Code review and approval
2. Automated testing
3. Build artifacts
4. Deploy to staging
5. QA verification
6. Deploy to production
7. Post-deployment verification

### Rollback Procedure
1. Identify failed deployment
2. Enable maintenance mode
3. Revert to previous version
4. Run migrations (if needed)
5. Clear caches
6. Disable maintenance mode
