<?php

namespace Drupal\basket;

class BasketCurrency{
    protected static $tree;
    protected static $currency;
    protected static $currency_iso;
    protected static $getOptions;
    protected static $Basket;
    protected static $getCurrent;
    protected static $getPayCurrency;
    public function __construct(){
        if(!self::$Basket){
            self::$Basket = \Drupal::service('Basket');
        }
    }
  	public function tree(){
  		if(!isset(self::$tree)){
	  		self::$tree = [];
            $results = \Drupal::database()->select('basket_currency', 'c')
                                    ->fields('c')
                                    ->orderBy('c.weight', 'ASC')
                                    ->orderBy('c.name', 'ASC')
                                    ->execute()->fetchAll();
            if(!empty($results)){
                foreach ($results as $result){
                    self::$tree[$result->id] = $result;
                }
            }
  		}
  		return self::$tree;
  	}
  	public function load($id){
  		if(!isset(self::$currency[$id])){
	  		self::$currency[$id] = \Drupal::database()->select('basket_currency', 'c')
	  								->fields('c')
	  								->condition('c.id', $id)
	  								->execute()->fetchObject();
  		}
  		return self::$currency[$id];
  	}
    public function loadByISO($iso){
        if(!isset(self::$currency_iso[$iso])){
            self::$currency_iso[$iso] = \Drupal::database()->select('basket_currency', 'c')
                                    ->fields('c')
                                    ->condition('c.iso', $iso)
                                    ->execute()->fetchObject();
        }
        return self::$currency_iso[$iso];
    }
    public function delete($id){
        \Drupal::database()->delete('basket_currency')
                    ->condition('id', $id)
                    ->isNull('locked')
                    ->execute();
    }
    public function updateRate($currency, $rate){
        if(!empty($currency->id)){
            \Drupal::database()->update('basket_currency')
                        ->fields([
                            'rate'      => $rate
                        ])
                        ->condition('id', $currency->id)
                        ->execute();
        }
    }
  	public function setDefault($id){
        \Drupal::database()->update('basket_currency')
                    ->fields([
                        'default'       => NULL
                    ])
                    ->execute();
        \Drupal::database()->update('basket_currency')
                    ->fields([
                        'default'       => 1
                    ])
                    ->condition('id', $id)
                    ->execute();
    }
    public function getOptions($viewPrefix = FALSE){
        if(!isset(self::$getOptions[(boolean)$viewPrefix])){
            self::$getOptions[(boolean)$viewPrefix] = [];
            foreach (self::tree() as $currency){
                if($viewPrefix && !empty($currency->name_prefix)){
                    $currency->name = $currency->name_prefix.' '.$currency->name;
                }
                self::$getOptions[(boolean)$viewPrefix][$currency->id] = self::$Basket->Translate()->t($currency->name);
            }
        }
        return self::$getOptions[(boolean)$viewPrefix];
    }
    public function setCurrent($id){
        $_SESSION['basket_currency'] = $id;
    }
    public function getCurrent($loadDef = FALSE){
        $loadDef = (boolean)$loadDef;
        if(!isset(self::$getCurrent[$loadDef])){
            if(!empty($loadDef)){
                self::$getCurrent[$loadDef] = \Drupal::database()->select('basket_currency', 'c')
                                                            ->fields('c', ['id'])
                                                            ->condition('c.default', 1)
                                                            ->execute()->fetchField();
            } else {
                $options = self::getOptions();
                if(empty($loadDef) && !empty($_SESSION['basket_currency']) && !empty($options[$_SESSION['basket_currency']])){
                    self::$getCurrent[$loadDef] = $_SESSION['basket_currency'];
                } else {
                    self::$getCurrent[$loadDef] = $this->getCurrent(TRUE);
                }
            }
            // Alter
            if(empty($loadDef)){
                \Drupal::moduleHandler()->alter('basket_current_currency', self::$getCurrent[$loadDef]);
            }
            // ---
        }
        return self::$getCurrent[$loadDef];
    }
    public function getPayCurrency($getData = FALSE){
        if(!self::$getPayCurrency){
            self::$getPayCurrency = \Drupal::service('Basket')->getSettings('currency_pay_order', 'cid');
            if(self::$getPayCurrency == 'all'){
                self::$getPayCurrency = $getData ? self::$getPayCurrency : $this->getCurrent();
            } else if(!empty(self::$getPayCurrency) && empty($this->tree()[self::$getPayCurrency])){
                self::$getPayCurrency = NULL;
            }
            if(empty(self::$getPayCurrency)){
                self::$getPayCurrency = $this->getCurrent(TRUE);
            }
        }
        return self::$getPayCurrency;
    }
    public function PriceConvert(&$price, &$currency, $loadDef = FALSE, $getCurrent = NULL){
        if(empty($getCurrent)) $getCurrent = self::getCurrent($loadDef);
        $currency_ = self::load($currency);
        $getCurrent = self::load($getCurrent);
        if(!empty($currency_->rate) && !empty($getCurrent->rate)){
            $price = $price*($currency_->rate/$getCurrent->rate);
            $currency = $getCurrent->id;
        }
    }
    public function clearCache(){
        \Drupal::service('cache_context.basket_currency')->clearCacheTag();
    }
}