<?php
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get top users by followers
    $query = "SELECT u.id, u.name, u.phone, u.profile_picture,
              (SELECT COUNT(*) FROM user_followers WHERE following_id = u.id) as total_followers,
              (SELECT COUNT(*) FROM user_followers WHERE follower_id = u.id) as total_following,
              (SELECT COUNT(*) FROM post_likes pl JOIN posts p ON pl.post_id = p.id WHERE p.user_id = u.id) as total_likes,
              (SELECT COUNT(*) FROM posts WHERE user_id = u.id) as posts_count
              FROM users u
              WHERE u.role = 'user'
              ORDER BY total_followers DESC
              LIMIT 50";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $top_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get recent followers activity
    $query = "SELECT uf.*, 
              u1.name as follower_name, u1.profile_picture as follower_pic,
              u2.name as following_name, u2.profile_picture as following_pic
              FROM user_followers uf
              JOIN users u1 ON uf.follower_id = u1.id
              JOIN users u2 ON uf.following_id = u2.id
              ORDER BY uf.created_at DESC
              LIMIT 20";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $recent_follows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $top_users = [];
    $recent_follows = [];
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>المتابعين - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">إحصائيات المتابعين</h1>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $total_followers = !empty($top_users) ? array_sum(array_column($top_users, 'total_followers')) : 0;
                $total_posts = !empty($top_users) ? array_sum(array_column($top_users, 'posts_count')) : 0;
                $total_likes = !empty($top_users) ? array_sum(array_column($top_users, 'total_likes')) : 0;
            ?>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي المستخدمين</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($top_users); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-users text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي المتابعات</p>
                            <p class="text-2xl font-bold text-purple-600"><?php echo number_format($total_followers); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-user-plus text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي المنشورات</p>
                            <p class="text-2xl font-bold text-teal-600"><?php echo number_format($total_posts); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-teal-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-newspaper text-teal-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي الإعجابات</p>
                            <p class="text-2xl font-bold text-red-600"><?php echo number_format($total_likes); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-heart text-red-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- Top Users -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="px-6 py-5 border-b border-gray-200">
                        <h3 class="text-xl font-semibold text-gray-900">المستخدمون الأكثر متابعة</h3>
                    </div>
                    <div class="p-6">
                        <?php if (!empty($top_users)): ?>
                            <div class="space-y-3">
                                <?php foreach (array_slice($top_users, 0, 10) as $index => $user): ?>
                                    <div class="flex items-center gap-4 p-3 bg-gray-50 rounded-lg">
                                        <div class="flex items-center gap-3 flex-1">
                                            <div class="text-lg font-bold text-gray-400">#<?php echo $index + 1; ?></div>
                                            <?php if (!empty($user['profile_picture'])): ?>
                                                <img src="../../<?php echo htmlspecialchars($user['profile_picture']); ?>" 
                                                     alt="<?php echo htmlspecialchars($user['name']); ?>" 
                                                     class="w-12 h-12 object-cover rounded-full">
                                            <?php else: ?>
                                                <div class="w-12 h-12 bg-gradient-to-br from-purple-400 to-pink-400 rounded-full flex items-center justify-center">
                                                    <span class="text-white font-bold"><?php echo mb_substr($user['name'], 0, 1); ?></span>
                                                </div>
                                            <?php endif; ?>
                                            <div>
                                                <h4 class="font-semibold text-gray-900"><?php echo htmlspecialchars($user['name']); ?></h4>
                                                <p class="text-xs text-gray-600"><?php echo $user['posts_count']; ?> منشور</p>
                                            </div>
                                        </div>
                                        <div class="text-center">
                                            <div class="flex items-center gap-1 text-purple-600">
                                                <i class="fas fa-users"></i>
                                                <span class="font-bold"><?php echo number_format($user['total_followers']); ?></span>
                                            </div>
                                            <p class="text-xs text-gray-500 mt-1"><?php echo number_format($user['total_likes']); ?> إعجاب</p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-center text-gray-500 py-8">لا توجد بيانات متابعين</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent Follows -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="px-6 py-5 border-b border-gray-200">
                        <h3 class="text-xl font-semibold text-gray-900">آخر المتابعات</h3>
                    </div>
                    <div class="p-6">
                        <?php if (!empty($recent_follows)): ?>
                            <div class="space-y-3">
                                <?php foreach ($recent_follows as $follow): ?>
                                    <div class="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                                        <?php if (!empty($follow['follower_pic'])): ?>
                                            <img src="../../<?php echo htmlspecialchars($follow['follower_pic']); ?>" 
                                                 alt="<?php echo htmlspecialchars($follow['follower_name']); ?>" 
                                                 class="w-10 h-10 object-cover rounded-full">
                                        <?php else: ?>
                                            <div class="w-10 h-10 bg-gradient-to-br from-blue-400 to-purple-400 rounded-full flex items-center justify-center">
                                                <span class="text-white text-sm font-bold"><?php echo mb_substr($follow['follower_name'], 0, 1); ?></span>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <div class="flex-1">
                                            <p class="text-sm">
                                                <span class="font-semibold text-gray-900"><?php echo htmlspecialchars($follow['follower_name']); ?></span>
                                                <span class="text-gray-600"> يتابع </span>
                                                <span class="font-semibold text-gray-900"><?php echo htmlspecialchars($follow['following_name']); ?></span>
                                            </p>
                                            <p class="text-xs text-gray-500"><?php echo date('Y-m-d H:i', strtotime($follow['created_at'])); ?></p>
                                        </div>
                                        
                                        <?php if (!empty($follow['following_pic'])): ?>
                                            <img src="../../<?php echo htmlspecialchars($follow['following_pic']); ?>" 
                                                 alt="<?php echo htmlspecialchars($follow['following_name']); ?>" 
                                                 class="w-10 h-10 object-cover rounded-full">
                                        <?php else: ?>
                                            <div class="w-10 h-10 bg-gradient-to-br from-pink-400 to-red-400 rounded-full flex items-center justify-center">
                                                <span class="text-white text-sm font-bold"><?php echo mb_substr($follow['following_name'], 0, 1); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-center text-gray-500 py-8">لا توجد متابعات حديثة</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
