<?php
require_once (PATH_TABLES . "activity/CurrencyRateTable.php") ;
require_once (PATH_MODELS . "base/MasterBase.php") ;

class CurrencyRateClass extends MasterBase {
	function __construct($db) {
		$this->db = $db ;
		$this->tbl = CurrencyRateTable::C_TABLE ;
		$this->fldid = CurrencyRateTable::C_ID ;
		$this->flddesc = CurrencyRateTable::C_DESC ;
	}
	function __destruct() {
	}
	
	function getAllRecord(){
		$sql = "SELECT * FROM " . CurrencyRateTable::C_TABLE . " ";
		
		$rows = $this->db->getTable($sql);
		
		if(is_null($rows) || count($rows) == 0){
			return null;
		} else {			
			return $rows;
		}
	}
	function getRatesById($id, $fromId = 0){
		$sql = "SELECT * FROM " . CurrencyRateTable::C_TABLE . " " . 
                "WHERE " . CurrencyRateTable::C_ID . " = " . $id . " ";
        
        if($fromId != 0){
            $sql .= " AND " . CurrencyRateTable::C_ID_FROM . " = " . $fromId;
        }
		
		$rows = $this->db->getTable($sql);
		
		if(is_null($rows) || count($rows) == 0){
			return null;
		} else {			
			return $rows;
		}
	}
	function deleteRatesById($id, $fromId = 0){
		$sql = "DELETE FROM " . CurrencyRateTable::C_TABLE . " " . 
                "WHERE " . CurrencyRateTable::C_ID . " = " . $id . " ";
        
        if($fromId != 0){
            $sql .= " AND " . CurrencyRateTable::C_ID_FROM . " = " . $fromId;
        }
        
        try{
            $this->db->executeSql($sql);
        } catch (Exception $e){
            Log::write("[CurrencyRateClass]" . $ex->getMessage());
        }
	}
    function addRate($currTo, $currFrom, $rates){
        $rows = $this->getRatesById($currTo, $currFrom);
        if (!is_null($rows) && count($rows) > 0){
            $this->deleteRatesById($currTo, $currFrom);
        }
        
        $datas = array();
        $datas[] = $this->db->fieldValue(CurrencyRateTable::C_ID,$currTo) ;
        $datas[] = $this->db->fieldValue(CurrencyRateTable::C_ID_FROM,$currFrom) ;
        $datas[] = $this->db->fieldValue(CurrencyRateTable::C_RATE,$rates) ;
        $datas[] = $this->db->fieldValue(CurrencyRateTable::C_DATE,NULL_DATE) ;
        $datas[] = $this->db->fieldValue(CurrencyRateTable::C_DESC,"") ;
        $datas[] = $this->db->fieldValue(CurrencyRateTable::C_CODE,"") ;
        
        try{
            $this->addRecord($datas);
        } catch (Exception $e){
            Log::write("[CurrencyRateClass]" . $ex->getMessage());
        }
    }
}
?>