<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Video;
use App\Models\Gallery;
use App\Models\Ad;
use App\Models\Reader;
use App\Models\Poll;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        // Estatísticas
        $stats = [
            'posts_today' => Post::whereDate('created_at', today())->count(),
            'posts_total' => Post::count(),
            'posts_published' => Post::where('status', 'published')->count(),
            'videos_total' => Video::count(),
            'galleries_total' => Gallery::count(),
            'ads_active' => Ad::where('status', 'active')->count(),
            'readers_total' => Reader::where('status', 'active')->count(),
            'polls_active' => Poll::where('status', 'active')->count(),
        ];

        // Últimas notícias
        $recentPosts = Post::with(['user', 'category'])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Últimos leitores
        $recentReaders = Reader::orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Top matérias (mais visualizadas)
        $topPosts = Post::where('status', 'published')
            ->orderBy('views', 'desc')
            ->limit(5)
            ->get();

        // Acessos diários (últimos 7 dias)
        $dailyViews = Post::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('SUM(views) as total_views')
            )
            ->where('created_at', '>=', now()->subDays(7))
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->get();

        return view('admin.dashboard.index', compact(
            'stats',
            'recentPosts',
            'recentReaders',
            'topPosts',
            'dailyViews'
        ));
    }
}

