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

class AnalyticsController extends Controller
{
    public function overview()
    {
        return response()->json(['success'=>true,'data'=>[
            'revenue_this_month' => Order::where('payment_status','paid')->whereMonth('created_at',now()->month)->sum('total'),
            'orders_this_month'  => Order::whereMonth('created_at',now()->month)->count(),
            'new_customers'      => User::where('role','customer')->whereMonth('created_at',now()->month)->count(),
            'avg_order_value'    => Order::where('payment_status','paid')->avg('total'),
        ]]);
    }
    public function sales()
    {
        $monthly = Order::where('payment_status','paid')->selectRaw('YEAR(created_at) as year,MONTH(created_at) as month,SUM(total) as revenue,COUNT(*) as orders')->groupByRaw('YEAR(created_at),MONTH(created_at)')->orderByRaw('YEAR(created_at),MONTH(created_at)')->get();
        $byCat   = DB::table('order_items')->join('products','products.id','=','order_items.product_id')->join('categories','categories.id','=','products.category_id')->selectRaw('categories.name,SUM(order_items.quantity * order_items.price) as revenue')->groupBy('categories.name')->get();
        return response()->json(['success'=>true,'data'=>['monthly'=>$monthly,'by_category'=>$byCat]]);
    }
}
