<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Comment;
use App\Models\Source;
use App\Models\PostView;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        $ranges = [
            '5min'   => now()->subMinutes(5),
            '15min'  => now()->subMinutes(15),
            '30min'  => now()->subMinutes(30),
            '1hr'    => now()->subHour(),
            '6hr'    => now()->subHours(6),
            '12hr'   => now()->subHours(12),
            '24hr'   => now()->subDay(),
            '7days'  => now()->subDays(7),
            '30days' => now()->subDays(30),
            '1year'  => now()->subYear(),
            '2years' => now()->subYears(2),
            'all'    => null,
        ];

        $views = [];
        foreach ($ranges as $label => $from) {
            $q = PostView::query();
            if ($from) $q->where('created_at', '>=', $from);
            $views[$label] = $q->count();
        }

        // 30-day chart data
        $dailyViews = PostView::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as count')
            )
            ->where('created_at', '>=', now()->subDays(30))
            ->groupBy(DB::raw('DATE(created_at)'))
            ->orderBy('date')
            ->pluck('count', 'date')
            ->toArray();

        // Fill missing days with 0
        $chart = [];
        for ($i = 29; $i >= 0; $i--) {
            $d = now()->subDays($i)->format('Y-m-d');
            $chart[$d] = $dailyViews[$d] ?? 0;
        }

        $stats = [
            'total_posts'      => Post::count(),
            'published'        => Post::where('status', 'published')->count(),
            'total_views'      => PostView::count(),
            'comments'         => Comment::where('status', 'approved')->count(),
            'pending_comments' => Comment::where('status', 'pending')->count(),
            'sources'          => Source::where('is_active', true)->count(),
            'users'            => User::count(),
        ];

        $topPosts = Post::with('category')
            ->select('id', 'title', 'slug', 'views_count', 'comments_count', 'category_id', 'published_at')
            ->orderByDesc('views_count')
            ->limit(10)
            ->get();

        $recentPosts = Post::with(['category', 'author'])
            ->latest('published_at')
            ->limit(8)
            ->get();

        return view('admin.dashboard', compact('views', 'chart', 'stats', 'topPosts', 'recentPosts'));
    }
}
