<?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_BannerRotator extends XenCentral_AdServer_Model_Abstract
{
    /**
     * @var Int
     * If set, only the banner with this ID will be returned
     */
    protected $only_bannerId;

    protected $_rotate_banners;
    protected $_randomize_banners;

    protected $_banners=array();

    protected $_skip_placeholder=false;
    protected $_skip_capping=false;
    protected $_skip_ordered_random=false;

    protected static $rotation_queue;
    protected static $requestId='';

    /**
     * @return mixed
     */
    public function getRandomizeBanners()
    {
        return $this->_randomize_banners;
    }

    /**
     * @param mixed $randomize_banners
     */
    public function setRandomizeBanners($randomize_banners)
    {
        $this->_randomize_banners = $randomize_banners;
    }

    /**
     * @param mixed $rotate_banners
     */
    public function setRotateBanners($rotate_banners)
    {
        $this->_rotate_banners = $rotate_banners;
    }

    public function setBanners($banners)
    {
        $this->_banners=$banners;
    }

    public function addBanner($banner) {
        $this->_banners[]=$banner;
    }

    public function getProcessedBanners($requestId='')
    {
        if(empty(self::$requestId)) {
            self::$requestId = $requestId;
        }

        $banners=$this->_banners;

        if($this->_randomize_banners) {
            shuffle($banners);
        }

        foreach ($banners AS $bannerIndex => $banner) {
            if ($this->only_bannerId && $this->only_bannerId != $banner['bannerId']) {
                unset($banners[$bannerIndex]);
                continue;
            }

            if (!$this->only_bannerId && $banner['status'] != 'active') {
                // do not serve inactive banners in zone
                unset($banners[$bannerIndex]);
                continue;
            }

            if ($banner['safe_mode']) {
                // safe mode banners should not be served by delivery script
                unset($banners[$bannerIndex]);
                continue;
            }

            if ($this->only_bannerId && $banner['status'] != 'active') {
                // make sure to serve inactive banners only from our domain
                if (!$this->_validateDeliveryDomain($banner)) {
                    unset($banners[$bannerIndex]);
                    continue;
                }
            }

            if (
                    $this->_skip_placeholder==false AND
                    $banner['is_placeholder']
            ) {
                unset($banners[$bannerIndex]);
            }

            if ($this->_skip_capping==false AND
                !$this->_getCappingModel()->displayBanner($banner['bannerId'])
            ) {
                unset($banners[$bannerIndex]);
            }
        }

        if(empty($banners)) {
            if($this->_skip_placeholder==false) {
                $this->_skip_placeholder=true;
                return $this->getProcessedBanners();
            } elseif($this->_skip_capping==false) {
                $this->_skip_capping=true;
                return $this->getProcessedBanners();
            }

            // no banner to serve
            return array();
        }

        if($this->_rotate_banners==false OR count($banners)==1) {
            return $banners;
        }

        if($this->_skip_ordered_random==false) {
            foreach($banners AS $bannerIndex=>$banner) {
                if($this->isInRotationQueue($banner['bannerId'])) {
                    unset($banners[$bannerIndex]);
                }
            }
        }

        if (empty($banners)) {
            if ($this->_skip_ordered_random == false) {
                $this->clearRandomQueue();
                // try again, without checking the order
                $this->_skip_ordered_random = true;
                return $this->getProcessedBanners();
            } else {
                // we don't have any banner again
                return array();
            }
        }

        $banner= $banners[array_rand($banners)];

        $this->setBannerInLoadedQueue($banner['bannerId']);

        return array($banner);
    }

    public function setBannerInLoadedQueue($bannerId)
    {
        $queue=self::_readRotationQueue();
        $queue[]=$bannerId;
        self::_saveRotationQueue($queue);
    }

    public function clearRandomQueue()
    {
        self::$rotation_queue=array();
        XenForo_Helper_Cookie::deleteCookie('xcas_banner_rotation_queue');
    }

    public function isInRotationQueue($bannerId)
    {
        return in_array($bannerId, self::_readRotationQueue());
    }

    public function setOnlyBannerId($bannerId)
    {
        $this->only_bannerId=$bannerId;
    }


    protected function _validateDeliveryDomain($banner)
    {
        // for now no dependency on particular banner
        if (
                empty($_SERVER['HTTP_REFERER'])
                OR parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) != parse_url(XenForo_Application::getOptions()->get('boardUrl'), PHP_URL_HOST)
        ) {
            return false;
        }
        return true;
    }


    protected static function _readRotationQueue()
    {
        if(is_null(self::$rotation_queue)) {
            self::$rotation_queue = array();

            /** @var XenCentral_Framework_Model_Cache $cacheModel */
            /*$cacheModel=XenForo_Model::create('XenCentral_Framework_Model_Cache');

            $cached = $cacheModel->load(self::_getUserCacheId());
            if ($cached) {
                $cached = explode(',', $cached);
                $cached=array_unique($cached);
                self::$rotation_queue=$cached;
            } else {
                self::$rotation_queue=array();
            }*/
        }

        return self::$rotation_queue;
    }

    protected static function _saveRotationQueue($queue)
    {
        self::$rotation_queue=$queue;
    }

    function __destruct()
    {
        return; // disabled
        if(is_null(self::$rotation_queue)) {
            return;
        }

        /** @var XenCentral_Framework_Model_Cache $cacheModel */
        $cacheModel = XenForo_Model::create('XenCentral_Framework_Model_Cache');
        $cacheModel->save(implode(',', self::$rotation_queue), self::_getUserCacheId(), array(), 10);
    }

    protected static function _getUserCacheId()
    {
        return 'xcas_rotation_cache_' . md5(self::$requestId);
    }

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

}