> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Braian551/viax/llms.txt
> Use this file to discover all available pages before exploring further.

# System Architecture

> Comprehensive overview of Viax's technical architecture, technology stack, and system design

# System Architecture

Viax is built with a **modular monolith architecture** that follows Clean Architecture principles, preparing the platform for future scalability and potential migration to microservices.

## Architecture Overview

```mermaid theme={null}
graph TB
    subgraph "Client Layer"
        A[Flutter Mobile App]
    end
    
    subgraph "API Layer"
        B[PHP REST API]
        C[API Gateway Future]
    end
    
    subgraph "Service Layer"
        D[Auth Service]
        E[Conductor Service]
        F[User Service]
        G[Admin Service]
        H[Map Service]
    end
    
    subgraph "Data Layer"
        I[MySQL Database]
        J[File Storage]
    end
    
    subgraph "External APIs"
        K[Mapbox API]
        L[TomTom API]
        M[Nominatim API]
        N[Gmail SMTP]
    end
    
    A --> B
    B --> D
    B --> E
    B --> F
    B --> G
    B --> H
    D --> I
    E --> I
    F --> I
    G --> I
    H --> K
    H --> L
    H --> M
    D --> N
    E --> J
```

## Technology Stack

### Frontend Technology

<Tabs>
  <Tab title="Flutter Framework">
    **Flutter SDK 3.35.3+**

    * Cross-platform development (iOS & Android)
    * Hot reload for rapid development
    * Native performance with compiled code
    * Rich widget library
    * Material Design 3 implementation

    **Key Dependencies:**

    ```yaml theme={null}
    provider: ^6.1.3              # State management
    flutter_map: ^8.2.2           # Interactive maps
    geolocator: ^14.0.2           # GPS location
    geocoding: ^4.0.0             # Address conversion
    http: ^1.1.0                  # HTTP client
    shared_preferences: ^2.2.2    # Local storage
    ```
  </Tab>

  <Tab title="State Management">
    **Provider Pattern**

    * Simple and intuitive
    * Built-in to Flutter
    * Minimal boilerplate
    * Testable architecture

    **Key Providers:**

    * `AuthProvider` - Authentication state
    * `UserProvider` - User profile data
    * `ConductorProfileProvider` - Driver information
    * `TripProvider` - Trip management
    * `MapProvider` - Location and routing
  </Tab>

  <Tab title="UI/UX">
    **Design System:**

    * Material Design 3
    * Custom color scheme (Blue #2196F3)
    * Consistent spacing and typography
    * Responsive layouts
    * Accessibility support

    **Components:**

    * Reusable widgets
    * Custom animations
    * Shimmer loading effects
    * Bottom sheets and dialogs
    * Professional onboarding
  </Tab>
</Tabs>

### Backend Technology

<CodeGroup>
  ```php Server Stack theme={null}
  // PHP 8.3+ with modern features
  - PHP 8.3+
  - Apache/Nginx web server
  - Composer dependency management
  - PSR-4 autoloading
  - RESTful API design
  ```

  ```sql Database theme={null}
  -- MySQL 8.0+ with InnoDB engine
  - MySQL 8.0+
  - InnoDB storage engine
  - utf8mb4 character set
  - Foreign key constraints
  - Indexed queries for performance
  ```

  ```php Dependencies theme={null}
  // composer.json
  {
    "require": {
      "phpmailer/phpmailer": "^6.9",
      "firebase/php-jwt": "^6.10"
    }
  }
  ```
</CodeGroup>

### External Services

<CardGroup cols={2}>
  <Card title="Mapbox" icon="map">
    **Maps & Routing**

    * Map tiles: 100,000/month free
    * Directions API: 100,000/month free
    * Geocoding API
    * Static maps
  </Card>

  <Card title="TomTom" icon="traffic-light">
    **Traffic Data**

    * Real-time traffic: 2,500/day free
    * Route optimization
    * ETA calculation
    * Traffic flow data
  </Card>

  <Card title="Nominatim" icon="location-dot">
    **Geocoding**

    * Address to coordinates
    * Reverse geocoding
    * Unlimited free tier
    * OpenStreetMap data
  </Card>

  <Card title="Gmail SMTP" icon="envelope">
    **Email Service**

    * Email verification
    * Password reset
    * Notifications
    * PHPMailer integration
  </Card>
</CardGroup>

## System Components

### Mobile Application (Flutter)

**Directory Structure:**

```
lib/
├── src/
│   ├── core/                    # Shared functionality
│   │   ├── config/              # App configuration
│   │   ├── di/                  # Dependency injection
│   │   ├── error/               # Error handling
│   │   └── network/             # Network utilities
│   │
│   ├── features/                # Feature modules
│   │   ├── auth/                # Authentication
│   │   ├── user/                # User features
│   │   ├── conductor/           # Driver features
│   │   ├── admin/               # Admin panel
│   │   ├── company/             # Company management
│   │   ├── maps/                # Map integration
│   │   └── trips/               # Trip management
│   │
│   └── routes/                  # Navigation
└── main.dart
```

**Key Modules:**

<AccordionGroup>
  <Accordion title="Authentication Module">
    **Capabilities:**

    * User registration with validation
    * Email verification (6-digit codes)
    * Secure login/logout
    * Password reset flow
    * Session management

    **Security:**

    * Passwords hashed with bcrypt
    * Email verification required
    * Input sanitization
    * Secure token storage
  </Accordion>

  <Accordion title="Map Integration Module">
    **Features:**

    * Real-time GPS tracking
    * Interactive map display
    * Marker placement
    * Route visualization
    * Geocoding/reverse geocoding

    **Technologies:**

    * flutter\_map for rendering
    * geolocator for GPS
    * Mapbox API for tiles
    * Nominatim for geocoding
  </Accordion>

  <Accordion title="Trip Management Module">
    **User Flow:**

    1. Select pickup location
    2. Choose destination
    3. Select vehicle type
    4. View price estimate
    5. Confirm booking
    6. Track driver
    7. Complete trip

    **States:**

    * Pending (searching driver)
    * Accepted (driver assigned)
    * In Progress (trip ongoing)
    * Completed (finished)
    * Cancelled (user/driver cancelled)
  </Accordion>

  <Accordion title="Driver Module">
    **Registration:**

    * Personal information form
    * Document upload (license, vehicle)
    * Background verification
    * Admin approval workflow

    **Operations:**

    * Toggle availability
    * View nearby requests
    * Accept/decline trips
    * Navigate to pickup
    * Update location
    * Complete trips
  </Accordion>
</AccordionGroup>

### Backend API (PHP)

**Service Organization:**

```php theme={null}
backend/
├── auth/                      # Authentication service
│   ├── login.php              # User login
│   ├── register.php           # User registration
│   ├── verify_email.php       # Email verification
│   └── email_service.php      # Email sending
│
├── conductor/                 # Driver service
│   ├── get_profile.php        # Get driver profile
│   ├── update_location.php    # Update GPS location
│   ├── get_pending_requests.php  # View trip requests
│   └── accept_trip_request.php   # Accept trip
│
├── user/                      # User service
│   ├── create_trip_request.php   # Request trip
│   ├── find_nearby_drivers.php   # Find drivers
│   └── get_trip_history.php      # Trip history
│
├── admin/                     # Admin service
│   ├── dashboard_stats.php    # Dashboard metrics
│   ├── user_management.php    # Manage users
│   └── document_verification.php # Verify documents
│
├── config/                    # Configuration
│   ├── database.php           # DB connection
│   └── config.php             # App config
│
└── vendor/                    # Composer dependencies
```

**API Design Principles:**

<Steps>
  <Step title="RESTful Endpoints">
    Standard HTTP methods (GET, POST, PUT, DELETE) with resource-based URLs
  </Step>

  <Step title="JSON Responses">
    Consistent JSON format with success/error indicators and data payload
  </Step>

  <Step title="Error Handling">
    Structured error responses with codes, messages, and debugging info
  </Step>

  <Step title="Security">
    Input validation, SQL injection prevention, and authentication checks
  </Step>
</Steps>

**Example API Response:**

```json theme={null}
{
  "success": true,
  "message": "Trip request created successfully",
  "data": {
    "solicitud_id": 123,
    "estado": "pendiente",
    "precio_estimado": 12500,
    "conductores_disponibles": [
      {
        "conductor_id": 42,
        "nombre": "Carlos Rodriguez",
        "distancia_km": 2.3,
        "calificacion": 4.8,
        "tipo_vehiculo": "carro"
      }
    ]
  }
}
```

### Database Schema

**Core Entities:**

<Tabs>
  <Tab title="Users">
    ```sql theme={null}
    CREATE TABLE usuarios (
      id INT PRIMARY KEY AUTO_INCREMENT,
      nombre_completo VARCHAR(255) NOT NULL,
      email VARCHAR(255) UNIQUE NOT NULL,
      telefono VARCHAR(20),
      password_hash VARCHAR(255) NOT NULL,
      email_verificado TINYINT DEFAULT 0,
      codigo_verificacion VARCHAR(6),
      fecha_registro TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      estado ENUM('activo', 'suspendido') DEFAULT 'activo'
    );
    ```
  </Tab>

  <Tab title="Drivers">
    ```sql theme={null}
    CREATE TABLE conductores (
      id INT PRIMARY KEY AUTO_INCREMENT,
      usuario_id INT NOT NULL,
      nombre_completo VARCHAR(255) NOT NULL,
      telefono VARCHAR(20) NOT NULL,
      direccion TEXT,
      tipo_vehiculo ENUM('moto', 'carro', 'moto_carga', 'carro_carga'),
      latitud_actual DECIMAL(10, 8),
      longitud_actual DECIMAL(11, 8),
      disponibilidad TINYINT DEFAULT 0,
      estado_verificacion ENUM('pendiente', 'aprobado', 'rechazado'),
      calificacion_promedio DECIMAL(3, 2) DEFAULT 0.00,
      FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
    );
    ```
  </Tab>

  <Tab title="Trips">
    ```sql theme={null}
    CREATE TABLE solicitudes_servicio (
      id INT PRIMARY KEY AUTO_INCREMENT,
      usuario_id INT NOT NULL,
      latitud_origen DECIMAL(10, 8) NOT NULL,
      longitud_origen DECIMAL(11, 8) NOT NULL,
      direccion_origen TEXT,
      latitud_destino DECIMAL(10, 8) NOT NULL,
      longitud_destino DECIMAL(11, 8) NOT NULL,
      direccion_destino TEXT,
      tipo_servicio ENUM('viaje', 'paquete') NOT NULL,
      tipo_vehiculo ENUM('moto', 'carro', 'moto_carga', 'carro_carga'),
      distancia_km DECIMAL(6, 2),
      duracion_minutos INT,
      precio_estimado DECIMAL(10, 2),
      estado ENUM('pendiente', 'aceptada', 'en_curso', 'completada', 'cancelada'),
      fecha_solicitud TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
    );
    ```
  </Tab>

  <Tab title="Documents">
    ```sql theme={null}
    CREATE TABLE documentos_conductor (
      id INT PRIMARY KEY AUTO_INCREMENT,
      conductor_id INT NOT NULL,
      tipo_documento ENUM('licencia_conduccion', 'cedula', 'seguro_vehiculo', 'tarjeta_propiedad'),
      numero_documento VARCHAR(100),
      fecha_expedicion DATE,
      fecha_vencimiento DATE,
      ruta_archivo VARCHAR(500),
      estado_verificacion ENUM('pendiente', 'aprobado', 'rechazado'),
      observaciones TEXT,
      FOREIGN KEY (conductor_id) REFERENCES conductores(id)
    );
    ```
  </Tab>
</Tabs>

**Relationships:**

```mermaid theme={null}
erDiagram
    USUARIOS ||--o{ CONDUCTORES : "can be"
    USUARIOS ||--o{ SOLICITUDES : "creates"
    CONDUCTORES ||--o{ ASIGNACIONES : "accepts"
    CONDUCTORES ||--o{ DOCUMENTOS : "uploads"
    SOLICITUDES ||--o{ ASIGNACIONES : "assigned to"
    SOLICITUDES ||--o{ VIAJES : "becomes"
```

## Deployment Architecture

### Production Environment

<Info>
  Current production setup on VPS infrastructure
</Info>

```
VPS Server (76.13.114.194)
├── Apache Web Server
│   ├── Virtual Host: /var/www/viax/backend
│   └── PHP 8.3 Module
│
├── MySQL Server
│   ├── Database: viax_production
│   └── User: viax_user
│
├── File Storage
│   ├── uploads/documents/
│   └── logs/
│
└── SSL/TLS (Future)
    └── Let's Encrypt Certificate
```

**Deployment Flow:**

<Steps>
  <Step title="Code Preparation">
    ```bash theme={null}
    git pull origin main
    composer install --no-dev --optimize-autoloader
    ```
  </Step>

  <Step title="Database Migration">
    ```bash theme={null}
    php migrations/run_migrations.php
    ```
  </Step>

  <Step title="Permissions">
    ```bash theme={null}
    chmod 755 logs uploads
    chown -R www-data:www-data /var/www/viax/backend
    ```
  </Step>

  <Step title="Service Restart">
    ```bash theme={null}
    sudo systemctl restart apache2
    sudo systemctl restart mysql
    ```
  </Step>

  <Step title="Health Check">
    ```bash theme={null}
    curl http://76.13.114.194/health.php
    ```
  </Step>
</Steps>

### Development Environment

**Local Setup with Laragon:**

```
C:/laragon/
├── bin/
│   ├── apache/
│   ├── mysql/
│   └── php/
│
├── www/
│   └── viax/
│       └── backend/    # Backend code here
│
└── data/
    └── mysql/         # Database files
```

## Performance Considerations

### Optimization Strategies

<CardGroup cols={2}>
  <Card title="Database Indexing" icon="database">
    * Primary keys on all tables
    * Indexes on foreign keys
    * Composite indexes for queries
    * Geospatial indexes for location
  </Card>

  <Card title="Caching" icon="box">
    * Shared preferences for user data
    * In-memory driver location cache
    * API response caching
    * Static asset caching
  </Card>

  <Card title="Query Optimization" icon="gauge-high">
    * Prepared statements
    * Join optimization
    * Limit result sets
    * Pagination for large datasets
  </Card>

  <Card title="Asset Optimization" icon="image">
    * Compressed images
    * Lazy loading
    * CDN for static files (future)
    * Minified JSON responses
  </Card>
</CardGroup>

### Scalability Path

**Current Capacity:**

* \~1,000 concurrent users
* \~200 active drivers
* \~500 trips per day

**Scaling Options:**

1. **Vertical Scaling** (Short-term)
   * Upgrade VPS resources
   * Increase database memory
   * Optimize queries

2. **Horizontal Scaling** (Medium-term)
   * Load balancer
   * Multiple app servers
   * Database replication
   * Redis for caching

3. **Microservices** (Long-term)
   * Separate services
   * Container orchestration
   * Message queues
   * Service mesh

## Security Architecture

<Warning>
  Security measures implemented to protect user data and system integrity
</Warning>

### Security Layers

```
Application Security
├── Input Validation
├── SQL Injection Prevention (Prepared Statements)
├── XSS Protection
└── CSRF Tokens (Future)

Authentication & Authorization
├── Password Hashing (bcrypt)
├── Email Verification
├── Session Management
└── Role-Based Access Control

Data Security
├── HTTPS/TLS (Future)
├── Database Encryption
├── Secure File Storage
└── Audit Logging

Network Security
├── Firewall Rules
├── Rate Limiting (Future)
├── DDoS Protection
└── API Key Management
```

<Check>
  Viax's architecture is designed for reliability, performance, and future growth while maintaining clean code principles and security best practices.
</Check>
