> ## 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.

# Environment Configuration

> Configure Viax for different environments (development, staging, production) with proper API endpoints and settings

# Environment Configuration

Viax supports multiple environments with different backend configurations. Learn how to switch between local development, staging, and production setups.

## Environment Types

<CardGroup cols={3}>
  <Card title="Development" icon="laptop-code" color="#4CAF50">
    **Local development with Laragon**

    * Backend: localhost
    * Database: Local MySQL
    * Hot reload enabled
    * Debug mode active
  </Card>

  <Card title="Staging" icon="flask" color="#FF9800">
    **Testing environment**

    * Backend: Staging server
    * Database: Test database
    * Mirrors production
    * Safe for testing
  </Card>

  <Card title="Production" icon="rocket" color="#2196F3">
    **Live environment**

    * Backend: VPS (76.13.114.194)
    * Database: Production MySQL
    * Optimized builds
    * Real user data
  </Card>
</CardGroup>

***

## Configuration Architecture

Viax uses a centralized configuration system that automatically detects the environment based on the API base URL.

### AppConfig Class

**Location:** `lib/src/core/config/app_config.dart`

```dart theme={null}
class AppConfig {
  // Environment variable for API URL
  static const String _envBaseUrl = String.fromEnvironment(
    'API_BASE_URL',
    defaultValue: 'http://76.13.114.194', // Production by default
  );
  
  // Auto-detect environment
  static Environment get environment {
    if (_envBaseUrl.contains('localhost') || 
        _envBaseUrl.contains('10.0.2.2') || 
        _envBaseUrl.contains('192.168.')) {
      return Environment.development;
    } else if (_envBaseUrl.contains('staging')) {
      return Environment.staging;
    }
    return Environment.production;
  }
  
  // Base URL getter
  static String get baseUrl => _envBaseUrl;
  
  // Microservice endpoints
  static String get authServiceUrl => '$baseUrl/auth';
  static String get conductorServiceUrl => '$baseUrl/conductor';
  static String get adminServiceUrl => '$baseUrl/admin';
  static String get userServiceUrl => '$baseUrl/user';
}
```

***

## Environment Setup

### Development (Local)

<Tabs>
  <Tab title="Android Emulator">
    The Android emulator maps `localhost` to `10.0.2.2`.

    ```bash theme={null}
    flutter run --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend
    ```

    **Full URL structure:**

    * Base: `http://10.0.2.2/viax/backend`
    * Auth: `http://10.0.2.2/viax/backend/auth`
    * Conductor: `http://10.0.2.2/viax/backend/conductor`
    * User: `http://10.0.2.2/viax/backend/user`
    * Admin: `http://10.0.2.2/viax/backend/admin`
  </Tab>

  <Tab title="Physical Device">
    Use your computer's local IP address.

    **Find your IP:**

    <CodeGroup>
      ```bash Windows theme={null}
      ipconfig
      # Look for "IPv4 Address" under your network adapter
      # Example: 192.168.1.100
      ```

      ```bash macOS/Linux theme={null}
      ifconfig
      # or
      ip addr show
      # Look for inet under your network interface
      # Example: 192.168.1.100
      ```
    </CodeGroup>

    **Run with your IP:**

    ```bash theme={null}
    flutter run --dart-define=API_BASE_URL=http://192.168.1.100/viax/backend
    ```

    <Warning>
      Ensure your phone and computer are on the same WiFi network.
    </Warning>
  </Tab>

  <Tab title="iOS Simulator">
    iOS Simulator can use `localhost` directly.

    ```bash theme={null}
    flutter run --dart-define=API_BASE_URL=http://localhost/viax/backend
    ```
  </Tab>

  <Tab title="Web Browser">
    ```bash theme={null}
    flutter run -d chrome --dart-define=API_BASE_URL=http://localhost/viax/backend
    ```
  </Tab>
</Tabs>

### Staging (Optional)

If you have a staging server:

```bash theme={null}
flutter run --dart-define=API_BASE_URL=https://staging.viax.com
```

