config->usesEtehadiePricing(); } public function apiUrl(): string { $url = trim((string) $this->config->getString( 'etehadie_api_url', (string) config('price_providers.etehadie_api_url', 'http://109.122.246.48:4949/api/free') )); return $url !== '' ? $url : 'http://109.122.246.48:4949/api/free'; } /** کلید محصول در پاسخ API اتحادیه (همان price_method گلد علی) */ public function priceKey(): string { $key = trim((string) $this->config->getString( 'price_method', (string) config('price_providers.price_method', '') )); return $key; } /** * @return array{price: int, raw: array|null} */ public function fetchMainGramPrice(): array { if (!$this->isEnabled() && $this->priceKey() === '') { return ['price' => 0, 'raw' => null]; } try { $prices = Http::withoutVerifying() ->timeout(20) ->get($this->apiUrl()) ->json(); if (!is_array($prices)) { return ['price' => 0, 'raw' => null]; } $key = $this->priceKey(); $collection = collect($prices); $row = $key !== '' ? $collection->firstWhere('key', $key) : $collection->first(); if (empty($row)) { return ['price' => 0, 'raw' => null]; } $base = (float) ($row['price'] ?? 0); $profit = (float) ($row['profit'] ?? 0); $gramPrice = (int) round($base / 10 + $profit); return ['price' => $gramPrice, 'raw' => $row]; } catch (\Throwable $e) { Log::warning('Etehadie price fetch failed', ['message' => $e->getMessage()]); return ['price' => 0, 'raw' => null]; } } /** @return array>|null */ public function fetchPriceList(): ?array { try { $prices = Http::withoutVerifying() ->timeout(20) ->get($this->apiUrl()) ->json(); return is_array($prices) ? $prices : null; } catch (\Throwable $e) { Log::warning('Etehadie price list fetch failed', ['message' => $e->getMessage()]); return null; } } public function syncProductsFromApi(): bool { $prices = $this->fetchPriceList(); if ($prices === null) { return false; } $products = \App\Models\Product::with([])->whereNotNull('reading_method')->get(); $collection = collect($prices); $copper = null; $dollar = null; foreach ($products as $product) { $RPrice = $collection->firstWhere('key', $product->reading_method); if (empty($RPrice)) { continue; } if (($RPrice['name'] ?? '') === 'TGJU فلز مس') { $copper = ($RPrice['price'] ?? 0) + ($RPrice['profit'] ?? 0); } if (($RPrice['name'] ?? '') === 'TGJU دلار') { $dollar = ($RPrice['price'] ?? 0) + ($RPrice['profit'] ?? 0); } if (($RPrice['name'] ?? '') === 'گلد دات ای از آبشده - رسمی - نقد فردا') { $RPrice['price'] = ($RPrice['price'] ?? 0) / 4.3318; } ProductPriceService::syncFromReference( $product, (int) $RPrice['price'], (int) ($RPrice['profit'] ?? 0) ); } if ($copper !== null && $dollar !== null) { $cp = ($copper / 1000000) * $dollar; $copperProduct = \App\Models\Product::find(33); if ($copperProduct) { ProductPriceService::syncFromReference($copperProduct, (int) round($cp), 0); } } return true; } }