<?php
if ( ! class_exists( 'IPVisc_Campaign' )) {

    /**
     * Class campaign handler
     */
    class IPVisc_Campaign
    {
        //{{ parameters

        /**
         * Take campaign object
         *
         * @var object
         */
        protected $_campaign;

        /**
         * Take campaign setting
         *
         * @var object
         */
        protected $_setting;

        //}}
        //{{ __construct

        /**
         * Class constructor
         *
         * @param  object $campaign
         * @return void
         */
        public function __construct( $campaign )
        {
            $this->_campaign = $campaign;
            $this->_setting  = new IPVisc_Setting( $campaign->ID, '__ipvisc-setting' );
        }

        //}}
        //{{ save

        /**
         * Save campaign
         *
         * @return boolean
         */
        public function save()
        {
            $setting    = $this->_setting;
            $timezone   = $setting->getSetting( 'timezone' );
            date_default_timezone_set( $timezone );
            //
            //Save stat
            $this->_saveStat();

            $endDate    = $setting->getSetting( 'end_date' );
            $timeFuture = strtotime( $endDate );
            $timeNow    = time();

            //
            //Redirect to target
            if ( $timeNow < $timeFuture ) {
                $redirect = $setting->getSetting( 'campaign_url' );
            } else {
                $redirect = $setting->getSetting( 'info_url', '#' );
            }
            wp_redirect( $redirect );
            exit();
        }

        //}}
        //{{ _saveStat

        /**
         * Save stat
         *
         * @return string
         */
        public function _saveStat()
        {
            $campaign = $this->_campaign;
            $model    = new IPVisc_Model_Stat();
            //
            //Save display count
            $model->saveStat( $campaign, 'click' );
            //
            //Save unique display count
            $access = $model->getUniqueAccess( 2, $campaign );
            if ( empty( $access )) {
                $model->saveStat( $campaign, 'unique_click' );
            }
            //
            //Save access
            $model->insertAccess( 2, $campaign );
        }
    }
}
