<?php
// Admin/v2/analytics/revenue.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,
            SUM(price) as total_revenue,
            SUM(price - price_for_driver) as company_profit,
            COUNT(*) as total_rides
        FROM ride 
        WHERE status = 'Finished' 
          AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
    ");
    $stmt->execute();
    $daily_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ملخص عام
    $stmt = $con->prepare("
        SELECT 
            SUM(price) as total_revenue_all,
            SUM(price - price_for_driver) as total_profit_all,
            AVG(price) as avg_ride_price
        FROM ride 
        WHERE status = 'Finished' 
          AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    ");
    $stmt->execute();
    $summary = $stmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'data' => [
            'daily' => $daily_stats,
            'summary' => $summary
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
