<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    if (!$conn) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    // إحصائيات المستخدمين
    $usersQuery = "SELECT COUNT(*) as total FROM users";
    $usersStmt = $conn->query($usersQuery);
    $users = $usersStmt->fetch(PDO::FETCH_ASSOC);
    
    // إحصائيات الفحوصات
    $inspectionsQuery = "SELECT 
                            COUNT(*) as total,
                            COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
                            COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as in_progress,
                            COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed,
                            COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled
                         FROM inspection_requests";
    $inspectionsStmt = $conn->query($inspectionsQuery);
    $inspections = $inspectionsStmt->fetch(PDO::FETCH_ASSOC);
    
    // الإيرادات (من المكتملة فقط)
    $revenueQuery = "SELECT COALESCE(SUM(total_amount), 0) as total FROM inspection_requests WHERE status = 'completed'";
    $revenueStmt = $conn->query($revenueQuery);
    $revenue = $revenueStmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'totalUsers' => (int)$users['total'],
            'totalInspections' => (int)$inspections['total'],
            'pendingInspections' => (int)$inspections['pending'],
            'inProgressInspections' => (int)$inspections['in_progress'],
            'completedInspections' => (int)$inspections['completed'],
            'cancelledInspections' => (int)$inspections['cancelled'],
            'totalRevenue' => (float)$revenue['total']
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>