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

# Admin Analytics

> Platform statistics and analytics for administrators

## Get System Statistics

```
GET /admin/dashboard_stats.php
```

Retrieve comprehensive platform statistics for the admin dashboard.

### Query Parameters

<ParamField query="admin_id" type="integer" required>
  Administrator ID
</ParamField>

### Response

<ResponseField name="success" type="boolean">
  Request success status
</ResponseField>

<ResponseField name="stats" type="object">
  System-wide statistics

  <Expandable title="stats structure">
    <ResponseField name="total_usuarios" type="integer">
      Total registered users (all types)
    </ResponseField>

    <ResponseField name="total_conductores" type="integer">
      Total registered drivers
    </ResponseField>

    <ResponseField name="conductores_activos" type="integer">
      Active drivers currently online
    </ResponseField>

    <ResponseField name="conductores_pendientes" type="integer">
      Drivers pending approval
    </ResponseField>

    <ResponseField name="viajes_hoy" type="integer">
      Trips completed today
    </ResponseField>

    <ResponseField name="viajes_total" type="integer">
      Total trips completed (all time)
    </ResponseField>

    <ResponseField name="viajes_activos" type="integer">
      Currently active trips
    </ResponseField>

    <ResponseField name="ganancia_hoy" type="number">
      Platform revenue today (COP)
    </ResponseField>

    <ResponseField name="ganancia_total" type="number">
      Total platform revenue (COP)
    </ResponseField>

    <ResponseField name="usuarios_nuevos_hoy" type="integer">
      New user registrations today
    </ResponseField>

    <ResponseField name="usuarios_nuevos_semana" type="integer">
      New user registrations this week
    </ResponseField>
  </Expandable>
</ResponseField>

### Request Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://76.13.114.194/admin/dashboard_stats.php?admin_id=1" \
    -H "Accept: application/json"
  ```

  ```dart Dart theme={null}
  Future<Map<String, dynamic>> getSystemStats(int adminId) async {
    final response = await http.get(
      Uri.parse('https://76.13.114.194/admin/dashboard_stats.php?admin_id=$adminId'),
      headers: {'Accept': 'application/json'},
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      return data['stats'];
    }
    throw Exception('Failed to load statistics');
  }
  ```

  ```javascript JavaScript theme={null}
  async function getSystemStats(adminId) {
    const response = await fetch(
      `https://76.13.114.194/admin/dashboard_stats.php?admin_id=${adminId}`,
      { headers: { 'Accept': 'application/json' } }
    );
    
    const data = await response.json();
    return data.stats;
  }
  ```
</CodeGroup>

### Response Example

```json Success theme={null}
{
  "success": true,
  "stats": {
    "total_usuarios": 2547,
    "total_conductores": 342,
    "conductores_activos": 125,
    "conductores_pendientes": 18,
    "viajes_hoy": 487,
    "viajes_total": 45623,
    "viajes_activos": 23,
    "ganancia_hoy": 9740000,
    "ganancia_total": 912800000,
    "usuarios_nuevos_hoy": 15,
    "usuarios_nuevos_semana": 84
  }
}
```

***

## Dashboard Metrics

### Key Performance Indicators (KPIs)

<CardGroup cols={2}>
  <Card title="User Growth" icon="users">
    Track new user registrations over time
  </Card>

  <Card title="Trip Volume" icon="car">
    Monitor daily and total trip counts
  </Card>

  <Card title="Revenue" icon="dollar-sign">
    Track platform earnings and commissions
  </Card>

  <Card title="Driver Availability" icon="user-tie">
    Monitor active drivers and approval queue
  </Card>
</CardGroup>

### Calculate Metrics

```dart theme={null}
class AdminAnalytics {
  final Map<String, dynamic> stats;
  
  AdminAnalytics(this.stats);
  
  // Driver approval rate
  double get driverApprovalRate {
    final total = stats['total_conductores'] as int;
    final pending = stats['conductores_pendientes'] as int;
    if (total == 0) return 0.0;
    return ((total - pending) / total) * 100;
  }
  
