<?php
// Admin/v2/analytics/growth.php
require_once __DIR__ . '/../../../connect.php';

if ($role !== 'admin' && $role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized access.']);
    exit;
}

try {
    // نمو الركاب لآخر 30 يوم
    $stmt = $con->prepare("
        SELECT DATE(created_at) as date, COUNT(*) as new_passengers
        FROM passengers 
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
    ");
    $stmt->execute();
    $passenger_growth = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // نمو السائقين لآخر 30 يوم
    $stmt = $con->prepare("
        SELECT DATE(created_at) as date, COUNT(*) as new_drivers
        FROM driver 
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
    ");
    $stmt->execute();
    $driver_growth = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // إجمالي الأعداد الحالية
    $stmt = $con->prepare("SELECT COUNT(*) FROM passengers");
    $stmt->execute();
    $total_passengers = $stmt->fetchColumn();

    $stmt = $con->prepare("SELECT COUNT(*) FROM driver");
    $stmt->execute();
    $total_drivers = $stmt->fetchColumn();

    echo json_encode([
        'status' => 'success',
        'data' => [
            'passenger_daily' => $passenger_growth,
            'driver_daily' => $driver_growth,
            'totals' => [
                'passengers' => (int)$total_passengers,
                'drivers' => (int)$total_drivers
            ]
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
