<?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_ControllerPublic_Stats extends XenCentral_AdServer_ControllerPublic_Account
{
    public function actionIndex()
    {
        return $this->responseReroute(__CLASS__, 'zones');
    }

    public function actionZones()
    {
        $zones = $this->_getAvailableZones();

        $zoneId = $this->getInput()->filterSingle('zoneId', XenForo_Input::UINT);
        $breadCrumbs = $this->_getBreadCrumbs();
        $breadCrumbs['zone_info'] = array(
                'href' => XenForo_Link::buildPublicLink('ads/zone'),
                'value' => new XenForo_Phrase('xcas_zone_information')
        );
        $breadCrumbs['zone_stats'] = array(
                'href' => XenForo_Link::buildPublicLink('ads/stats/zones'),
                'value' => new XenForo_Phrase('xcas_zone_stats')
        );
        if (!$zoneId) {

        } else {
            $zone = $zones[$zoneId];
            $requestPaths = XenForo_Application::get('requestPaths');
            $breadCrumbs['current'] = array(
                    'href' => $requestPaths['fullUri'],
                    'value' => $zone['title']
            );
        }

        $viewParams = array(
                'zones' => $zones,
                'itemId' => $zoneId,
                'filterItems' => $zones,
                'from' => XenForo_Locale::date($this->_getStatsModel()->getFirstZoneImpressionDate($zones), 'picker'),
                'to' => XenForo_Locale::date(XenForo_Application::$time, 'picker'),
                'breadCrumbs' => $breadCrumbs
        );
        if ($viewParams['to'] == $viewParams['from']) {
            $viewParams['from'] = XenForo_Locale::date(XenForo_Application::$time - 86400, 'picker');
        }

        $viewParams += XenCentral_AdServer_Permissions::getPermissions();

        return $this->_getWrapper(
                'ads', 'stats-zones',
                $this->responseView('XenCentral_AdServer_ViewPublic_StatsIndex', 'xcas_stats', $viewParams)
        );
    }

    public function actionBanners()
    {
        $banners = $this->_getAvailableBanners();
        $zones = $this->_getAvailableZones();

        $bannerId = $this->getInput()->filterSingle('bannerId', XenForo_Input::UINT);
        $breadCrumbs = $this->_getBreadCrumbs();

        $zoneId = $this->getInput()->filterSingle('zoneId', XenForo_Input::UINT);
        if ($zoneId) {
            $breadCrumbs['zone_info'] = array(
                    'href' => XenForo_Link::buildPublicLink('ads/zone'),
                    'value' => new XenForo_Phrase('xcas_zone_information')
            );
            $zone = $zones[$zoneId];
            $breadCrumbs['zone_info2'] = array(
                    'href' => XenForo_Link::buildPublicLink('ads/zone'),
                    'value' => $zone['title']
            );

            $requestPaths = XenForo_Application::get('requestPaths');

            $breadCrumbs['banner_stats'] = array(
                    'href' => $requestPaths['fullUri'],
                    'value' => new XenForo_Phrase('xcas_banner_stats')
            );
        } else {
            $breadCrumbs['banner_stats'] = array(
                    'href' => XenForo_Link::buildPublicLink('ads/stats/banners'),
                    'value' => new XenForo_Phrase('xcas_banner_stats')
            );
        }


        if (!$bannerId) {

        } else {
            $banner = $banners[$bannerId];
            $requestPaths = XenForo_Application::get('requestPaths');
            $breadCrumbs['current'] = array(
                    'href' => $requestPaths['fullUri'],
                    'value' => $banner['title']
            );
        }

        $viewParams = array(
                'banners' => $banners,
                'itemId' => $bannerId,
                'filterItems' => $banners,
                'from' => XenForo_Locale::date($this->_getStatsModel()->getFirstBannerImpressionDate($banners), 'picker'),
                'to' => XenForo_Locale::date(XenForo_Application::$time, 'picker'),
                'breadCrumbs' => $breadCrumbs
        );

        $viewParams += XenCentral_AdServer_Permissions::getPermissions();

        return $this->_getWrapper(
                'ads', 'stats-banners',
                $this->responseView('XenCentral_AdServer_ViewPublic_StatsIndex', 'xcas_stats_banners', $viewParams)
        );
    }

    // Zone statistics
    public function actionGenerateZoneImpressionsTimeStats()
    {
        $zones = $this->_getAvailableZones();
        return $this->_getStatsInTimeResponse($zones, 'zone', 'impressions');
    }

    public function actionGenerateZoneClicksTimeStats()
    {
        $zones = $this->_getAvailableZones();
        return $this->_getStatsInTimeResponse($zones, 'zone', 'clicks');
    }

    public function actionGenerateZoneImpressionsPercentageStats()
    {
        $zones = $this->_getAvailableZones();
        return $this->_getPercentageStatsResponse($zones, 'zone', 'impressions');
    }

    public function actionGenerateZoneReferrerPercentageStats()
    {
        $zones = $this->_getAvailableZones();
        return $this->_getAttributePercentageStatsResponse($zones, 'zone', 'referrer');
    }

    public function actionGenerateZoneCountryPercentageStats()
    {
        $zones = $this->_getAvailableZones();
        return $this->_getAttributePercentageStatsResponse($zones, 'zone', 'country');
    }

    public function actionGenerateZoneClicksPercentageStats()
    {
        $zones = $this->_getAvailableZones();
        return $this->_getPercentageStatsResponse($zones, 'zone', 'clicks');
    }

    // banner statistics
    public function actionGenerateBannerImpressionsTimeStats()
    {
        $banners = $this->_getAvailableBanners();
        return $this->_getStatsInTimeResponse($banners, 'banner', 'impressions');
    }

    public function actionGenerateBannerClicksTimeStats()
    {
        $banners = $this->_getAvailableBanners();
        return $this->_getStatsInTimeResponse($banners, 'banner', 'clicks');
    }

    public function actionGenerateBannerImpressionsPercentageStats()
    {
        $banners = $this->_getAvailableBanners();
        return $this->_getPercentageStatsResponse($banners, 'banner', 'impressions');
    }

    public function actionGenerateBannerReferrerPercentageStats()
    {
        $banners = $this->_getAvailableBanners();
        return $this->_getAttributePercentageStatsResponse($banners, 'banner', 'referrer');
    }

    public function actionGenerateBannerCountryPercentageStats()
    {
        $banners = $this->_getAvailableBanners();
        return $this->_getAttributePercentageStatsResponse($banners, 'banner', 'country');
    }

    public function actionGenerateBannerClicksPercentageStats()
    {
        $banners = $this->_getAvailableBanners();
        return $this->_getPercentageStatsResponse($banners, 'banner', 'clicks');
    }

    /**
     * @param $content_array
     * @param $content_type
     * @param $stats_type
     * Returns array to be used in graphs for click attributes, like referrer, country etc.
     */
    protected function _getAttributePercentageStatsResponse($content_array, $content_type, $attribute)
    {
        $statsFilter = $this->_getFilterFromInput($content_type, $content_array);
        if (!$statsFilter->validateFilter()) {
            return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', array('error' => $statsFilter->getError()));
        }
        if ($statsFilter->getFilter()) {
            $content_array = $statsFilter->getFilteredItems($content_array);
        }

        $data = $this->_getStatsModel()->getAttributePercentageStats($content_array, $content_type, $attribute, $statsFilter->getFrom(), $statsFilter->getTo());

        $title = '';

        $data['title'] = $title;

        return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', $data);
    }

    protected function _getStatsInTimeResponse($content_array, $content_type, $stats_type)
    {
        $statsFilter = $this->_getFilterFromInput($content_type, $content_array);
        if (!$statsFilter->validateFilter()) {
            return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', array('error' => $statsFilter->getError()));
        }
        if ($statsFilter->getFilter()) {
            $content_array = $statsFilter->getFilteredItems($content_array);
        }

        $data = $this->_getStatsModel()->getStatsInTimeData($content_array, $content_type, $stats_type, $statsFilter->getFrom(), $statsFilter->getTo());

        if (!$data) {
            $error = new XenForo_Phrase('xcas_no_stats_data_is_available');
            return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', array('error' => $error->render()));
        }

        $title = '';

        $data['title'] = $title;

        return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', $data);
    }

    protected function _getPercentageStatsResponse($content_array, $content_type, $stats_type)
    {
        $statsFilter = $this->_getFilterFromInput($content_type, $content_array);
        if (!$statsFilter->validateFilter()) {
            return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', array('error' => $statsFilter->getError()));
        }
        if ($statsFilter->getFilter()) {
            $content_array = $statsFilter->getFilteredItems($content_array);
        }

        $data = $this->_getStatsModel()->getPercentageStatsData($content_array, $content_type, $stats_type, $statsFilter->getFrom(), $statsFilter->getTo());

        if (!$data) {
            $error = new XenForo_Phrase('xcas_no_stats_data_is_available');
            return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', array('error' => $error->render()));
        }

        $data['from'] = XenForo_Locale::date($statsFilter->getFrom(), 'picker');
        $data['to'] = XenForo_Locale::date($statsFilter->getTo(), 'picker');

        $title = $data['from'] . ' - ' . $data['to'];

        $data['title'] = $title;
        $data['total_phrase'] = new XenForo_Phrase('xcas_total');

        return $this->responseView('XenCentral_AdServer_ViewPublic_Stats', '', $data);
    }

    /**
     * @return XenCentral_AdServer_Helper_StatsFilter
     */
    protected function _getFilterFromInput($content_type, $content_array)
    {
        $to = $this->_input->filterSingle('to', XenForo_Input::STRING);
        $from = $this->_input->filterSingle('from', XenForo_Input::STRING);

        $dateInterval = $this->_input->filterSingle('dateInterval', XenForo_Input::STRING);
        $to = strtotime($to);

        $from = strtotime($from);
        $to += 86400; // end of day

        switch ($dateInterval) {
            case 'week':
                $to = XenForo_Application::$time;
                $from = XenForo_Application::$time - 7 * 24 * 3600;
                break;
            case 'month':
                $to = XenForo_Application::$time;
                $from = XenForo_Application::$time - 31 * 24 * 3600;
                break;
            case 'half_year':
                $to = XenForo_Application::$time;
                $from = XenForo_Application::$time - 182 * 24 * 3600;
                break;
            case 'year':
                $to = XenForo_Application::$time;
                $from = XenForo_Application::$time - 365 * 24 * 3600;
                break;
            case 'all':
                $to = XenForo_Application::$time;
                $from = $content_type == 'zone'
                        ? $this->_getStatsModel()->getFirstZoneImpressionDate($content_array) : $this->_getStatsModel()->getFirstBannerImpressionDate($content_array);
                break;
        }

        $filter = $this->_input->filterSingle('filter', XenForo_Input::ARRAY_SIMPLE);

        $requireFilter = $this->getInput()->inRequest('filter');

        $statsFilter = new XenCentral_AdServer_Helper_StatsFilter();

        $statsFilter->setFrom($from);
        $statsFilter->setTo($to);
        $statsFilter->setFilter($filter);
        $statsFilter->setRequireFilter($requireFilter);

        return $statsFilter;
    }

    protected function _getAvailableZones()
    {
        if (XenCentral_AdServer_Permissions::isAdmin()) {
            $zones = $this->_getZoneModel()->getActiveZones(true);
        } else {
            $zones = $this->_getZoneModel()->getUserZones();
        }

        $zones+=$this->_getZoneModel()->getAvailableCustomZones();

        foreach ($zones AS $zoneId => $zone) {
            if (
                    $zone->isCustomZone()
                    AND $zone->isZoneOwner(XenForo_Visitor::getUserId()) == false
                    AND XenCentral_AdServer_Permissions::isAdmin() == false

            ) {
                unset($zones[$zoneId]);
                continue;
            }

            if($zone->isCustomZone() AND XenCentral_AdServer_Permissions::isAdmin()) {
                $activeOwner= $zone->getActiveOwnerUserInfo(0);
                if($activeOwner) {
                    $zone['title']=$activeOwner['username'].': '.$zone['title'];
                }
            }
        }

        /*if($skipInputCheck==false) {
            $zoneId=$this->getInput()->filterSingle('currentItemId', XenForo_Input::UINT);
            if($zoneId) {
                if(isset($zones[$zoneId])) {
                    $zones=array($zoneId=>$zones[$zoneId]);
                } else {
                    $zones=array();
                }
            }
        }*/
        if (empty($zones)) {
            throw new XenForo_ControllerResponse_Exception(
                    $this->responseMessage(new XenForo_Phrase('xcas_there_are_no_zones_defined'))
            );
        }
        return $zones;
    }

    protected function _getAvailableBanners()
    {
        if (XenCentral_AdServer_Permissions::isAdmin()) {
            $banners = $this->_getBannerModel()->getActiveBanners();
        } else {
            $banners = $this->_getBannerModel()->getUserBanners(XenForo_Visitor::getUserId());
        }

        if ($zoneId = $this->getInput()->filterSingle('zoneId', XenForo_Input::UINT)) {
            foreach ($banners AS $bannerId => $banner) {
                if ($banner['zoneId'] != $zoneId) {
                    unset($banners[$bannerId]);
                }
            }
        }

        if (empty($banners)) {
            throw new XenForo_ControllerResponse_Exception(
                    $this->responseMessage(new XenForo_Phrase('xcas_there_are_no_banners_defined'))
            );
        }
        return $banners;
    }

    protected function _getBreadCrumbs($current = null)
    {
        $breadCrumb = parent::_getBreadCrumbs($current);
        return $breadCrumb;
    }


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