<?php
class CursBNR
{
    /**
     * xml document
     * @var string
     */
    private $xmlDocument = "";
    public $date_found = null;

    /**
     * exchange date
     * BNR date format is Y-m-d
     * @var string
     */
    private $date = "";


    /**
     * currency
     * @var associative array
     */
    private $currency = array();


    /**
     * Class constructor
     *
     * @access        public
     * @return        void
    */
    function __construct()
    {
      ini_set("allow_url_fopen", 1);
    }

    private function curl_get_file_contents($URL)
    {

        if(!function_exists('curl_version')){
            die('CURL is disabled. curl_get_file_contents would not work');
        }
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        if (curl_errno($c)) {
            $error_msg = curl_error($h);
        }
        curl_close($c);
        if (isset($error_msg)) {
            die($error_msg);
        }
        if ($contents) return $contents;
        else return FALSE;
    }
    /**
     * parseXMLDocument method
     *
     * @access        private
     * @return         void
     */
    private function parseXMLDocument()
    {
      $url = "https://www.bnr.ro/nbrfxrates.xml";
      $url = base_url('storage/bnrxml/nbrfxrates.xml');
      $url = HUBURL.'/storage/bnrxml/nbrfxrates.xml';

		if( !ini_get('allow_url_fopen') ) {
           // die('allow_url_fopen is disabled. file_get_contents would not work');
        }

		/*if(($this->xmlDocument = @file_get_contents($url)) === false){
            throw new Exception('Connection error');
        }*/

        if(($this->xmlDocument = @$this->curl_get_file_contents($url)) === false){
            throw new Exception('Connection error');
        }

        try{
            $xml = @new SimpleXMLElement($this->xmlDocument);
        }catch (Exception $e){
            throw new Exception("BNR response is wrong");
        }

        $this->date=$xml->Header->PublishingDate;

        foreach($xml->Body->Cube->Rate as $line)
        {
            $this->currency[]=array("name"=>$line["currency"], "value"=>$line, "multiplier"=>$line["multiplier"]);
        }
    }


    private function parseDate($date)
    {
        // Make sure we have the right format of our date
        $date = $this->validateAndConvertToDate($date);
        
        $year = date('Y',strtotime($date));
        $url = HUBURL.'/storage/bnrxml/years/nbrfxrates'.$year.'.xml';
        if(($this->xmlDocument = @$this->curl_get_file_contents($url)) === false){
            throw new Exception('Connection error');
        }
        
        try{
            $xml = @new SimpleXMLElement($this->xmlDocument);
        }catch (Exception $e){
            throw new Exception("BNR response is wrong");
        }
   
        $this->date=$xml->Header->PublishingDate;

        foreach($xml->Body->Cube as $cube)
        {

          if($cube['date']->__toString() != $date){
            
            continue;
          } else {

            $this->date_found = $cube['date']->__toString();
            
            foreach($cube->Rate as $line){
              $this->currency[]=array("name"=>$line["currency"], "value"=>$line, "multiplier"=>$line["multiplier"]);
            }
          }


        }

        //pre($this->currency);
    }

    /**
     * We will validate the received date format
     * we will change format iif the format received is diferent than expected
     */
    function validateAndConvertToDate($dateString) {
        // Try to create a DateTime object from the input date string using the expected format "Y-m-d"
        $dateObject = DateTime::createFromFormat('Y-m-d', $dateString);

        // Check if the dateObject is valid and the input date is already in the correct format
        if ($dateObject !== false && $dateObject->format('Y-m-d') === $dateString) {
            // Input date is in the correct format, return it as is
            return $dateString;
        } else {
            // Input date is not in the correct format, try to convert it to "Y-m-d"
            $convertedDate = date('Y-m-d', strtotime($dateString));

            // If the conversion is successful, return the converted date
            if ($convertedDate !== false) {
                return $convertedDate;
            } else {
                // #cezartodo
                return false;
            }
        }
    }


    /**
     * getCurs method
     *
     * get current exchange rate: example getCurs("USD")
     *
     * @access        public
     * @return         double
     */
    public function getCurs($currency,$date = false)
    {
      if(!$date){
    	     $this->parseXMLDocument();
            foreach($this->currency as $line)
            {
                if($line["name"]==$currency)
                {
                    return (float)$line["value"];
                }
            }
      }else{

        $this->parseDate($date);
        
        if($this->currency == null){
          $date = date('Y-m-d', strtotime('-1 day', strtotime($date)));
          $this->parseDate($date);
        }
        if($this->currency == null){
          $date = date('Y-m-d', strtotime('-1 day', strtotime($date)));
          $this->parseDate($date);
        }
        if($this->currency == null){
          $date = date('Y-m-d', strtotime('-1 day', strtotime($date)));
          $this->parseDate($date);
        }
        if($this->currency == null){
          $date = date('Y-m-d', strtotime('-1 day', strtotime($date)));
          $this->parseDate($date);
        }
        if($this->currency == null){
          $date = date('Y-m-d', strtotime('-1 day', strtotime($date)));
          $this->parseDate($date);
        }

        foreach($this->currency as $line)
        {
            if($line["name"]==$currency)
            {
              return (float)$line["value"];
            }
        }
      }



        throw new Exception('Incorrect currency!');
    }

	//https://www.bnr.ro/files/xml/years/nbrfxrates2021.xml
  //$url = base_url('storage/bnrxml/years/nbrfxrates2021.xml');

	//<Cube date="2021-01-07">
	//<cube>/<Rate currency="HUF" multiplier="100">1.3620</Rate>
	public function get_year_rates($year,$currency){

	}
	public function get_day_rate($date,$currency){

	}
}

/*
$curs = new CursBNR();

echo $curs->getCurs("EUR");
*/
