<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\User;
use App\Models\Product;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        return response()->json(['success'=>true,'data'=>[
            'total_revenue'   => Order::where('payment_status','paid')->sum('total'),
            'total_orders'    => Order::count(),
            'total_customers' => User::where('role','customer')->count(),
            'total_products'  => Product::active()->count(),
            'pending_orders'  => Order::where('status','pending')->count(),
            'low_stock'       => Product::where('stock','<=',10)->where('stock','>',0)->count(),
            'out_of_stock'    => Product::where('stock',0)->count(),
            'recent_orders'   => Order::with('user','items')->latest()->take(5)->get(),
            'top_products'    => DB::table('order_items')->select('product_id',DB::raw('SUM(quantity) as sold'))->groupBy('product_id')->orderByDesc('sold')->take(5)->get(),
            'monthly_revenue' => Order::where('payment_status','paid')->selectRaw('MONTH(created_at) as month,SUM(total) as revenue')->groupByRaw('MONTH(created_at)')->get(),
        ]]);
    }
}
