<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        // 1. Aggregate Stats
        $totalPosts = $user->posts()->count();
        $totalViews = $user->posts()->sum('views_count');
        
        // Calculate Total Comments received on user's posts
        $totalComments = $user->posts()->withCount('comments')->get()->sum('comments_count');

        // 2. Chart Data: Posts created in the last 7 days
        $chartData = collect(range(6, 0))->map(function ($daysAgo) use ($user) {
            $date = Carbon::now()->subDays($daysAgo);
            return [
                'name' => $date->format('D'), // Mon, Tue...
                'full_date' => $date->format('Y-m-d'),
                'value' => $user->posts()
                                ->whereDate('created_at', $date)
                                ->count()
            ];
        });

        // 3. Recent Activity (Latest 5 posts)
        $recentActivity = $user->posts()
            ->with(['category:id,name'])
            ->select('id', 'title', 'status', 'created_at', 'views_count', 'slug')
            ->latest()
            ->take(5)
            ->get();

        return Inertia::render('Dashboard', [
            'stats' => [
                'total_posts' => $totalPosts,
                'total_views' => $totalViews,
                'total_comments' => $totalComments,
            ],
            'chartData' => $chartData,
            'recentActivity' => $recentActivity
        ]);
    }
}