<?php

namespace App\Http\Controllers\Traits;

use App\Currency;
use App\CurrencyRate;

trait PriceFormatTrait
{
    protected $exchangeRate = 1;

    public function formatState($price)
    {
        $state = '';
        if ($price >= 1000000) {
            $state = 'млн.';
        } elseif ($price >= 1000) {
            $state = 'тис.';
        }

        return $state;
    }

    public function formatPrice($price, $isConvert = true)
    {
        $price = $price * $this->exchangeRate;
        if ($isConvert) {
            $priceFormat = '';
            if (!empty($price)) {
                $priceFormat = floatval($price);
                if ($price >= 1000000) {
                    $priceConcat = $price / 1000000;
                    $priceFormat = floatval(number_format($priceConcat, 2)) . ' ' . $this->formatState($price);
                } elseif ($price >= 1000) {
                    $priceConcat = $price / 1000;
                    $priceFormat = floatval(number_format($priceConcat, 2)) . ' ' . $this->formatState($price);
                }
            }

            return $priceFormat;
        }

        return $price;
    }

    public function getExchangeRate()
    {
        $defaultCurrency = Currency::query()->where('is_default', 1)->first();
        $currencyFrom = $defaultCurrency ? $defaultCurrency->code : Currency::USD;
        $currencyTo = request()->headers->has('Currency') ? strtoupper(request()->headers->get('Currency')) : Currency::UAH;
        $this->exchangeRate = 1;
        if ($currencyFrom != $currencyTo) {
            $exchangeRate = CurrencyRate::query()
                ->leftJoin('currencies as crf', 'currency_rates.currency_from_id', '=', 'crf.id')
                ->leftJoin('currencies as crt', 'currency_rates.currency_to_id', '=', 'crt.id')
                ->where('crf.code', $currencyFrom)
                ->where('crt.code', $currencyTo)
                ->first();

            $this->exchangeRate = $exchangeRate ? $exchangeRate->rate : 1;
        }

    }
}
