<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AnalyticsController extends Controller
{
    /**
     * Get product analytics.
     */
    public function index(Request $request): JsonResponse
    {
        $totalProducts = Product::count();
        $inStockProducts = Product::where('in_stock', true)->count();
        $outOfStockProducts = Product::where('in_stock', false)->count();
        $onSaleProducts = Product::where('on_sale', true)->count();

        // Category distribution
        $categoryDistribution = Product::select('category', DB::raw('count(*) as count'))
            ->groupBy('category')
            ->get()
            ->mapWithKeys(function ($item) {
                return [$item->category => $item->count];
            });

        // Price statistics
        $priceStats = Product::select(
            DB::raw('AVG(price) as avg_price'),
            DB::raw('MIN(price) as min_price'),
            DB::raw('MAX(price) as max_price'),
            DB::raw('SUM(price) as total_value')
        )->first();

        // Rating statistics
        $ratingStats = Product::select(
            DB::raw('AVG(rating) as avg_rating'),
            DB::raw('MIN(rating) as min_rating'),
            DB::raw('MAX(rating) as max_rating')
        )->where('rating', '>', 0)->first();

        // Products by price range
        $priceRanges = [
            '0-50' => Product::whereBetween('price', [0, 50])->count(),
            '51-100' => Product::whereBetween('price', [51, 100])->count(),
            '101-150' => Product::whereBetween('price', [101, 150])->count(),
            '151-200' => Product::whereBetween('price', [151, 200])->count(),
            '201+' => Product::where('price', '>', 200)->count(),
        ];

        // Top rated products
        $topRatedProducts = Product::where('rating', '>', 0)
            ->orderBy('rating', 'desc')
            ->orderBy('reviews', 'desc')
            ->limit(10)
            ->get(['id', 'name', 'rating', 'reviews', 'price']);

        // Most reviewed products
        $mostReviewedProducts = Product::where('reviews', '>', 0)
            ->orderBy('reviews', 'desc')
            ->limit(10)
            ->get(['id', 'name', 'rating', 'reviews', 'price']);

        // Products with discount
        $productsWithDiscount = Product::where('original_price', '>', 0)
            ->whereColumn('original_price', '>', 'price')
            ->count();

        // Average discount percentage
        $avgDiscount = Product::where('original_price', '>', 0)
            ->whereColumn('original_price', '>', 'price')
            ->selectRaw('AVG(((original_price - price) / original_price) * 100) as avg_discount')
            ->first();

        // Recent products (last 30 days)
        $recentProducts = Product::where('created_at', '>=', now()->subDays(30))->count();

        return response()->json([
            'success' => true,
            'data' => [
                'overview' => [
                    'total_products' => $totalProducts,
                    'in_stock' => $inStockProducts,
                    'out_of_stock' => $outOfStockProducts,
                    'on_sale' => $onSaleProducts,
                    'with_discount' => $productsWithDiscount,
                    'recent_products' => $recentProducts,
                ],
                'category_distribution' => $categoryDistribution,
                'price_statistics' => [
                    'average' => round($priceStats->avg_price ?? 0, 2),
                    'minimum' => round($priceStats->min_price ?? 0, 2),
                    'maximum' => round($priceStats->max_price ?? 0, 2),
                    'total_value' => round($priceStats->total_value ?? 0, 2),
                ],
                'rating_statistics' => [
                    'average' => round($ratingStats->avg_rating ?? 0, 2),
                    'minimum' => round($ratingStats->min_rating ?? 0, 2),
                    'maximum' => round($ratingStats->max_rating ?? 0, 2),
                ],
                'price_ranges' => $priceRanges,
                'top_rated_products' => $topRatedProducts,
                'most_reviewed_products' => $mostReviewedProducts,
                'discount_analysis' => [
                    'products_with_discount' => $productsWithDiscount,
                    'average_discount_percentage' => round($avgDiscount->avg_discount ?? 0, 2),
                ],
            ],
        ]);
    }

    /**
     * Get category-specific analytics.
     */
    public function category(Request $request, string $category): JsonResponse
    {
        $products = Product::where('category', $category)->get();

        if ($products->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'No products found in this category',
            ], 404);
        }

        $priceStats = $products->map(function ($product) {
            return $product->price;
        });

        $ratingStats = $products->where('rating', '>', 0)->map(function ($product) {
            return $product->rating;
        });

        return response()->json([
            'success' => true,
            'data' => [
                'category' => $category,
                'total_products' => $products->count(),
                'in_stock' => $products->where('in_stock', true)->count(),
                'on_sale' => $products->where('on_sale', true)->count(),
                'price_statistics' => [
                    'average' => round($priceStats->avg() ?? 0, 2),
                    'minimum' => $priceStats->min() ?? 0,
                    'maximum' => $priceStats->max() ?? 0,
                ],
                'rating_statistics' => [
                    'average' => round($ratingStats->avg() ?? 0, 2),
                    'minimum' => $ratingStats->min() ?? 0,
                    'maximum' => $ratingStats->max() ?? 0,
                ],
            ],
        ]);
    }
}
