<?php

namespace App\Http\Controllers\CommunityManager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Newsletter;
use App\Models\Post;
use App\Models\Review;
use App\Models\User;
use App\Models\Notification;
use App\Models\Badge;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardController extends Controller
{
    /**
     * Afficher dashboard community manager
     */
    public function index()
    {
        $user = auth()->user();
        
        // Vérifier permissions
        if (!in_array($user->role, ['community_manager', 'marketing', 'admin', 'sub_admin', 'super_admin'])) {
            abort(403, 'Accès community manager refusé');
        }

        // Période filtrée
        $startDate = request('start_date') 
            ? Carbon::parse(request('start_date'))->startOfDay()
            : now()->startOfMonth();
        $endDate = request('end_date')
            ? Carbon::parse(request('end_date'))->endOfDay()
            : now()->endOfMonth();

        // KPIs Community
        $stats = [
            // Utilisateurs
            'total_users' => User::count(),
            'active_users' => User::where('is_active', true)->count(),
            'banned_users' => User::where('is_banned', true)->count(),
            'new_users_period' => User::whereBetween('created_at', [$startDate, $endDate])->count(),
            
            // Contenu
            'total_posts' => Post::count(),
            'posts_period' => Post::whereBetween('created_at', [$startDate, $endDate])->count(),
            'featured_posts' => Post::where('featured', true)->count(),
            
            // Avis & Critiques
            'pending_reviews' => Review::where('status', 'pending')->count(),
            'approved_reviews' => Review::where('status', 'approved')->count(),
            'rejected_reviews' => Review::where('status', 'rejected')->count(),
            'total_reviews' => Review::count(),
            
            // Newsletters
            'newsletter_subscribers' => Newsletter::where('is_active', true)->count(),
            'newsletters_sent_period' => Newsletter::whereBetween('created_at', [$startDate, $endDate])->count(),
            
            // Notifications
            'notifications_sent_period' => Notification::whereBetween('created_at', [$startDate, $endDate])->count(),
            'unread_notifications' => Notification::where('read_at', null)->count(),
            
            // Badges & Récompenses
            'total_badges' => Badge::count(),
            'active_badges' => Badge::where('is_active', true)->count(),
        ];

        // Avis en attente d'approbation
        $pendingReviews = Review::where('status', 'pending')
            ->with(['user', 'product'])
            ->latest()
            ->limit(15)
            ->get();
        
        // Posts récents
        $recentPosts = Post::with('author')
            ->latest()
            ->limit(10)
            ->get();
        
        // Utilisateurs récemment bannis
        $bannedUsers = User::where('is_banned', true)
            ->orderBy('updated_at', 'desc')
            ->limit(10)
            ->get();
        
        // Utilisateurs actifs (activité récente)
        $activeUsers = $this->getMostActiveUsers($startDate, $endDate);
        
        // Badges les plus attribués
        $topBadges = $this->getTopBadges();
        
        // Statistiques engagement
        $engagementStats = [
            'posts_per_day' => round(Post::whereBetween('created_at', [$startDate, $endDate])->count() / max(1, $startDate->diffInDays($endDate)), 2),
            'reviews_per_day' => round(Review::whereBetween('created_at', [$startDate, $endDate])->count() / max(1, $startDate->diffInDays($endDate)), 2),
            'avg_review_rating' => Review::where('status', 'approved')->avg('rating') ?? 0,
        ];
        
        // Graphique activité utilisateurs (7 jours)
        $activityChart = User::where('created_at', '>=', now()->subDays(7))
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('COUNT(*) as count'))
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return view('community.dashboard', compact(
            'stats',
            'pendingReviews',
            'recentPosts',
            'bannedUsers',
            'activeUsers',
            'topBadges',
            'engagementStats',
            'activityChart',
            'startDate',
            'endDate'
        ));
    }

    /**
     * Utilisateurs les plus actifs
     */
    private function getMostActiveUsers($startDate, $endDate)
    {
        return DB::table('user_activity_logs')
            ->join('users', 'user_activity_logs.user_id', '=', 'users.id')
            ->select('users.id', 'users.name', 'users.email',
                DB::raw('COUNT(*) as activity_count'))
            ->whereBetween('user_activity_logs.created_at', [$startDate, $endDate])
            ->groupBy('user_activity_logs.user_id')
            ->orderBy('activity_count', 'desc')
            ->limit(10)
            ->get();
    }

    /**
     * Top badges attribués
     */
    private function getTopBadges()
    {
        return DB::table('badges')
            ->join('user_badges', 'badges.id', '=', 'user_badges.badge_id')
            ->select('badges.id', 'badges.name', 'badges.slug',
                DB::raw('COUNT(*) as times_awarded'))
            ->groupBy('badges.id')
            ->orderBy('times_awarded', 'desc')
            ->limit(10)
            ->get();
    }
}