  // Average trips per driver today
  double get avgTripsPerDriverToday {
    final trips = stats['viajes_hoy'] as int;
    final drivers = stats['conductores_activos'] as int;
    if (drivers == 0) return 0.0;
    return trips / drivers;
  }
  
  // Average revenue per trip today
  double get avgRevenuePerTripToday {
    final revenue = stats['ganancia_hoy'] as num;
    final trips = stats['viajes_hoy'] as int;
    if (trips == 0) return 0.0;
    return revenue / trips;
  }
  
  // Driver utilization rate
  double get driverUtilizationRate {
    final active = stats['conductores_activos'] as int;
    final total = stats['total_conductores'] as int;
    if (total == 0) return 0.0;
    return (active / total) * 100;
  }
}
```

***

## Revenue Analytics

### Platform Commission

Calculate platform earnings from trip commissions:

```dart theme={null}
class RevenueCalculator {
  static const double platformCommissionRate = 0.15; // 15%
  
  double calculatePlatformRevenue(double tripPrice) {
    return tripPrice * platformCommissionRate;
  }
  
  double calculateDriverEarnings(double tripPrice) {
    return tripPrice * (1 - platformCommissionRate);
  }
}
```

### Revenue Breakdown

```dart theme={null}
class RevenueBreakdown {
  final double totalRevenue;
  final double platformCommission;
  final double driverPayouts;
  final int tripCount;
  
  RevenueBreakdown({
    required this.totalRevenue,
    required this.platformCommission,
    required this.driverPayouts,
    required this.tripCount,
  });
  
  double get avgTripValue => tripCount > 0 ? totalRevenue / tripCount : 0.0;
  double get avgCommissionPerTrip => tripCount > 0 ? platformCommission / tripCount : 0.0;
}
```

***

## User Analytics

### User Growth Tracking

```dart theme={null}
class UserGrowthMetrics {
  int calculateGrowthRate(int newUsers, int totalUsers) {
    if (totalUsers == 0) return 0;
    return ((newUsers / totalUsers) * 100).round();
  }
  
  double calculateRetentionRate(
    int activeUsersThisWeek,
    int activeUsersLastWeek,
  ) {
    if (activeUsersLastWeek == 0) return 0.0;
    return (activeUsersThisWeek / activeUsersLastWeek) * 100;
  }
}
```

***

## Trip Analytics

### Trip Status Distribution

```dart theme={null}
class TripAnalytics {
  Map<String, int> getTripStatusDistribution(List<Trip> trips) {
    final distribution = <String, int>{};
    
    for (final trip in trips) {
      distribution[trip.estado] = (distribution[trip.estado] ?? 0) + 1;
    }
    
    return distribution;
  }
  
  double calculateCompletionRate(List<Trip> trips) {
    if (trips.isEmpty) return 0.0;
    final completed = trips.where((t) => t.estado == 'completado').length;
    return (completed / trips.length) * 100;
  }
  
  double calculateCancellationRate(List<Trip> trips) {
    if (trips.isEmpty) return 0.0;
    final cancelled = trips.where((t) => t.estado == 'cancelado').length;
    return (cancelled / trips.length) * 100;
  }
}
```

***

## Time Series Data

<Note>
  For historical trend analysis, consider implementing dedicated analytics endpoints that return time-series data for charting and visualization.
</Note>

### Example Time Series Query

```dart theme={null}
Future<List<Map<String, dynamic>>> getTripsOverTime(
  DateTime startDate,
  DateTime endDate,
  String interval, // 'day', 'week', 'month'
) async {
  // Implementation would query database for trip counts
  // grouped by the specified time interval
  return [];
}
```

***

## Export Data

<Note>
  For data export functionality, implement endpoints that generate CSV or Excel files with filtered data ranges.
</Note>

***

## Error Responses

<ResponseField name="403" type="Forbidden">
  Insufficient admin privileges
</ResponseField>

<ResponseField name="500" type="Internal Server Error">
  Server error retrieving statistics
</ResponseField>

## See Also

* [User Management](/api/admin/users) - Manage users
* [Driver Management](/api/admin/drivers) - Manage driver approvals
* [Trip History](/api/trips/history) - View trip data