### Production

Connect to the live VPS server:

```bash theme={null}
# Default - no need to specify
flutter run

# Or explicitly
flutter run --dart-define=API_BASE_URL=http://76.13.114.194
```

***

## Backend Configuration

### Development Backend (Laragon)

**File:** `backend/config/database.php`

```php theme={null}
<?php
class Database {
    private $host = 'localhost';
    private $db_name = 'viax';
    private $username = 'root';
    private $password = 'root';  // Default Laragon password
    private $conn;
    
    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host=" . $this->host . ";dbname=" . $this->db_name,
                $this->username,
                $this->password
            );
            $this->conn->exec("set names utf8");
        } catch(PDOException $exception) {
            echo "Connection error: " . $exception->getMessage();
        }
        return $this->conn;
    }
}
?>
```

### Production Backend (VPS)

**File:** `backend/config/database.php`

```php theme={null}
<?php
class Database {
    private $host = 'localhost';  // MySQL on same VPS
    private $db_name = 'viax_production';
    private $username = 'viax_user';
    private $password = 'YOUR_SECURE_PASSWORD_HERE';
    private $conn;
    
    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO(
                "mysql:host=" . $this->host . ";dbname=" . $this->db_name,
                $this->username,
                $this->password
            );
            $this->conn->exec("set names utf8mb4");
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $exception) {
            error_log("DB Connection error: " . $exception->getMessage());
            // Don't expose details in production
            throw new Exception("Database connection failed");
        }
        return $this->conn;
    }
}
?>
```

***

## Environment Variables

### Flutter Environment Variables

Viax supports custom configuration through Dart defines:

```bash theme={null}
flutter run \
  --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend \
  --dart-define=MAPBOX_ACCESS_TOKEN=pk.your_token_here \
  --dart-define=TOMTOM_API_KEY=your_key_here
```

**Available Variables:**

<Tabs>
  <Tab title="API Configuration">
    ```bash theme={null}
    # Backend URL
    API_BASE_URL=http://76.13.114.194

    # Website URL for sharing
    WEBSITE_URL=https://viaxcol.online
    ```
  </Tab>

  <Tab title="Map Services">
    ```bash theme={null}
    # Mapbox (for map tiles and routing)
    MAPBOX_ACCESS_TOKEN=pk.eyJ1Ijoi...

    # TomTom (for traffic data)
    TOMTOM_API_KEY=your_api_key_here
    ```
  </Tab>

  <Tab title="Feature Flags">
    ```bash theme={null}
    # Enable/disable features
    ENABLE_ANALYTICS=true
    ENABLE_CRASH_REPORTING=true
    ENABLE_OFFLINE_MODE=false
    ```
  </Tab>
</Tabs>

### Environment File (Recommended)

Create configuration files for different environments:

**`config/dev.env`:**

```bash theme={null}
API_BASE_URL=http://10.0.2.2/viax/backend
ENABLE_DEBUG_LOGS=true
ENABLE_ANALYTICS=false
```

**`config/prod.env`:**

```bash theme={null}
API_BASE_URL=http://76.13.114.194
ENABLE_DEBUG_LOGS=false
ENABLE_ANALYTICS=true
```

**Use with scripts:**

```bash theme={null}
# Load and run
source config/dev.env && flutter run --dart-define=API_BASE_URL=$API_BASE_URL
```

***

## VS Code Launch Configurations

Create `.vscode/launch.json` for easy environment switching:

```json theme={null}
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Viax (Development)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://10.0.2.2/viax/backend",
        "--dart-define=ENABLE_DEBUG_LOGS=true"
      ]
    },
    {
      "name": "Viax (Production)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://76.13.114.194",
        "--dart-define=ENABLE_DEBUG_LOGS=false"
      ]
    },
    {
      "name": "Viax (Physical Device - Update IP)",
      "request": "launch",
      "type": "dart",
      "program": "lib/main.dart",
      "args": [
        "--dart-define=API_BASE_URL=http://192.168.1.100/viax/backend"
      ]
    }
  ]
}
```

