<?php
/**
 * Class represents records from table currency_exchange
 * {autogenerated}
 * @property int $rate_id
 * @property string $currency
 * @property date $date
 * @property double $rate
 * @see Am_Table
 */
class CurrencyExchange extends Am_Record
{
    function insert($reload = true)
    {
        if (empty($this->base)) {
            $this->base = Am_Currency::getDefault();
        }
        return parent::insert($reload);
    }
}

class CurrencyExchangeTable extends Am_Table
{
    protected $_key = 'rate_id';
    protected $_table = '?_currency_exchange';

    /**
     * Get actual rate for currency to date
     * @param string $currency example "EUR"
     * @param type $date "2011-01-23"
     * @return double|null
     */
    function getRate($currency, $date)
    {
        $base = Am_Currency::getDefault();

        $ret = $this->_db->selectCell(<<<CUT
            SELECT ROUND(IF(currency=?, rate, 1/rate), 6)
                FROM ?_currency_exchange
                WHERE
                    ((currency=? AND base=?) OR (currency=? AND base=?))
                    AND `date`<=?
                ORDER BY `date` DESC
                LIMIT 1;
CUT
            , $currency, $currency, $base, $base, $currency, $date);
        if (empty($ret)) $ret = 1.00;
        return $ret;
    }
}
