<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Model_usd_to_myr extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    public function getTodayRate()
    {
        $myr = $this->get_stored_rate();
        if(empty($myr))
        {
            $myr = $this->get_today_rate_from_currencyconverterapi();
            if(empty($myr))
            {
                $myr = $this->get_today_rate_from_exchangerateapi();
            }
        }

        if($myr)
        {
            return $myr;
        }else{
            return false;
        }
    }

    public function insert($insert)
    {
        $this->db->insert('usd_to_myr',$insert);
    }

    private function get_stored_rate()
    {
        $today = date('Y-m-d');
        $myr = $this->db->select('myr') 
                ->where('date',$today)
                ->limit(1,0)
                ->get('usd_to_myr')
                ->result();

        // debug($myr);
        if(!empty($myr))
        {
            return $myr[0]->myr;
        }
        return false;
    }

    //1. currencyconvertapi
    private function get_today_rate_from_currencyconverterapi()
    {
        error_reporting(0);
        $currency_json = file_get_contents('https://free.currencyconverterapi.com/api/v6/convert?q=USD_MYR&compact=ultra&apiKey=3fa42ba1080190561c6c');
        if(!empty($currency_json))
        {
            $currency_object = json_decode($currency_json);
            error_reporting(-1); //on error reporting because request already finished
            $insert_data = array
            (
                'date'  => date('Y-m-d'),
                'usd'   => 1,
                'myr'   => number_format($currency_object->USD_MYR,3)
            );
            $this->insert($insert_data);
            return number_format($currency_object->USD_MYR,3);
        }
        return false; //unable to request to the website
    }
    
    //2.exchangeratesapi
    private function get_today_rate_from_exchangerateapi()
    {
        $currency_json = file_get_contents('https://api.exchangeratesapi.io/latest?base=USD&symbols=MYR');
        if(!empty($currency_json))
        {
            $currency_object = json_decode($currency_json);
            error_reporting(-1); //on error reporting.
            $insert_data = array
            (
                'date'      => date('Y-m-d'),
                'usd'       => 1,
                'myr'       => number_format($currency_object->rates->MYR,3)
            );
            $this->insert($insert_data);
            return number_format($currency_object->rates->MYR,3);
        }
        return false;
    }
    

}
?>