<?php

namespace App\Http\Controllers;

use App\Models\BlogPost;
use App\Models\BlogComment;
use App\Models\ForumTopic;
use App\Models\ForumPost;
use App\Models\User;
use App\Models\LibraryContent;
use App\Models\InterviewAttempt;
use App\Models\ChatMessage;
use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class StatisticsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    // Public statistics page
    public function index(): View
    {
        $stats = $this->getPublicStats();
        return view('statistics.index', compact('stats'));
    }

    // Admin dashboard with full stats
    public function adminDashboard(): View
    {
        $this->authorize('admin');
        $stats = $this->getFullStats();
        return view('admin.dashboard', compact('stats'));
    }

    // API endpoint for chart data
    public function chartData(Request $request): JsonResponse
    {
        $period = $request->get('period', '30');
        $days = min((int) $period, 365);
        $from = now()->subDays($days);

        $userGrowth = User::where('created_at', '>=', $from)
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $blogPosts = BlogPost::where('created_at', '>=', $from)
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $forumTopics = ForumTopic::where('created_at', '>=', $from)
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return response()->json([
            'user_growth' => $userGrowth,
            'blog_posts' => $blogPosts,
            'forum_topics' => $forumTopics,
        ]);
    }

    protected function getPublicStats(): array
    {
        return [
            'total_users' => User::count(),
            'total_blog_posts' => BlogPost::where('status', 'published')->count(),
            'total_forum_topics' => ForumTopic::count(),
            'total_library_contents' => LibraryContent::where('is_published', true)->count(),
            'total_comments' => BlogComment::count(),
            'total_forum_replies' => ForumPost::count(),
        ];
    }

    protected function getFullStats(): array
    {
        $today = now()->startOfDay();
        $thisWeek = now()->subWeek();
        $thisMonth = now()->subMonth();

        return [
            // Users
            'total_users' => User::count(),
            'new_users_today' => User::where('created_at', '>=', $today)->count(),
            'new_users_week' => User::where('created_at', '>=', $thisWeek)->count(),
            'new_users_month' => User::where('created_at', '>=', $thisMonth)->count(),
            'admin_users' => User::where('role', 'admin')->count(),
            'moderator_users' => User::where('role', 'moderator')->count(),

            // Blog
            'total_blog_posts' => BlogPost::count(),
            'published_blog_posts' => BlogPost::where('status', 'published')->count(),
            'draft_blog_posts' => BlogPost::where('status', 'draft')->count(),
            'total_comments' => BlogComment::count(),
            'comments_today' => BlogComment::where('created_at', '>=', $today)->count(),

            // Forum
            'total_forum_topics' => ForumTopic::count(),
            'total_forum_replies' => ForumPost::count(),
            'forum_today' => ForumTopic::where('created_at', '>=', $today)->count(),

            // Library
            'total_library_contents' => LibraryContent::count(),
            'published_library' => LibraryContent::where('is_published', true)->count(),

            // Interview
            'total_interview_attempts' => InterviewAttempt::count(),
            'interview_today' => InterviewAttempt::where('created_at', '>=', $today)->count(),

            // Chat
            'total_chat_messages' => ChatMessage::count(),
            'chat_today' => ChatMessage::where('created_at', '>=', $today)->count(),

            // Notifications
            'total_notifications' => Notification::count(),
            'unread_notifications' => Notification::where('is_read', false)->count(),

            // Recent activity
            'recent_users' => User::latest()->take(5)->get(),
            'recent_posts' => BlogPost::with('user')->latest()->take(5)->get(),
            'recent_comments' => BlogComment::with('user', 'post')->latest()->take(5)->get(),
        ];
    }

    protected function authorize(string $role): void
    {
        if (!auth()->check() || auth()->user()->role !== $role) {
            abort(403);
        }
    }
}