**Usage:**

1. Press F5 in VS Code
2. Select configuration from dropdown
3. App launches with selected environment

***

## Testing Configuration

### Verify Backend Connection

Create a simple test to verify your configuration:

```dart theme={null}
// test/config_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:viax/src/core/config/app_config.dart';

void main() {
  test('Backend health check', () async {
    final url = '${AppConfig.baseUrl}/health.php';
    
    try {
      final response = await http.get(Uri.parse(url));
      
      expect(response.statusCode, 200);
      expect(response.body, contains('status'));
      
      print('✅ Backend connected: $url');
      print('Response: ${response.body}');
    } catch (e) {
      fail('❌ Backend connection failed: $e');
    }
  });
  
  test('Environment detection', () {
    print('Current environment: ${AppConfig.environment}');
    print('Base URL: ${AppConfig.baseUrl}');
    print('Auth Service: ${AppConfig.authServiceUrl}');
    
    expect(AppConfig.baseUrl, isNotEmpty);
  });
}
```

**Run test:**

```bash theme={null}
flutter test test/config_test.dart
```

### Manual Health Check

Test backend endpoints directly:

<CodeGroup>
  ```bash Local theme={null}
  curl http://localhost/viax/backend/health.php

  # Expected response:
  {"status":"ok","timestamp":"2024-11-01 10:30:00"}
  ```

  ```bash Production theme={null}
  curl http://76.13.114.194/health.php

  # Expected response:
  {"status":"ok","timestamp":"2024-11-01 10:30:00"}
  ```
</CodeGroup>

***

## URL Structure Reference

### Complete URL Mapping

<Tabs>
  <Tab title="Development (Emulator)">
    | Service             | URL                                                         |
    | ------------------- | ----------------------------------------------------------- |
    | **Base**            | `http://10.0.2.2/viax/backend`                              |
    | **Health**          | `http://10.0.2.2/viax/backend/health.php`                   |
    | **Auth Login**      | `http://10.0.2.2/viax/backend/auth/login.php`               |
    | **Auth Register**   | `http://10.0.2.2/viax/backend/auth/register.php`            |
    | **User Profile**    | `http://10.0.2.2/viax/backend/user/get_profile.php`         |
    | **Driver Profile**  | `http://10.0.2.2/viax/backend/conductor/get_profile.php`    |
    | **Create Trip**     | `http://10.0.2.2/viax/backend/user/create_trip_request.php` |
    | **Admin Dashboard** | `http://10.0.2.2/viax/backend/admin/dashboard_stats.php`    |
  </Tab>

  <Tab title="Production">
    | Service             | URL                                                 |
    | ------------------- | --------------------------------------------------- |
    | **Base**            | `http://76.13.114.194`                              |
    | **Health**          | `http://76.13.114.194/health.php`                   |
    | **Auth Login**      | `http://76.13.114.194/auth/login.php`               |
    | **Auth Register**   | `http://76.13.114.194/auth/register.php`            |
    | **User Profile**    | `http://76.13.114.194/user/get_profile.php`         |
    | **Driver Profile**  | `http://76.13.114.194/conductor/get_profile.php`    |
    | **Create Trip**     | `http://76.13.114.194/user/create_trip_request.php` |
    | **Admin Dashboard** | `http://76.13.114.194/admin/dashboard_stats.php`    |
  </Tab>
</Tabs>

***

## Build Configurations

### Development Build

```bash theme={null}
# Debug build with hot reload
flutter run \
  --dart-define=API_BASE_URL=http://10.0.2.2/viax/backend \
  --debug
```

### Staging Build

```bash theme={null}
# Profile build for performance testing
flutter build apk \
  --dart-define=API_BASE_URL=https://staging.viax.com \
  --profile
```

### Production Build

