# Elohome Architecture & Design

## System Architecture

Elohome follows a modern, scalable MVC (Model-View-Controller) architecture with clean separation of concerns.

```
┌─────────────────────────────────────────────────────────┐
│                      Client Layer                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │  Web Browser │  │ Mobile App   │  │ Admin Panel  │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└────────────────────────┬──────────────────────────────────┘
                         │ HTTP/HTTPS
┌────────────────────────▼──────────────────────────────────┐
│                    API Layer                              │
│  ┌──────────────────────────────────────────────────┐   │
│  │ Laravel 11 Web Server (Blade + Vue routes)       │   │
│  │ REST API Endpoints (Sanctum Authenticated)       │   │
│  └──────────────────────────────────────────────────┘   │
└────────────────────────┬──────────────────────────────────┘
                         │
┌────────────────────────▼──────────────────────────────────┐
│                 Application Layer                         │
│  ┌─────────────────┐  ┌──────────────┐  ┌─────────────┐ │
│  │  Controllers    │  │  Middleware  │  │   Routes    │ │
│  │  Services       │  │  Validation  │  │   Events    │ │
│  │  Policies       │  │  Gates        │  │  Listeners  │ │
│  └─────────────────┘  └──────────────┘  └─────────────┘ │
└────────────────────────┬──────────────────────────────────┘
                         │
┌────────────────────────▼──────────────────────────────────┐
│                   Domain Layer                            │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐   │
│  │ Eloquent     │  │  Validation  │  │  Business    │   │
│  │ Models       │  │  Rules       │  │  Logic       │   │
│  │  Relations   │  │  Requests    │  │  Services    │   │
│  └──────────────┘  └──────────────┘  └──────────────┘   │
└────────────────────────┬──────────────────────────────────┘
                         │
┌────────────────────────▼──────────────────────────────────┐
│                 Persistence Layer                         │
│         ┌──────────────────────────────────┐             │
│         │    MySQL Database                 │             │
│         │  ├─ Users & Authentication        │             │
│         │  ├─ Products & Categories         │             │
│         │  ├─ Orders & Payments             │             │
│         │  ├─ Customer Data                 │             │
│         │  └─ System Configuration          │             │
│         └──────────────────────────────────┘             │
└─────────────────────────────────────────────────────────────┘
```

---

## Component Architecture

### Models (Domain Objects)

Every model represents a business entity with:
- **Relationships**: Properly configured Eloquent relations
- **Scopes**: Query builder convenience methods
- **Casts**: Type conversion for attributes
- **Accessors/Mutators**: Data transformation
- **Validation**: Rules for data integrity

Example:
```php
class Product extends Model {
    // Relationships
    belongsTo(Category::class);
    hasMany(ProductImage::class);
    hasMany(Review::class);
    
    // Scopes
    scopeActive();
    scopeFeatured();
    scopeInStock();
    
    // Search
    toSearchableArray();
}
```

### Controllers (Request Handlers)

Slim controllers that:
- Receive HTTP requests
- Validate input data
- Delegate business logic to services
- Return responses (views or JSON)

Structure:
```
Controllers/
├── ProductController.php      # Public product browsing
├── CartController.php         # Shopping cart management
├── OrderController.php        # Order management
├── ReviewController.php       # Product reviews
├── UserController.php         # User profiles
├── Auth/
│   ├── LoginController.php
│   ├── RegisterController.php
│   └── PasswordController.php
└── Admin/
    ├── DashboardController.php
    ├── ProductController.php  # Product management
    ├── OrderController.php    # Order management
    └── ...
```

### Services (Business Logic)

Encapsulates complex operations:
- `OrderService` - Order processing, validation
- `PaymentService` - Payment handling
- `CartService` - Cart calculations
- `NotificationService` - Email/SMS sending
- `InventoryService` - Stock management

### Middleware (Request/Response Filters)

- `AuthMiddleware` - Authentication check
- `AdminMiddleware` - Admin authorization
- `VerifyCsrfToken` - CSRF protection
- `ThrottleRequests` - Rate limiting
- `SetLocale` - Language/locale setting

### Routing Strategy

```
Routes/
├── web.php          # Public & authenticated web routes
├── api.php          # RESTful API routes
└── console.php      # Artisan commands
```

**Route Groups**:
- `/` - Public routes
- `/auth` - Authentication routes
- `/dashboard` - User dashboard (protected)
- `/admin` - Admin panel (protected)
- `/api` - REST APIs (token-based)

---

## Database Design

### Entity Relationship Diagram

```
users (1) ──────────┬─────────── (many) orders
         │          │
         │          └─────────── (many) reviews
         │
         ├────────── (many) wishlists
         │
         ├────────── (many) carts
         │
         └────────── (many) addresses

products (1) ─────────┬─────────── (many) order_items
            │         │
            │         ├─────────── (many) reviews
            │         │
            │         ├─────────── (many) product_images
            │         │
            │         └─────────── (many) wishlist_items
            │
            ├─── (many-to-one) categories
            │
            └─── (many-to-one) brands

orders (1) ────────────┬────────── (many) order_items
          │            │
          │            └────────── (many) payments
          │
          ├───── (many-to-one) users
          │
          └───── (many-to-one) addresses
```

### Key Relationships

| Relationship | Type | Purpose |
|-------------|------|---------|
| User →Orders | 1:N | Tracks customer orders |
| Order →OrderItems | 1:N | Line items in order |
| OrderItem →Product | N:1 | Product in order |
| Product →Category | N:1 | Product categorization |
| Product →Brand | N:1 | Brand information |
| Product →Images | 1:N | Product photos |
| Product →Reviews | 1:N | Customer reviews |
| User →Addresses | 1:N | Shipping addresses |
| User →Cart | 1:N | Shopping cart items |
| User →Wishlist | 1:N | Saved products |

