<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductApiController extends Controller
{
    /**
     * Get a paginated list of visible products.
     */
    public function index(Request $request)
    {
        $query = Product::query()
            ->where('is_visible', true)
            ->with(['variants', 'media', 'category']);

        // Filter: Search
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($sub) use ($search) {
                $sub->where('name', 'like', '%' . $search . '%')
                    ->orWhere('sku', 'like', '%' . $search . '%')
                    ->orWhere('short_description', 'like', '%' . $search . '%');
            });
        }

        // Filter: Category ID
        if ($request->filled('category_id')) {
            $query->where('category_id', $request->input('category_id'));
        }

        // Filter: Category Slug (supports single or combined slugs split by comma/hyphen)
        if ($request->filled('category_slug')) {
            $slugInput = $request->input('category_slug');
            $slugs = preg_split('/[\s,]+|-(?!seeds|lentils|food)/', $slugInput); // Don't split "nuts-seeds", "flours-lentils", "functional-food"
            $query->whereHas('category', function ($q) use ($slugs) {
                $q->whereIn('slug', $slugs);
            });
        }

        // Filter: Featured only
        if ($request->boolean('featured')) {
            $query->where('is_featured', true);
        }

        // Filter: Price Range
        if ($request->filled('min_price')) {
            $min = floatval($request->input('min_price'));
            $query->where('price', '>=', $min);
        }
        if ($request->filled('max_price')) {
            $max = floatval($request->input('max_price'));
            $query->where('price', '<=', $max);
        }

        // Filter: Attribute Values (comma-separated value string, e.g. M,L)
        if ($request->filled('attribute_values')) {
            $vals = explode(',', $request->input('attribute_values'));
            $query->whereHas('variants', function ($q) use ($vals) {
                $q->where(function ($sub) use ($vals) {
                    foreach ($vals as $val) {
                        $sub->orWhere('options', 'like', '%"' . $val . '"%');
                    }
                });
            });
        }

        // Sorting
        $sortBy = $request->input('sortBy', 'latest');
        $query = match ($sortBy) {
            'price_asc'  => $query->orderBy('price', 'asc'),
            'price_desc' => $query->orderBy('price', 'desc'),
            'name_asc'   => $query->orderBy('name', 'asc'),
            'featured'   => $query->orderBy('is_featured', 'desc')->orderByDesc('created_at'),
            default      => $query->orderByDesc('created_at'), // latest
        };

        // Paginate
        $perPage = $request->integer('per_page', 12);
        $products = $query->paginate($perPage);

        // Transform results to append formatted image URLs
        $products->getCollection()->transform(function ($product) {
            $product->image_url = $product->getFirstMediaUrl('images', 'webp') 
                ?: ($product->getFirstMediaUrl('images') 
                ?: '/images/placeholder.jpg');
            
            $product->all_images = $product->getMedia('images')->map(function ($media) {
                return [
                    'url' => $media->getUrl(),
                    'webp' => $media->hasGeneratedConversion('webp') ? $media->getUrl('webp') : null,
                ];
            });

            return $product;
        });

        return response()->json($products);
    }

    public function show($identifier)
    {
        $cacheKey = 'product_detail_' . $identifier;
        $data = \Illuminate\Support\Facades\Cache::remember($cacheKey, 300, function () use ($identifier) {
            $product = Product::where('is_visible', true)
                ->with(['variants', 'media', 'category', 'reviews.user'])
                ->where(function ($q) use ($identifier) {
                    $q->where('id', $identifier)
                      ->orWhere('slug', $identifier);
                })
                ->firstOrFail();

            // Append formatted image fields
            $product->image_url = $product->getFirstMediaUrl('images', 'webp') 
                ?: ($product->getFirstMediaUrl('images') 
                ?: '/images/placeholder.jpg');

            $product->all_images = $product->getMedia('images')->map(function ($media) {
                return [
                    'url' => $media->getUrl(),
                    'webp' => $media->hasGeneratedConversion('webp') ? $media->getUrl('webp') : null,
                ];
            })->toArray();

            // Related products (same category, excluding current, randomized)
            $relatedProducts = Product::where('is_visible', true)
                ->where('category_id', $product->category_id)
                ->where('id', '!=', $product->id)
                ->inRandomOrder()
                ->limit(10)
                ->get();

            if ($relatedProducts->count() < 10) {
                $excludeIds = $relatedProducts->pluck('id')->push($product->id)->toArray();
                $fallbackLimit = 10 - $relatedProducts->count();
                
                $fallbackProducts = Product::where('is_visible', true)
                    ->whereNotIn('id', $excludeIds)
                    ->inRandomOrder()
                    ->limit($fallbackLimit)
                    ->get();
                    
                $relatedProducts = $relatedProducts->concat($fallbackProducts);
            }

            $relatedProducts = $relatedProducts->map(function ($relProduct) {
                $relProduct->image_url = $relProduct->getFirstMediaUrl('images', 'webp') 
                    ?: ($relProduct->getFirstMediaUrl('images') 
                    ?: '/images/placeholder.jpg');
                return $relProduct;
            });

            return [
                'product' => $product->toArray(),
                'related' => $relatedProducts->toArray(),
            ];
        });

        return response()->json($data);
    }

    public function shopFilters()
    {
        $enablePrice = \App\Models\Setting::getValue('enable_filter_by_price_range', 'on') === 'on';
        $priceMax = intval(\App\Models\Setting::getValue('price_range_max', '10000'));
        
        $enableAttr = \App\Models\Setting::getValue('enable_filter_by_attribute', 'on') === 'on';
        
        $attributesList = [];
        if ($enableAttr) {
            $attributes = \App\Models\ProductAttribute::with('values')->get();
            foreach ($attributes as $attribute) {
                $values = $attribute->values->pluck('value')->unique()->toArray();
                if (!empty($values)) {
                    $attributesList[] = [
                        'name'   => $attribute->name,
                        'values' => $values,
                    ];
                }
            }
        }
        
        // Backward compatibility fallbacks
        $firstAttr = collect($attributesList)->first();
        $attributeName = $firstAttr['name'] ?? '';
        $attributeValues = $firstAttr['values'] ?? [];
        
        return response()->json([
            'enable_price_filter' => $enablePrice,
            'price_range_max'     => $priceMax,
            'enable_attr_filter'  => $enableAttr,
            'attribute_name'      => $attributeName,
            'attribute_values'    => $attributeValues,
            'attributes'          => $attributesList,
        ]);
    }
}
