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

// التحقق من الصلاحيات
if ($role !== 'admin' && $role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized access. Admin role required.']);
    exit;
}

$response = [
    'status' => 'success',
    'message' => []
];

try {
    // 1. الرحلات النشطة حالياً
    $stmt = $con->prepare("SELECT COUNT(*) FROM ride WHERE status IN ('wait', 'started', 'arrived')");
    $stmt->execute();
    $active_rides = $stmt->fetchColumn();

    // 2. السائقون المتصلون حالياً (أونلاين)
    $stmt = $con->prepare("SELECT COUNT(*) FROM car_locations WHERE status = 'on'");
    $stmt->execute();
    $online_drivers = $stmt->fetchColumn();

    // 3. إيرادات اليوم
    $stmt = $con->prepare("SELECT IFNULL(SUM(price_for_passenger), 0) FROM ride WHERE status = 'Finished' AND DATE(created_at) = CURDATE()");
    $stmt->execute();
    $revenue_today = $stmt->fetchColumn();

    // إيرادات الأمس (للمقارنة)
    $stmt = $con->prepare("SELECT IFNULL(SUM(price_for_passenger), 0) FROM ride WHERE status = 'Finished' AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
    $stmt->execute();
    $revenue_yesterday = $stmt->fetchColumn();

    // 4. شكاوى جديدة اليوم
    $stmt = $con->prepare("SELECT COUNT(*) FROM complaint WHERE DATE(date_filed) = CURDATE() AND statusComplaint = 'Open'");
    $stmt->execute();
    $new_complaints = $stmt->fetchColumn();

    // 5. رخص تنتهي هذا الشهر
    $stmt = $con->prepare("SELECT COUNT(*) FROM driver WHERE expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)");
    $stmt->execute();
    $expiring_licenses = $stmt->fetchColumn();

    $response['message'] = [
        'active_rides' => (int)$active_rides,
        'online_drivers' => (int)$online_drivers,
        'revenue_today' => (float)$revenue_today,
        'revenue_yesterday' => (float)$revenue_yesterday,
        'new_complaints' => (int)$new_complaints,
        'expiring_licenses' => (int)$expiring_licenses
    ];

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