---

## Data Flow

### Product Browsing Flow
```
1. User requests product list
2. ProductController queries database
3. Apply filters/search/sort
4. Return paginated results
5. Blade template renders HTML
6. Client receives product listing
```

### Order Creation Flow
```
1. User submits checkout form
2. CheckoutController validates input
3. OrderService creates order transaction
4. Stock inventory decremented
5. Payment record created
6. Cart cleared
7. Notifications sent (email, SMS)
8. Order confirmation returned
```

### Payment Processing Flow
```
1. Payment details submitted
2. Determine payment method (MTN, Airtel, Stripe)
3. Call appropriate Payment Gateway API
4. Handle success/failure response
5. Update payment status
6. Update order status
7. Send notifications
8. Generate invoice
```

---

## API Design

### REST Principles Applied

- **Resources**: Products, Orders, Users, Carts, Reviews
- **Methods**: GET (read), POST (create), PUT (update), DELETE (delete)
- **Status Codes**: 200 (OK), 201 (Created), 400 (Bad Request), 401 (Unauthorized), 404 (Not Found)
- **Authentication**: Bearer token (Sanctum)

### API Versioning (Future)

```
/api/v1/products
/api/v2/products     # With enhanced features
```

### Response Format

```json
{
  "success": true,
  "message": "Operation successful",
  "data": {
    // Resource data
  },
  "meta": {
    "pagination": {
      "total": 100,
      "per_page": 15,
      "current_page": 1,
      "from": 1,
      "to": 15
    }
  }
}
```

---

## Security Architecture

### Authentication & Authorization

```
Request
  ↓
[Authentication Middleware]
  ├─ Check if user is authenticated
  ├─ Verify JWT/Sanctum token
  ↓
[Authorization Gate/Policy]
  ├─ Check user permissions
  ├─ Check resource ownership
  ↓
[Business Logic]
  ├─ Process authenticated request
  ↓
Response
```

### Security Layers

1. **Transport Security**: HTTPS/SSL encryption
2. **Input Validation**: Request validation rules
3. **SQL Security**: Eloquent ORM prevents injection
4. **CSRF Protection**: Token-based form validation
5. **Authorization**: Gate & Policy system
6. **Password Security**: bcrypt hashing (minimum 8 characters)
7. **API Security**: Sanctum token authentication
8. **Rate Limiting**: ThrottleRequests middleware
9. **Audit Logging**: Complete activity tracking (Spatie)

---

## Caching Strategy

```
Application Cache Layers:
1. Process-level: Application cache (file/Redis)
2. Database-level: Query caching
3. HTTP-level: Browser cache headers
4. CDN-level: Static asset caching
```

### Cacheable Items
- Product listings (30 min)
- Categories (1 hour)
- Brands (1 hour)
- User sessions
- API responses

---

## Error Handling

### Exception Hierarchy
```
Exception
├── ValidationException    # Form validation errors
├── AuthenticationException # Login/auth failures
├── AuthorizationException  # Permission denials
├── ModelNotFoundException  # Missing resources
└── PaymentException        # Payment failures
```

### Error Logging
- All errors logged to `/storage/logs/`
- Production errors to Sentry (optional)
- Cleared weekly (configurable)

---

## Scalability Considerations

### Horizontal Scaling
- Stateless application design
- Database replication
- Load balancing
- Distributed caching (Redis)
- Session storage in database

### Vertical Scaling
- Query optimization
- Database indexing
- Eager loading relationships
- Pagination for large datasets
- Asset minification

---

## Technology Decisions

| Decision | Rationale |
|----------|-----------|
| Laravel 11 | Modern PHP, excellent ecosystem |
| MySQL | Reliable, ACID-compliant RDBMS |
| Blade Templates | Built-in templating, zero learning curve |
| Sanctum | Simple token-based API auth |
| Spatie Permission | Role-based access control |
| Stripe | Industry-leading payment processor |
| Twilio | Reliable SMS service |

---

## Development Workflow

### Feature Development
```
1. Create migration (schema change)
2. Create model (business logic)
3. Create controller (request handling)
4. Create routes
5. Create views/templates
6. Write tests
7. Code review
8. Merge to main
```

### Git Workflow
```
main (production)
└─ develop (staging)
   ├─ feature/product-search
   ├─ feature/payment-gateway
   ├─ bugfix/cart-calculation
   └─ ...
```

---

## Monitoring & Logging

### Application Logs
- Location: `/storage/logs/`
- Level: debug, info, warning, error, critical
- Retention: 14 days (configurable)

### Metrics to Monitor
- HTTP response times
- Database query performance
- Payment success rate
- Error rates
- User activity
- Inventory alerts

---

## Deployment Pipeline

```
1. Code commit to GitHub
2. Automated tests run
3. Code quality checks
4. Build artifacts created
5. Deploy to staging
6. Manual QA testing
7. Deploy to production
8. Monitor for errors
9. Rollback if needed
```

---

## Future Enhancements

- [ ] GraphQL API
- [ ] Elasticsearch for advanced search
- [ ] Microservices architecture
- [ ] Machine learning recommendations
- [ ] Real-time chat support
- [ ] Progressive Web App (PWA)
- [ ] Social media integration
- [ ] Advanced analytics dashboard

---

**Architecture Version**: 1.0  
**Last Updated**: May 2026
