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

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Product;
use App\Models\Review;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VendorDashboardController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $vendor = $request->user()->vendor;

        $totalOrders      = Order::where('vendor_id', $vendor->id)->count();
        $pendingOrders    = Order::where('vendor_id', $vendor->id)->where('status', 'pending')->count();
        $totalRevenue     = Order::where('vendor_id', $vendor->id)->where('payment_status', 'paid')->sum('vendor_earnings');
        $totalProducts    = Product::where('vendor_id', $vendor->id)->count();
        $publishedProducts = Product::where('vendor_id', $vendor->id)->where('status', 'published')->count();
        $lowStockProducts = Product::where('vendor_id', $vendor->id)->where('stock_quantity', '<=', DB::raw('low_stock_threshold'))->where('track_inventory', true)->count();
        $avgRating        = Review::whereHas('product', fn($q) => $q->where('vendor_id', $vendor->id))->where('status', 'approved')->avg('rating');

        $recentOrders = Order::with(['user:id,name,email', 'items.product:id,name'])
            ->where('vendor_id', $vendor->id)
            ->latest()->limit(10)
            ->get();

        $monthlyRevenue = Order::where('vendor_id', $vendor->id)
            ->where('payment_status', 'paid')
            ->where('created_at', '>=', now()->subMonths(6))
            ->select(
                DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'),
                DB::raw('SUM(vendor_earnings) as revenue'),
                DB::raw('COUNT(*) as orders')
            )
            ->groupBy('month')->orderBy('month')->get();

        return response()->json([
            'stats' => [
                'total_orders'      => $totalOrders,
                'pending_orders'    => $pendingOrders,
                'total_revenue'     => round((float)$totalRevenue, 2),
                'balance'           => $vendor->balance,
                'total_products'    => $totalProducts,
                'published_products' => $publishedProducts,
                'low_stock_products' => $lowStockProducts,
                'average_rating'    => round((float)$avgRating, 2),
                'subscription_plan' => $vendor->subscription_plan,
                'subscription_expires_at' => $vendor->subscription_expires_at,
                'max_products'      => $vendor->getMaxProducts(),
            ],
            'recent_orders'   => $recentOrders,
            'monthly_revenue' => $monthlyRevenue,
        ]);
    }
}
