<?php

namespace App\Services\Admin;

use App\Models\Category;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DashboardService
{
    public function getStats(): array
    {
        return [
            'total_products' => Product::count(),
            'active_products' => Product::where('is_active', true)->count(),
            'total_categories' => Category::count(),
            'active_categories' => Category::where('is_active', true)->count(),
            'total_orders' => Order::count(),
            'today_orders' => Order::whereDate('created_at', today())->count(),
            'pending_orders' => Order::where('status', 'pending')->count(),
            'total_customers' => User::where('role', 'customer')->count(),
            'total_revenue' => Order::where('status', '!=', 'cancelled')->sum('total'),
            'today_revenue' => Order::whereDate('created_at', today())
                ->where('status', '!=', 'cancelled')
                ->sum('total'),
            'month_revenue' => Order::whereMonth('created_at', now()->month)
                ->whereYear('created_at', now()->year)
                ->where('status', '!=', 'cancelled')
                ->sum('total'),
            'low_stock_items' => ProductVariant::whereColumn('stock_quantity', '<=', 'min_stock_level')
                ->where('is_active', true)
                ->count(),
        ];
    }

    public function getRecentOrders(int $limit = 10)
    {
        return Order::with(['user', 'items.product'])
            ->latest()
            ->limit($limit)
            ->get();
    }

    public function getLowStockProducts(int $limit = 10)
    {
        return ProductVariant::with('product')
            ->whereColumn('stock_quantity', '<=', 'min_stock_level')
            ->where('is_active', true)
            ->orderBy('stock_quantity')
            ->limit($limit)
            ->get();
    }

    public function getRevenueChart(int $days = 30): array
    {
        $startDate = Carbon::now()->subDays($days);
        
        $revenue = Order::select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('SUM(total) as revenue'),
                DB::raw('COUNT(*) as orders')
            )
            ->where('created_at', '>=', $startDate)
            ->where('status', '!=', 'cancelled')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return [
            'labels' => $revenue->pluck('date')->toArray(),
            'revenue' => $revenue->pluck('revenue')->toArray(),
            'orders' => $revenue->pluck('orders')->toArray(),
        ];
    }

    public function getOrderStatusDistribution(): array
    {
        return Order::select('status', DB::raw('COUNT(*) as count'))
            ->groupBy('status')
            ->pluck('count', 'status')
            ->toArray();
    }
}
