<?php

namespace App\Http\Resources;

use App\Currency;
use App\CurrencyRate;
use App\Http\Controllers\Traits\PriceFormatTrait;
use Illuminate\Http\Resources\Json\ResourceCollection;

class PriceCollection extends ResourceCollection
{
    use PriceFormatTrait;

    /** @var array */
    private $parameters;

    /**
     * Create a new resource instance.
     *
     * @param  mixed $resource
     * @param array $parameters
     */
    public function __construct($resource, $parameters = null)
    {
        parent::__construct($resource);
        $this->resource = $resource;
        $this->parameters = is_array($parameters) ? $parameters : [];
    }

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
//        $defaultCurrency = Currency::query()->where('is_default', 1)->first();
//        $currencyFrom = $defaultCurrency ? $defaultCurrency->code : Currency::USD;
////        $currencyFrom = $request->headers->has('currency') ? strtoupper($request->headers->get('currency')) : Currency::USD;
//        $currencyTo = $request->headers->has('currency') ? strtoupper($request->headers->get('currency')) : Currency::USD;
//        $rate = 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_from_id', '=', 'cr.crt')
//                ->where('crf.code', $currencyFrom)
//                ->where('crt.code', $currencyTo)
//                ->first();
//
//            $rate = $exchangeRate ? $exchangeRate->rate : 1;
//        }

        $this->getExchangeRate();

        $result = [];
        if (isset($this->parameters['collection'])) {
            foreach ($this->collection as $key => $price) {
                if ($key < 3) {
                    $result[$key] = $this->result($price);
                }
            }
        } else {
            foreach ($this->collection as $key => $price) {
                $result[$key] = $this->result($price);
            }
        }

        return $result;
    }

    private function result($price)
    {

        return [
            'room_count' => $price->room_count_id,
            'room_type' => $price->room_type ? $price->room_type->code : '',
            'min_price' => !empty($price->min_price) ? $this->formatPrice((float)$price->min_price) : 0,
            'min_space' => !empty($price->min_space) ? (float)$price->min_space : 0,
        ];
    }
}
