<?php  namespace App\Services\ProductSpecs;  use App\Models\Product; use App\Models\SpecsCategory; use App\Models\ProductSpecsItemValue;  class ProductSpecs { 	public static function createSpecsCategoriesAndProductValues(array $specs_values, array $specs_categories, Product $product): void 	{ 		$categories = SpecsCategory::includes()->whereIn('id', $specs_categories)->get(); 		$product->specsCategories()->attach($specs_categories); 		$data = [];  		foreach ($categories as $category) { 			$specs = $category->specs ?? [];  			foreach ($specs as $spec) { 				$data[] = new ProductSpecsItemValue([ 					'name' => $specs_values[$spec->id], 					'specs_item_id' => $spec->id, 				]); 			} 		}  		$product->values()->saveMany($data); 	}  	public static function removeProductSpecsCategoryItems(array $category, Product $product): void 	{ 		$product->specsCategories()->detach($category); 		// find Specs of the category and then delete this products values of those specs 		$categories = SpecsCategory::whereIn('id', $category)->first(); 		$specsIds = $categories->specs->pluck('id')->all();  		$product->values()->whereIn('specs_item_id', $specsIds)->delete(); 	}  	public static function getSpecsByCategory(Product $product): array 	{ 		$specsByCategory = []; 		$langs = getCurrentLanguages();  		$product_specs = $product->values;  		foreach ($langs as $lang) { 			$specsByCategory[$lang] = $product->specsCategories->map(function ($category) use ($product_specs) { 				$specs = $category->specs->map(function ($spec) use ($product_specs) { 					$spec->value = $product_specs->firstWhere('specs_item_id', $spec->id)->name ?? '';  					return $spec; 				});  				$category->setSpecs($specs);  				return $category; 			}); 		}  		return $specsByCategory; 	}  	public static function getSpecsByCategoryAPI(Product $product, string $language = 'en'): array 	{ 		$specsByCategory = []; 		$product_specs = $product->values;  		foreach ($product->specsCategories as $category) { 			$categorySpecs = [];  			foreach ($category->specs as $spec) { 				$product_spec = $product_specs->firstWhere('specs_item_id', $spec->id); 				$specValue = getTranslation($product_spec?->name, $language) ?? '';  				if ($specValue != '') { 					$categorySpecs[] = [ 						'id' => $spec->id, 						'name' => getTranslation($spec->name, $language), 						'value' => $specValue, 					]; 				} 			} 			$specsByCategory[] = [ 				'id' => $category->id, 				'name' => $category->name, 				'specs' => $categorySpecs, 			]; 		}  		return $specsByCategory; 	} }