<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardStatsController extends Controller
{
    public function index(): JsonResponse
    {
        // 1. Core Statistics
        $totalUsers = User::count();
        $totalPosts = Post::count();
        $pendingPosts = Post::where('status', 'pending')->count();
        $totalViews = Post::sum('views_count');

        // 2. Recent Activity (Posts)
        $recentPosts = Post::with('user:id,name,avatar')
            ->select('id', 'title', 'status', 'user_id', 'created_at', 'views_count')
            ->latest()
            ->take(5)
            ->get();

        // 3. Recent Users
        $recentUsers = User::select('id', 'name', 'email', 'avatar', 'created_at', 'role')
            ->latest()
            ->take(5)
            ->get();

        // 4. Chart Data (Posts per day for last 7 days)
        $chartData = Post::selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->where('created_at', '>=', now()->subDays(7))
            ->groupBy('date')
            ->orderBy('date', 'ASC')
            ->get()
            ->map(function ($item) {
                return [
                    'date' => Carbon::parse($item->date)->format('M d'), // e.g. "Jan 10"
                    'count' => $item->count,
                ];
            });

        return response()->json([
            'stats' => [
                'total_users' => $totalUsers,
                'total_posts' => $totalPosts,
                'pending_posts' => $pendingPosts,
                'total_views' => (int) $totalViews,
            ],
            'activity' => [
                'recent_posts' => $recentPosts,
                'recent_users' => $recentUsers,
            ],
            'chart' => $chartData
        ]);
    }
}