<?php

namespace App\Http\Resources\Silvers;

use BcMath\Number;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class SilverIndexResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $data = [
            'id' => $this->id,
            'name' => $this->silver->name_ar == 'فضة 999' && $this->country_id == 1 ? $this->silver->external_name_en : $this->silver->{'name_' . $request->header('lang')},
            // is_karat is true if the name contains a number followed by 'K' or 'k' (e.g., '10K', '18k'), otherwise false
            'hide_in_calculator' => preg_match('/\d+/', $this->silver->{'name_' . $request->header('lang')}) ? false : true,
            'icon' => uploadsPath($this->silver->icon),
            'base_price' => is_numeric($this->base_price) ? number_format($this->base_price, 2) : $this->base_price,
            'dollar_price' => is_numeric($this->dollar_price) ? number_format($this->dollar_price, 2) : $this->dollar_price,
            'base_price_nonformate' => str_replace(',', '', $this->base_price),
            'dollar_price_nonformate' => str_replace(',', '', $this->dollar_price),

            // 'status_price' => $this->status_price,
            'status_price' => $this->country_id == 1 ? $this->status_price : (number_format(abs($this->change_amount), 4) == 0 ? 'same' : $this->status_price),

            // 'change_amount' => number_format(abs($this->change_amount), 3),
             'change_amount' => $this->change_amount && $this->change_amount > 0 ? rtrim(rtrim(number_format($this->change_amount, 3, '.', ','), '0'), '.') : '0',
            'latest_updated' => (string) Carbon::parse($this->latest_updated)->addHour()->valueOf(),
        ];

        if ($this->country_id == 1) {
            $data['buy_price'] = is_numeric($this->buy_price) ? rtrim(rtrim(number_format($this->buy_price, 2, '.', ''), '0'), '.') : $this->buy_price;
            $data['sell_price'] = is_numeric($this->sell_price) ? rtrim(rtrim(number_format($this->sell_price, 2, '.', ''), '0'), '.') : $this->sell_price;
        }

        return $data;
    }
}
