<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use App\Models\Admin\Product;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\v1\Product\ProductAllResource;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Http\Resources\Api\v1\Product\ProductSingleResource;

class ProductController extends Controller
{
    public function __construct()
    {
        $acceptLanguage = request()->header('Accept-Language');
        app()->setLocale($acceptLanguage);
    }

    public function index(Request $request)
    {
        try {
            $filter = $request->input('filter') === 'true';

            $mainCategoryId = $request->input('main_category_id');
            $title = $request->input('title');

            $taxonomyFilters = [
                'sub_category_id' => $request->input('sub_category_id'),
                'type_id' => $request->input('type_id'),
                'option_id' => $request->input('option_id'),
                'body_id' => $request->input('body_id'),
                'material_id' => $request->input('material_id'),
                'trim_id' => $request->input('trim_id'),
                'trim_material_id' => $request->input('trim_material_id'),
                'stem_material_id' => $request->input('stem_material_id'),
                'end_id' => $request->input('end_id'),
            ];

            $taxonomyFilters = array_filter($taxonomyFilters);
            $dnValue = $request->input('dn');
            $figure = $request->input('figure');
            $impa = $request->input('impa');

            $productsQuery = Product::query();

            if ($filter && $title) {
                $productsQuery->where('title', 'like', '%' . $title . '%');
            } elseif ($filter) {
                $productsQuery->when($figure, function ($query, $figure) {
                    $query->where('dikkan_figure', $figure);
                });

                $productsQuery->when($impa, function ($query, $impa) {
                    $query->where('impa_code', $impa);
                });

                if (!empty($taxonomyFilters)) {
                    $productsQuery->whereHas('taxonomies', function ($query) use ($taxonomyFilters) {
                        $query->whereIn('taxonomy_id', $taxonomyFilters);
                    }, '=', count($taxonomyFilters));
                }

                if ($dnValue) {
                    $productsQuery->whereHas('taxonomies', function ($query) use ($dnValue) {
                        $query->where('value', $dnValue);
                    });
                }

                if ($mainCategoryId) {
                    $productsQuery->whereHas('taxonomies', function ($query) use ($mainCategoryId) {
                        $query->whereHas('parent', function ($parentQuery) use ($mainCategoryId) {
                            $parentQuery->where('id', $mainCategoryId);
                        });
                    });
                }
            }

            $products = $productsQuery->paginate(10);

            if ($products->isEmpty()) {
                return response()->json(['error' => 'No products found', 'code' => 404], 404);
            }

            return ProductAllResource::collection($products);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to retrieve products', 'code' => 500], 500);
        }
    }

    public function show($id)
    {
        try {
            $product = Product::with(['taxonomies','images'])->findOrFail($id);
            return new ProductSingleResource($product);
        } catch (ModelNotFoundException $e) {
            return response()->json(['error' => 'Product not found', 'code' => 404], 404);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to retrieve product', 'code' => 500], 500);
        }
    }
}
