<?php
/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/

class XenCentral_AdServer_Model_Capping extends XenCentral_AdServer_Model_Abstract
{
    protected static $cookies = array();

    protected $time_base = 1383955200;

    public function displayBanner($bannerId)
    {
        if (!($cappingCount = $this->_getOptionsModel()->getDailyCapping())) {
            return true;
        }

        $cookie = $this->_getCookie('xcas_bi_' . $bannerId);

        $limitTime = XenForo_Application::$time - 86400;

        foreach ($cookie AS $time => $count) {
            if ($time > $limitTime) {
                $cappingCount -= $count;
                if ($cappingCount <= 0) {
                    return false;
                }
            }
        }

        return true;
    }

    public function saveBannerImpression($bannerId)
    {
        $cookie = $this->_getCookie($cookieName = 'xcas_bi_' . $bannerId);
        $time = XenForo_Application::$time - XenForo_Application::$time % 3600; // one entry per hour

        if (isset($cookie[$time])) {
            $cookie[$time]++;
        } else {
            $cookie[$time] = 1;
        }

        $this->_saveCookie($cookieName, $cookie);
    }

    public function sendCookies()
    {
        // save into real cookies
        $cookies = $this->_getCacheModel()->load('xcas_cookie_cache');
        if (!$cookies) {
            $cookies = array();
        }

        $dayTime=time()-time()%86400;

        foreach (self::$cookies AS $cookieName => $cookieData) {
            $cookieString = array();
            foreach ($cookieData AS $time => $count) {
                $cookieString[] = "$time=$count";
            }
            $cookieString = implode('|', $cookieString);
            $cookies[$this->_getUniqueCookieName($cookieName)]= $cookieString;
        }

        $this->_getCacheModel()->save($cookies, 'xcas_cookie_cache', array(), 999999999);
    }

    protected function _saveCookie($cookieName, $cookie)
    {
        self::$cookies[$cookieName] = $cookie;
    }

    protected function _getCookie($cookieName)
    {
        if (isset(self::$cookies[$cookieName])) {
            return self::$cookies[$cookieName];
        }
        $cookies= $this->_getCacheModel()->load('xcas_cookie_cache');

        $uniqueCookieName= $this->_getUniqueCookieName($cookieName);

        if(isset($cookies[$uniqueCookieName])) {
            $cookie= $cookies[$uniqueCookieName];
            $cookieData = explode('|', $cookie);
            $cookie = array();
            foreach ($cookieData AS $hourCookie) {
                $hourCookie = explode('=', $hourCookie);
                if(count($hourCookie)==1) {
                    continue;
                }
                $cookie[intval($hourCookie[0])] = $hourCookie[1];
            }

            $dayTime = XenForo_Application::$time - XenForo_Application::$time % 86400;
            foreach($cookie AS $cookieDate=>$cookieCount) {
                if($dayTime-$cookieDate>86400) {
                    // more than two days ago
                    unset($cookie[$cookieDate]);
                }
                else {
                    break; // anyway we have ordered array, so no need to check further
                }
            }

            ksort($cookie);
        }
        else {
            $cookie = array();
        }

        self::$cookies[$cookieName] = $cookie;

        return $cookie;
    }

    protected function _getUniqueCookieName($cookieName)
    {
        static $uniqueId;
        if (!is_null($uniqueId)) {
            return md5($uniqueId . $cookieName);
        }
        $uniqueId = XenForo_Helper_Cookie::getCookie('xcas_capping');
        if (!$uniqueId) {
            $uniqueId = md5(rand());
            if (!headers_sent()) {
                XenForo_Helper_Cookie::setCookie('xcas_capping', $uniqueId);
            }
        }
        return md5($uniqueId . $cookieName);
    }

    /**
     * @return XenCentral_Framework_Model_Cache
     */
    protected function _getCacheModel()
    {
        return $this->getModelFromCache('XenCentral_Framework_Model_Cache');
    }
}