<?php

namespace App\Http\Controllers\Api;

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

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::with('category')->active()->inStock();

        if ($request->category) {
            $slugAliases = [
                'womens-clothing'  => 'womens',
                'mens-clothing'    => 'mens',
                'kids-clothing'    => 'kids',
                'home-accessories' => 'home',
            ];
            $catSlug = $slugAliases[$request->category] ?? $request->category;
            $query->whereHas('category', fn($q) => $q->where('slug', $catSlug));
        }
        if ($request->min_price) $query->where('price', '>=', $request->min_price);
        if ($request->max_price) $query->where('price', '<=', $request->max_price);

        match($request->sort ?? 'popular') {
            'price_asc'  => $query->orderBy('price'),
            'price_desc' => $query->orderByDesc('price'),
            'newest'     => $query->latest(),
            'rating'     => $query->withAvg('reviews', 'rating')->orderByDesc('reviews_avg_rating'),
            default      => $query->orderByDesc('id'),
        };

        $products = $query->paginate($request->per_page ?? 16);

        // Add computed price fields — no hardcoded values
        $products->getCollection()->transform(fn($p) => $this->appendPriceFields($p));

        return response()->json(['success' => true, 'data' => $products]);
    }

    public function show(string $slug)
    {
        $product = Product::with(['category', 'reviews.user'])
            ->active()
            ->where('slug', $slug)
            ->firstOrFail();

        return response()->json([
            'success' => true,
            // All price fields come dynamically from DB — zero hardcoded values
            'data'    => $this->appendPriceFields($product)->toArray(),
        ]);
    }

    public function featured()
    {
        $products = Product::with('category')->active()->featured()->inStock()
            ->latest()->take(12)->get()
            ->map(fn($p) => $this->appendPriceFields($p));

        return response()->json(['success' => true, 'data' => $products]);
    }

    public function flash()
    {
        $products = Product::with('category')->active()->flashDeals()->inStock()
            ->get()->map(fn($p) => $this->appendPriceFields($p));

        return response()->json(['success' => true, 'data' => $products]);
    }

    public function search(Request $request)
    {
        $request->validate(['q' => 'required|string|min:2']);

        $products = Product::with('category')->active()
            ->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->q}%")
                  ->orWhere('description', 'like', "%{$request->q}%")
                  ->orWhere('brand', 'like', "%{$request->q}%");
            })
            ->paginate(16);

        $products->getCollection()->transform(fn($p) => $this->appendPriceFields($p));

        return response()->json(['success' => true, 'data' => $products]);
    }

    /**
     * Append computed price fields from DB — never hardcoded.
     * effective_price = sale_price if set (sale < original), else price.
     */
    private function appendPriceFields(Product $product): Product
    {
        // price = selling price (e.g. 850)
        // sale_price = original/MRP (e.g. 1200) — always higher than price when set
        $effectivePrice  = (float) $product->price;
        $hasMRP          = $product->sale_price && $product->sale_price > $product->price;
        $discountPercent = $hasMRP
            ? (int) round((($product->sale_price - $product->price) / $product->sale_price) * 100)
            : 0;

        $product->setAttribute('effective_price', $effectivePrice);
        $product->setAttribute('discount_percent', $discountPercent);
        $product->setAttribute('average_rating',
            round($product->reviews()->avg('rating') ?? 0, 1)
        );

        return $product;
    }
}
