isToday(); // 2. If not updated today, call the API if (!$isUpdatedToday) { $this->fetchAndCacheGoldPrices(); } // 3. Fetch data from our own database $goldCurrencies = GoldCurrency::all(); // 4. Debug check: If it is STILL empty, the API failed and we have no backup data yet. if ($goldCurrencies->isEmpty()) { return $this->failed(null, 'ارتباط با سرور قیمت‌ها برقرار نشد. لطفا بعدا تلاش کنید.'); } // 5. Map the data $mappedCurrencies = $goldCurrencies->map(function ($currency) { return [ 'change_percent' => $currency->change_percent, 'change_value' => $currency->change_value, 'date' => $currency->updated_at->format('Y-m-d'), 'name' => $currency->name, 'name_en' => $currency->name_en, 'price' => $currency->price, 'symbol' => $currency->symbol, 'time' => $currency->updated_at->format('H:i:s'), 'time_unix' => $currency->time_unix, 'unit' => $currency->unit, ]; }); return $this->success([ 'gold' => $mappedCurrencies ], 'موفق', 'لیست قیمت طلا و سکه دریافت شد.'); } /** * Private helper to fetch from the external API and save to DB */ private function fetchAndCacheGoldPrices() { try { $url = 'https://BrsApi.ir/Api/Market/Gold_Currency.php?key=B727Ue3kBrbtCwHR3BmSVZKRRNF1sllp'; // FIX: Added withoutVerifying() for Iranian SSL issues and a User-Agent to bypass firewalls $response = Http::withoutVerifying() ->withHeaders([ 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept' => 'application/json', ]) ->timeout(15) ->get($url); if ($response->successful()) { $data = $response->json(); if (isset($data['gold']) && is_array($data['gold'])) { foreach ($data['gold'] as $item) { 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() . ' - ' . $response->body()); } } catch (\Exception $e) { Log::error('Failed to fetch from BrsApi: ' . $e->getMessage()); } } }