<CodeGroup>
  ```bash Android APK theme={null}
  flutter build apk \
    --dart-define=API_BASE_URL=http://76.13.114.194 \
    --release

  # Output: build/app/outputs/flutter-apk/app-release.apk
  ```

  ```bash Android App Bundle theme={null}
  flutter build appbundle \
    --dart-define=API_BASE_URL=http://76.13.114.194 \
    --release

  # Output: build/app/outputs/bundle/release/app-release.aab
  ```

  ```bash iOS theme={null}
  flutter build ios \
    --dart-define=API_BASE_URL=http://76.13.114.194 \
    --release
  ```
</CodeGroup>

***

## Environment-Specific Features

### Debug Mode Features

```dart theme={null}
import 'package:flutter/foundation.dart';
import 'package:viax/src/core/config/app_config.dart';

class DebugFeatures {
  static bool get isDebugMode => kDebugMode;
  static bool get isDevelopment => 
    AppConfig.environment == Environment.development;
  
  static void logApiCall(String endpoint, Map<String, dynamic> params) {
    if (isDebugMode) {
      print('🌐 API Call: $endpoint');
      print('Parameters: $params');
    }
  }
  
  static void logError(String message, [dynamic error, StackTrace? stack]) {
    if (isDebugMode) {
      print('❌ Error: $message');
      if (error != null) print('Details: $error');
      if (stack != null) print('Stack: $stack');
    }
  }
}
```

### Analytics Control

```dart theme={null}
class AppConfig {
  // ... existing code ...
  
  static bool get enableAnalytics {
    return environment == Environment.production;
  }
  
  static bool get enableCrashReporting {
    return environment == Environment.production;
  }
  
  static Duration get connectionTimeout {
    switch (environment) {
      case Environment.development:
        return Duration(seconds: 60); // Longer for debugging
      case Environment.staging:
        return Duration(seconds: 30);
      case Environment.production:
        return Duration(seconds: 15);
    }
  }
}
```

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Connection Refused (Emulator)">
    **Problem:** Can't connect to `localhost` from Android emulator

    **Solution:**

    * Use `10.0.2.2` instead of `localhost`
    * Verify Laragon/backend is running
    * Check firewall settings

    ```bash theme={null}
    # Test from emulator terminal (adb shell)
    curl http://10.0.2.2/viax/backend/health.php
    ```
  </Accordion>

  <Accordion title="Connection Refused (Physical Device)">
    **Problem:** Can't connect using local IP

    **Solution:**

    * Verify same WiFi network
    * Check IP address is correct
    * Disable firewall temporarily to test
    * Use explicit IP, not hostname

    ```bash theme={null}
    # Ping from device
    ping 192.168.1.100
    ```
  </Accordion>

  <Accordion title="Environment Not Detected">
    **Problem:** App using wrong environment

    **Solution:**

    * Verify `--dart-define` syntax
    * Check for typos in URL
    * Print environment in app:

    ```dart theme={null}
    print('Environment: ${AppConfig.environment}');
    print('Base URL: ${AppConfig.baseUrl}');
    ```
  </Accordion>

  <Accordion title="Cached Old Configuration">
    **Problem:** App still using old base URL

    **Solution:**

    ```bash theme={null}
    # Clean and rebuild
    flutter clean
    flutter pub get
    flutter run --dart-define=API_BASE_URL=your_new_url
    ```
  </Accordion>
</AccordionGroup>

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Never Hardcode URLs" icon="ban">
    Always use `AppConfig.baseUrl` instead of hardcoded URLs in your code.
  </Card>

  <Card title="Use Launch Configs" icon="rocket">
    Set up VS Code launch configurations for quick environment switching.
  </Card>

  <Card title="Test All Environments" icon="vial">
    Test features in development before deploying to production.
  </Card>

  <Card title="Secure Production" icon="lock">
    Use HTTPS, strong passwords, and proper authentication in production.
  </Card>
</CardGroup>

<Check>
  **Configuration Complete!** You can now switch between environments seamlessly and configure Viax for any deployment scenario.
</Check>
