<?php

namespace App\Http\Controllers\Api;

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

class ProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Product::with(['category.parent', 'images', 'variants', 'primaryImage'])
            ->where('status', 'published');

        // Filter by Category or Subcategory
        if ($request->filled('category')) {
            $catSlug = $request->input('category');
            $category = Category::where('slug', $catSlug)->first();

            if ($category) {
                if ($category->parent_id === null) {
                    // Main category: get all subcategories + main category products
                    $subCatIds = Category::where('parent_id', $category->id)->pluck('id')->toArray();
                    $subCatIds[] = $category->id;
                    $query->whereIn('category_id', $subCatIds);
                } else {
                    $query->where('category_id', $category->id);
                }
            }
        }

        if ($request->filled('subcategory')) {
            $subSlug = $request->input('subcategory');
            $subCategory = Category::where('slug', $subSlug)->first();
            if ($subCategory) {
                $query->where('category_id', $subCategory->id);
            }
        }

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

        // Price Filters
        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'));
        }

        // Attribute Filters
        if ($request->filled('material')) {
            $query->where('material', 'like', '%' . $request->input('material') . '%');
        }
        if ($request->filled('color')) {
            $query->where('color', 'like', '%' . $request->input('color') . '%');
        }
        if ($request->filled('finish')) {
            $query->where('finish', 'like', '%' . $request->input('finish') . '%');
        }
        if ($request->filled('availability')) {
            $query->where('availability', $request->input('availability'));
        }

        // Flags
        if ($request->boolean('featured')) {
            $query->where('featured', true);
        }
        if ($request->boolean('new')) {
            $query->where('new_arrival', true);
        }
        if ($request->boolean('bestseller')) {
            $query->where('best_seller', true);
        }
        if ($request->boolean('editor_pick')) {
            $query->where('editor_pick', true);
        }

        // Sorting
        $sort = $request->input('sort', 'newest');
        switch ($sort) {
            case 'price_asc':
                $query->orderByRaw('CASE WHEN price IS NULL THEN 1 ELSE 0 END, price ASC');
                break;
            case 'price_desc':
                $query->orderBy('price', 'desc');
                break;
            case 'name_asc':
                $query->orderBy('name', 'asc');
                break;
            case 'name_desc':
                $query->orderBy('name', 'desc');
                break;
            case 'newest':
            default:
                $query->orderBy('created_at', 'desc');
                break;
        }

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

        return response()->json([
            'success' => true,
            'message' => 'Products retrieved successfully',
            'data' => ProductResource::collection($products),
            'meta' => [
                'current_page' => $products->currentPage(),
                'last_page' => $products->lastPage(),
                'per_page' => $products->perPage(),
                'total' => $products->total(),
            ],
        ]);
    }

    public function show(string $slug): JsonResponse
    {
        $product = Product::with(['category.parent', 'images', 'variants', 'reviews'])
            ->where('slug', $slug)
            ->where('status', 'published')
            ->first();

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

        return response()->json([
            'success' => true,
            'message' => 'Product details retrieved successfully',
            'data' => new ProductResource($product),
        ]);
    }

    public function featured(): JsonResponse
    {
        $products = Product::with(['category', 'images', 'primaryImage'])
            ->where('status', 'published')
            ->where('featured', true)
            ->limit(8)
            ->get();

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

    public function newArrivals(): JsonResponse
    {
        $products = Product::with(['category', 'images', 'primaryImage'])
            ->where('status', 'published')
            ->where('new_arrival', true)
            ->limit(8)
            ->get();

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

    public function bestsellers(): JsonResponse
    {
        $products = Product::with(['category', 'images', 'primaryImage'])
            ->where('status', 'published')
            ->where('best_seller', true)
            ->limit(8)
            ->get();

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