isToday(); // 2. If not updated today, call the API (Cache once per day) if (!$isUpdatedToday) { $this->fetchAndCacheGoldPrices(); } // 3. Fetch data from our own database $goldCurrencies = GoldCurrency::all()->map(function ($currency) { return [ 'change_percent' => $currency->change_percent, 'change_value' => $currency->change_value, 'date' => $currency->updated_at->format('Y-m-d'), // Format for the DTO 'name' => $currency->name, 'name_en' => $currency->name_en, 'price' => $currency->price, 'symbol' => $currency->symbol, 'time' => $currency->updated_at->format('H:i:s'), // Format for the DTO 'time_unix' => $currency->time_unix, 'unit' => $currency->unit, ]; }); // 4. Return in the exact format your frontend expects! // We nest it inside ['gold' => ...] to match your CurrencyListBrsDto return $this->success([ 'gold' => $goldCurrencies ], 'موفق', 'لیست قیمت طلا و سکه دریافت شد.'); } /** * Private helper to fetch from the external API and save to DB */ private function fetchAndCacheGoldPrices() { try { $url = 'https://Api.BrsApi.ir/Api/Market/Gold_Currency.php?key=B727Ue3kBrbtCwHR3BmSVZKRRNF1sllp'; // Timeout after 10 seconds so the user isn't stuck waiting if the API is down $response = Http::timeout(10)->get($url); if ($response->successful()) { $data = $response->json(); if (isset($data['gold']) && is_array($data['gold'])) { foreach ($data['gold'] as $item) { // updateOrCreate uses the 'name_en' as the unique key to update existing rows GoldCurrency::updateOrCreate( ['name_en' => $item['name_en']], [ 'name' => $item['name'], 'price' => (int) $item['price'], 'change_percent' => (float) $item['change_percent'], 'change_value' => (int) $item['change_value'], 'symbol' => $item['symbol'] ?? null, 'unit' => $item['unit'] ?? null, 'time_unix' => (int) $item['time_unix'], ] ); } } } else { Log::warning('BrsApi returned an error status: ' . $response->status()); } } catch (\Exception $e) { // If the API completely dies (DNS issue, offline), we log it but don't crash. // The controller will just safely return yesterday's prices from the DB! Log::error('Failed to fetch from BrsApi: ' . $e->getMessage()); } } }