<?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_Zone extends XenCentral_AdServer_ControllerPublic_Account
{
    public function actionIndex()
    {
        $zones = $this->_getAvailableSiteZones();
        $banners = $this->_getBannerModel()->getUserBanners(XenForo_Visitor::getUserId());
        $banners = $this->_getZoneBanners($zones, $banners);

        if (
                $this->_getOptionsModel()->showSiteZones() == false
                OR (
                        empty($banners)
                        AND XenCentral_AdServer_Permissions::canCreateZone()
                )
        ) {
            return $this->responseReroute('XenCentral_AdServer_ControllerPublic_Zone', 'custom');
        }

        return $this->responseReroute('XenCentral_AdServer_ControllerPublic_Zone', 'site');
    }

    public function actionSite()
    {
        $zones = $this->_getAvailableSiteZones();
        $banners = $this->_getBannerModel()->getUserBanners(XenForo_Visitor::getUserId());
        $banners = $this->_getZoneBanners($zones, $banners);

        $viewParams = array(
                        'banners' => $banners,
                        'zones' => $zones,
                        'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_site_zones'))
                ) + XenCentral_AdServer_Permissions::getPermissions();

        return $this->_getWrapper(
                'ads', 'site-zones',
                $this->responseView('XenCentral_AdServer_ViewPublic_ZoneSite', 'xcas_zone_list', $viewParams)
        );
    }

    public function actionCustom()
    {
        $this->_assertCanManageCustomZones();

        $zones = $this->_getAvailableCustomZones();

        $banners = $this->_getBannerModel()->getUserBanners(XenForo_Visitor::getUserId());
        $banners = $this->_getZoneBanners($zones, $banners);

        $user = $this->_getUserModel()->getAdServerUserInfo(XenForo_Visitor::getUserId());
        $user['excluded_campaign_domains'][] = '';

        $transactions = $this->_getCreditLogModel()->getUserTransactions(array(
                'user_ud' => XenForo_Visitor::getUserId()
        ));

        $viewParams = array(
                        'zones' => $zones,
                        'banners' => $banners,
                        'user' => $user,
                        'transactions' => $transactions,
                        'showCreateButton' => true,
                        'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_custom_zones'))
                ) + XenCentral_AdServer_Permissions::getPermissions();

        return $this->_getWrapper(
                'ads', 'custom-zones',
                $this->responseView('XenCentral_AdServer_ViewPublic_ZoneCustom', 'xcas_campaign_list', $viewParams)
        );
    }

    public function actionEdit()
    {
        $this->_assertCanManageCustomZones();

        $zoneId = $this->_input->filterSingle('zoneId', XenForo_Input::UINT);
        $zone = $this->_getZoneModel()->getZoneObjectById($zoneId);
        if (!$zone OR $zone->isCustomZone() == false OR $zone->isZoneOwner(XenForo_Visitor::getUserId()) == false) {
            return $this->responseNoPermission();
        }

        $viewParams = array(
                'title' => new XenForo_Phrase('xcas_add_banner'),
                'item' => $zone,
                'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_edit_campaign')),
        );

        return $this->_getIndexWrapper(
                $this->responseView('XenCentral_AdServer_ViewPublic_ZoneAdd', 'xcas_add_zone', $viewParams)
        );
    }

    public function actionAdd()
    {
        $this->_assertCanManageCustomZones();

        $defaultZone = $this->_getZoneModel()->getDefaultZone();

        $viewParams = array(
                'title' => new XenForo_Phrase('xcas_add_campaign'),
                'item' => $defaultZone,
                'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_add_campaign')),
        );

        return $this->_getIndexWrapper(
                $this->responseView('XenCentral_AdServer_ViewPublic_ZoneAdd', 'xcas_add_zone', $viewParams)
        );
    }

    public function actionSave()
    {
        $this->_assertCanManageCustomZones();
        $this->_assertPostOnly();

        $item = $this->_input->filter(array(
                'zoneId' => XenForo_Input::UINT,
                'title' => XenForo_Input::STRING,
                'rotate' => XenForo_Input::BOOLEAN,
                'randomize_banners' => XenForo_Input::BOOLEAN,
                'display_order' => XenForo_Input::UINT,
        ));

        $writer = XenForo_DataWriter::create('XenCentral_AdServer_DataWriter_Zone');

        if ($item['zoneId']) {
            $zone = $this->_getZoneModel()->getZoneObjectById($item['zoneId']);
            if (!$zone->isZoneOwner(XenForo_Visitor::getUserId())) {
                throw $this->getNoPermissionResponseException();
            }

            $writer->setExistingData($item['zoneId']);
        } else {
            if (XenForo_Application::getOptions()->get('xcas_default_zone_width')
                    OR XenForo_Application::getOptions()->get('xcas_default_zone_height')
            ) {
                $item['width'] = XenForo_Application::getOptions()->get('xcas_default_zone_width');
                $item['height'] = XenForo_Application::getOptions()->get('xcas_default_zone_height');
                $item['force_dimensions'] = true;
            }
        }

        $writer->bulkSet($item);

        $writer->set('owners', XenForo_Visitor::getUserId());
        $writer->set('creator_user_id', XenForo_Visitor::getUserId());
        $writer->set('price_per_click', $this->_getOptionsModel()->default_price_per_click(XenForo_Visitor::getUserId()));

        $this->_preSaveZone($writer);

        $writer->preSave();

        if ($dwErrors = $writer->getErrors()) {
            return $this->responseError($dwErrors);
        }

        $writer->save();

        $redirectParams = array();

        $this->_getZoneModel()->updateCache();

        return $this->responseRedirect(
                XenForo_ControllerResponse_Redirect::SUCCESS,
                XenForo_Link::buildPublicLink('ads/zone/custom'),
                null,
                $redirectParams
        );
    }

    /**
     * @param XenCentral_AdServer_Zone[] $zones
     * @param $banners
     * @return array
     */
    protected function _getZoneBanners($zones, $banners)
    {
        foreach ($banners AS $bannerId => $banner) {
            if (!isset($zones[$banner['zoneId']])) {
                unset($banners[$bannerId]);
                continue;
            }

            $banner = $this->_getBannerModel()->prepareForListing($banner);
            $banner = $this->_getBannerModel()->calculateBannerCost($banner, $zones[$banner['zoneId']]);
            $banner = $this->_getBannerModel()->prepareGeneralStats($banner);
            $banner['zoneName'] = $zones[$banner['zoneId']]->get('title');
            $banners[$bannerId] = $banner;
        }

        return $banners;
    }


    public function actionStats()
    {
        return $this->responseReroute('XenCentral_AdServer_ControllerPublic_Stats', 'zones');
    }

    public function actionCopyCode()
    {
        $zoneId = $this->_input->filterSingle('zoneId', XenForo_Input::UINT);
        $zones = $this->_getAvailableSiteZones() + $this->_getAvailableCustomZones();
        if (!isset($zones[$zoneId])) {
            // should not happen
            return $this->responseNoPermission();
        }
        $viewParams = array(
                'zone' => $zones[$zoneId],
                'explain' => new XenForo_Phrase('xcas_zone_embed_explain')
        );
        return $this->responseView('XenCentral_AdServer_ViewPublic_ZoneCode', 'xcas_embed_wrapper', $viewParams);
    }

    /**
     * @return XenCentral_AdServer_Zone[]
     * Returns prepared zone objects including website zones only
     */
    protected function _getAvailableSiteZones()
    {
        if (XenCentral_AdServer_Permissions::isAdmin()) {
            $zones = $this->_getZoneModel()->getActiveZones(true);
        } else {
            $zones = $this->_getZoneModel()->getUserZones();
        }

        foreach ($zones AS $zoneId => $zone) {
            if ($zone->isCustomZone()) {
                unset($zones[$zoneId]);
                continue;
            }

            $zone->prepareZoneInformation();
        }

        return $zones;
    }

    /**
     * @return XenCentral_AdServer_Zone[]
     * Returns prepared zone objects including website zones only
     */
    protected function _getAvailableCustomZones()
    {
        return $this->_getZoneModel()->getAvailableCustomZones(XenForo_Visitor::getUserId());
    }

    protected function _preSaveZone(XenCentral_AdServer_DataWriter_Zone $writer)
    {

    }

    protected function _assertCanManageCustomZones()
    {
        if (!XenCentral_AdServer_Permissions::canCreateZone()) {
            throw $this->getNoPermissionResponseException();
        }
    }

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