<?php
session_start();
require_once '../../../config/database.php';
header('Content-Type: application/json');

// التحقق من صلاحيات المدير
if (!isset($_SESSION['user_role']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'supervisor')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'غير مصرح']);
    exit;
}

try {
    // إجمالي المستخدمين
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM users WHERE status = 'active'");
    $users = $stmt->fetch()['total'];

    // الفاحصين
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM users WHERE role = 'inspector' AND status = 'active'");
    $inspectors = $stmt->fetch()['total'];

    // العملاء
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM users WHERE role = 'client' AND status = 'active'");
    $clients = $stmt->fetch()['total'];

    // حالات الفحص
    $stats = $pdo->query("
        SELECT
            COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
            COUNT(CASE WHEN status = 'assigned' THEN 1 END) as assigned,
            COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as in_progress,
            COUNT(CASE WHEN status = 'pending_review' THEN 1 END) as pending_review,
            COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed,
            COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled
        FROM inspection_requests_new
    ")->fetch();

    // بيانات أداء الفاحصين
    $inspectorStats = $pdo->query("
        SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) as full_name, COUNT(ir.id) as inspections_count
        FROM users u
        LEFT JOIN inspection_requests_new ir ON ir.inspector_id = u.id
        WHERE u.role = 'inspector' AND u.status = 'active'
        GROUP BY u.id
        ORDER BY inspections_count DESC
        LIMIT 5
    ")->fetchAll(PDO::FETCH_ASSOC);

    // إجمالي الفحوصات
    $totalInspections = $stats['pending'] + $stats['assigned'] + $stats['in_progress'] + $stats['pending_review'] + $stats['completed'] + $stats['cancelled'];

    // إجمالي الإيرادات (يمكنك تعديل هذا حسب منطقك)
    $totalRevenue = 150000; // قيمة افتراضية

    // إجمالي المراكز (يمكنك تعديل هذا حسب منطقك)
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM centers WHERE status = 'active'");
    $activeCenters = $stmt->fetch()['total'];

    echo json_encode([
        'success' => true,
        'data' => [
            'total_users' => $users,
            'total_inspectors' => $inspectors,
            'total_clients' => $clients,
            'total_inspections' => $totalInspections,
            'total_revenue' => $totalRevenue,
            'active_centers' => $activeCenters,
            'pending_inspections' => $stats['pending'],
            'assigned_inspections' => $stats['assigned'],
            'in_progress_inspections' => $stats['in_progress'] + $stats['pending_review'],
            'completed_inspections' => $stats['completed'],
            'cancelled_inspections' => $stats['cancelled'],
            'inspector_stats' => $inspectorStats
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'خطأ في الخادم: ' . $e->getMessage()]);
}
?>