<?php

namespace App\Http\Controllers\Api;

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

class ProductApiController extends Controller
{
    /**
     * Display a paginated listing of active products with search and category filtering.
     */
    public function index(Request $request)
    {
        $query = Product::with(['category', 'images'])
            ->where(function ($q) {
                $q->where('status', 'active')
                  ->orWhere('status', 'Active')
                  ->orWhere('status', 'ACTIVE')
                  ->orWhere('status', 1)
                  ->orWhereNull('status');
            });

        // Filter by Product Type (normal vs impon)
        if ($request->filled('type') || $request->filled('product_type')) {
            $type = strtolower($request->input('type') ?? $request->input('product_type'));
            if ($type === 'impon' || $type === 'impon-product' || $type === 'impon_product') {
                $query->where(function ($q) {
                    $q->where('product_type', 'impon')
                      ->orWhereHas('category', function ($cq) {
                          $cq->where('slug', 'impon-products')
                            ->orWhere('name', 'like', '%impon%');
                      });
                });
            } elseif ($type === 'normal' || $type === 'normal-product' || $type === 'normal_product') {
                $query->where(function ($q) {
                    $q->where(function ($nq) {
                        $nq->where('product_type', 'normal')
                           ->orWhereNull('product_type')
                           ->orWhere('product_type', '');
                    })->whereDoesntHave('category', function ($cq) {
                        $cq->where('slug', 'impon-products')
                          ->orWhere('name', 'like', '%impon%');
                    });
                });
            }
        }

        // Filter by Category
        if ($request->filled('category')) {
            $category = $request->input('category');
            $catLower = strtolower($category);
            if ($catLower === 'impon products' || $catLower === 'impon-products' || $catLower === 'impon') {
                $query->where(function ($q) {
                    $q->where('product_type', 'impon')
                      ->orWhereHas('category', function ($cq) {
                          $cq->where('slug', 'impon-products')
                            ->orWhere('name', 'like', '%impon%');
                      });
                });
            } else {
                $query->whereHas('category', function ($q) use ($category) {
                    $q->where('slug', $category)
                      ->orWhere('name', 'like', "%{$category}%")
                      ->orWhere('id', $category);
                });
            }
        }

        // Search query
        if ($request->filled('search') || $request->filled('q')) {
            $search = $request->input('search') ?? $request->input('q');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('sku', 'like', "%{$search}%")
                  ->orWhere('short_description', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Filter tabs / flag parameters
        $filterParam = strtolower($request->input('filter', ''));
        if ($filterParam === 'new' || $request->boolean('featured') || $request->boolean('new_arrival') || $request->input('is_new') === '1') {
            if ($filterParam === 'new' || $request->boolean('new_arrival') || $request->input('is_new') === '1') {
                $query->where('is_new', true);
            }
        }
        if ($filterParam === 'featured' || $request->boolean('featured') || $request->input('is_featured') === '1') {
            $query->where('is_featured', true);
        }
        if ($filterParam === 'bestseller' || $filterParam === 'best_seller' || $request->boolean('best_seller') || $request->input('is_best_seller') === '1') {
            $query->where('is_best_seller', true);
        }
        if ($filterParam === 'trending' || $request->boolean('trending') || $request->input('is_trending') === '1') {
            $query->where('is_trending', true);
        }

        // Price range
        if ($request->filled('min_price')) {
            $query->where('price', '>=', (float) $request->input('min_price'));
        }
        if ($request->filled('max_price')) {
            $query->where('price', '<=', (float) $request->input('max_price'));
        }

        // Sorting
        $sort = $request->input('sort', 'latest');
        if ($sort === 'price_asc' || $sort === 'price-asc') {
            $query->orderBy('price', 'asc');
        } elseif ($sort === 'price_desc' || $sort === 'price-desc') {
            $query->orderBy('price', 'desc');
        } elseif ($sort === 'featured') {
            $query->orderBy('is_featured', 'desc')->latest();
        } else {
            $query->latest();
        }

        $perPage = (int) $request->input('per_page', 100);
        $products = $query->paginate($perPage);

        return ProductResource::collection($products);
    }

    /**
     * Display featured products.
     */
    public function featured()
    {
        $featured = Product::with(['category', 'images'])
            ->where(function ($q) {
                $q->where('status', 'active')
                  ->orWhere('status', 'Active')
                  ->orWhere('status', 'ACTIVE')
                  ->orWhere('status', 1)
                  ->orWhereNull('status');
            })
            ->where('is_featured', true)
            ->latest()
            ->take(8)
            ->get();

        return ProductResource::collection($featured);
    }

    /**
     * Display products by category slug.
     */
    public function byCategory($category)
    {
        $catLower = strtolower($category);
        $query = Product::with(['category', 'images'])
            ->where(function ($q) {
                $q->where('status', 'active')
                  ->orWhere('status', 'Active')
                  ->orWhere('status', 'ACTIVE')
                  ->orWhere('status', 1)
                  ->orWhereNull('status');
            });

        if ($catLower === 'impon-products' || $catLower === 'impon' || $catLower === 'impon products') {
            $query->where(function ($q) {
                $q->where('product_type', 'impon')
                  ->orWhereHas('category', function ($cq) {
                      $cq->where('slug', 'impon-products')
                        ->orWhere('name', 'like', '%impon%');
                  });
            });
        } else {
            $query->whereHas('category', function ($q) use ($category) {
                $q->where('slug', $category)
                  ->orWhere('name', 'like', "%{$category}%")
                  ->orWhere('id', $category);
            });
        }

        $products = $query->latest()->get();

        return ProductResource::collection($products);
    }

    /**
     * Display the specified product by ID or Slug.
     */
    public function show($identifier)
    {
        $product = Product::with(['category', 'images'])
            ->where(function ($q) use ($identifier) {
                if (is_numeric($identifier)) {
                    $q->where('id', (int) $identifier);
                } else {
                    $q->where('slug', $identifier);
                }
            })
            ->first();

        if (!$product) {
            return response()->json(['message' => 'Product not found.'], 404);
        }

        return new ProductResource($product);
    }
}
