<?php

namespace App\Http\Controllers\Admin\Web;

use App\Http\Controllers\Controller;
use App\Models\FootballMatch;
use App\Models\News;
use App\Models\Poll;
use App\Models\Prediction;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class AdminDashboardController extends Controller
{
    public function index()
    {
        // Users active in the last 5 minutes (have a live session record).
        // Works because SESSION_DRIVER=database — every API request with a
        // valid Sanctum token touches the sessions table.
        // We count distinct user_id values to avoid duplicates.
        $activeNow = DB::table('sessions')
            ->whereNotNull('user_id')
            ->where('last_activity', '>=', now()->subMinutes(5)->timestamp)
            ->distinct('user_id')
            ->count('user_id');

        // Users active today (last 24 hours)
        $activeToday = DB::table('sessions')
            ->whereNotNull('user_id')
            ->where('last_activity', '>=', now()->subDay()->timestamp)
            ->distinct('user_id')
            ->count('user_id');

        $stats = [
            'total_users'       => User::where('is_banned', false)
                                       ->where('is_anonymized', false)
                                       ->where('is_admin', false)
                                       ->count(),
            'active_now'        => $activeNow,
            'active_today'      => $activeToday,
            'total_matches'     => FootballMatch::count(),
            'live_matches'      => FootballMatch::where('status', 'live')->count(),
            'upcoming_matches'  => FootballMatch::where('status', 'upcoming')->count(),
            'total_predictions' => Prediction::count(),
            'total_polls'       => Poll::count(),
            'active_polls'      => Poll::where('is_active', true)->count(),
            'total_news'        => News::where('is_published', true)->count(),
        ];

        $recentUsers = User::with('favoriteTeam')
            ->where('is_banned', false)
            ->orderByDesc('created_at')
            ->limit(5)
            ->get();

        $upcomingMatches = FootballMatch::with(['homeTeam', 'awayTeam'])
            ->where('status', 'upcoming')
            ->orderBy('match_datetime')
            ->limit(5)
            ->get();

        $liveMatches = FootballMatch::with(['homeTeam', 'awayTeam'])
            ->where('status', 'live')
            ->get();

        return view('admin.dashboard', compact(
            'stats', 'recentUsers', 'upcomingMatches', 'liveMatches'
        ));
    }
}
