<?php
namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use App\Models\Vendor;
use App\Models\WithdrawRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class AdminDashboardController extends Controller
{
    public function index(): JsonResponse
    {
        $totalRevenue = Order::where('payment_status', 'paid')->sum('total');
        $totalCommission = Order::where('payment_status', 'paid')->sum('commission_amount');
        $totalOrders = Order::count();
        $pendingOrders = Order::where('status', 'pending')->count();
        $totalVendors = Vendor::count();
        $pendingVendors = Vendor::where('status', 'pending')->count();
        $totalProducts = Product::count();
        $totalUsers = User::role('customer')->count();
        $pendingWithdrawals = WithdrawRequest::where('status', 'pending')->sum('amount');

        $recentOrders = Order::with(['user:id,name,email', 'vendor:id,store_name'])
            ->latest()
            ->limit(10)
            ->get(['id', 'order_number', 'user_id', 'vendor_id', 'total', 'status', 'payment_status', 'created_at']);

        $recentVendors = Vendor::with('user:id,name,email')
            ->latest()
            ->limit(5)
            ->get(['id', 'user_id', 'store_name', 'status', 'subscription_plan', 'created_at']);

        $monthlyRevenue = Order::where('payment_status', 'paid')
            ->where('created_at', '>=', now()->subMonths(6))
            ->select(
                DB::raw('YEAR(created_at) as year'),
                DB::raw('MONTH(created_at) as month'),
                DB::raw('SUM(total) as revenue'),
                DB::raw('SUM(commission_amount) as commission'),
                DB::raw('COUNT(*) as orders')
            )
            ->groupBy('year', 'month')
            ->orderBy('year')->orderBy('month')
            ->get();

        return response()->json([
            'stats' => [
                'total_revenue'        => round($totalRevenue, 2),
                'total_commission'     => round($totalCommission, 2),
                'total_orders'         => $totalOrders,
                'pending_orders'       => $pendingOrders,
                'total_vendors'        => $totalVendors,
                'pending_vendors'      => $pendingVendors,
                'total_products'       => $totalProducts,
                'total_customers'      => $totalUsers,
                'pending_withdrawals'  => round($pendingWithdrawals, 2),
            ],
            'recent_orders'   => $recentOrders,
            'recent_vendors'  => $recentVendors,
            'monthly_revenue' => $monthlyRevenue,
        ]);
    }
}
