<?php

namespace App\Services;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class DashboardStatsService
{
    public function getOverviewStats(): array
    {
        $totalProducts = Product::count();
        $totalCategories = Category::count();
        $recentImports = Product::where('created_at', '>=', now()->subDays(7))->count();

        $productsBySource = Product::select('source', DB::raw('count(*) as count'))
            ->groupBy('source')
            ->pluck('count', 'source')
            ->toArray();

        return [
            'total_products' => $totalProducts,
            'total_categories' => $totalCategories,
            'recent_imports' => $recentImports,
            'products_by_source' => $productsBySource,
        ];
    }

    public function getProductsByCategory(): array
    {
        $data = Category::withCount('products')
            ->whereHas('products')
            ->orderByDesc('products_count')
            ->limit(10)
            ->get();

        return [
            'labels' => $data->pluck('name_en')->toArray(),
            'datasets' => [
                [
                    'label' => 'Products',
                    'data' => $data->pluck('products_count')->toArray(),
                    'backgroundColor' => '#3b82f6',
                ],
            ],
        ];
    }

    public function getProductsOverTime(int $months = 6): array
    {
        $startDate = now()->subMonths($months)->startOfMonth();
        $data = [];
        $labels = [];

        for ($i = 0; $i < $months; $i++) {
            $date = now()->subMonths($months - $i - 1)->startOfMonth();
            $labels[] = $date->format('M Y');
            $count = Product::whereBetween('created_at', [
                $date->copy()->startOfMonth(),
                $date->copy()->endOfMonth(),
            ])->count();
            $data[] = $count;
        }

        return [
            'labels' => $labels,
            'datasets' => [
                [
                    'label' => 'Products Added',
                    'data' => $data,
                    'borderColor' => '#3b82f6',
                    'backgroundColor' => 'rgba(59, 130, 246, 0.1)',
                    'tension' => 0.4,
                ],
            ],
        ];
    }

    public function getProductsBySource(): array
    {
        $data = Product::select('source', DB::raw('count(*) as count'))
            ->groupBy('source')
            ->get();

        return [
            'labels' => $data->pluck('source')->map(fn ($s) => ucfirst($s))->toArray(),
            'datasets' => [
                [
                    'label' => 'Products',
                    'data' => $data->pluck('count')->toArray(),
                    'backgroundColor' => [
                        '#3b82f6',
                        '#10b981',
                        '#f59e0b',
                        '#ef4444',
                        '#8b5cf6',
                    ],
                ],
            ],
        ];
    }

    public function getPriceDistribution(): array
    {
        $ranges = [
            '0-100' => Product::whereBetween('price', [0, 100])->count(),
            '100-500' => Product::whereBetween('price', [100, 500])->count(),
            '500-1000' => Product::whereBetween('price', [500, 1000])->count(),
            '1000+' => Product::where('price', '>', 1000)->count(),
        ];

        return [
            'labels' => array_keys($ranges),
            'datasets' => [
                [
                    'label' => 'Products',
                    'data' => array_values($ranges),
                    'backgroundColor' => '#3b82f6',
                ],
            ],
        ];
    }

    public function getRecentActivity(int $limit = 10): Collection
    {
        return Product::with('category')
            ->latest()
            ->limit($limit)
            ->get();
    }
}
