<?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_ControllerAdmin_Zone extends XenCentral_AdServer_ControllerAdmin_Abstract
{
	public function actionIndex()
	{
        $this->_assertManagePermissions();

        $items=$this->_getZoneModel()->getAllZones();

        $siteZones=$customZones=array();

        $banners = $this->_getBannerModel()->getAllBanners();
        foreach ($items AS &$item) {
            $item['banners'] = array();
            foreach ($banners AS $bannerId => $banner) {
                if ($banner['zoneId'] == $item['zoneId']) {
                    $item['banners'][$bannerId] = $banner;
                }
            }
        }

        foreach($items AS $zone) {
            if($zone['owners']) {
                $customZones[$zone['zoneId']]= $zone;
            } else {
                $siteZones[$zone['zoneId']]= $zone;
            }
        }

        $viewParams=array(
            'siteZones'=> $siteZones,
            'customZones'=> $customZones,
            'breadCrumbs'=>$this->_getBreadCrumbs()
        );

		return $this->responseView('XenCentral_AdServer_ViewAdmin_ZoneIndex', 'xcas_manage_zones', $viewParams);
	}

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

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

        $viewParams = array(
            'title' => new XenForo_Phrase('xcas_add_zone'),
            'item' => $defaultZone,
            'userCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($defaultZone['user_criteria']),
            'not_userCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($defaultZone['user_criteria_not']),
            'userCriteriaData' => XenForo_Helper_Criteria::getDataForUserCriteriaSelection(),
            'pageCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($defaultZone['page_criteria']),
            'not_pageCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($defaultZone['page_criteria_not']),
            'pageCriteriaData' => XenForo_Helper_Criteria::getDataForPageCriteriaSelection(),
            'groupedLocations' => XenCentral_AdServer_LocationList::getInstance()->getGroupedLocationList(),
            'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_add_zone'))
        );

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

    public function actionEdit()
    {
        $item=$this->_assertCorrectZone();

        $viewParams = array(
            'title' => new XenForo_Phrase('xcas_edit_zone'),
            'item' => $item,
            'userCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($item['user_criteria']),
            'not_userCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($item['user_criteria_not']),
            'userCriteriaData' => XenForo_Helper_Criteria::getDataForUserCriteriaSelection(),
            'pageCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($item['page_criteria']),
            'not_pageCriteria' => XenForo_Helper_Criteria::prepareCriteriaForSelection($item['page_criteria_not']),
            'pageCriteriaData' => XenForo_Helper_Criteria::getDataForPageCriteriaSelection(),
            'groupedLocations'=> XenCentral_AdServer_LocationList::getInstance()->getGroupedLocationList(),
            'breadCrumbs' => $this->_getBreadCrumbs($item['title'])
        );

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

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

        $this->_assertManagePermissions();

        $item = $this->_input->filter(array(
            'zoneId'=> XenForo_Input::UINT,
            'title' => XenForo_Input::STRING,
            'width'=>XenForo_Input::UINT,
            'height'=>XenForo_Input::UINT,
            'force_dimensions'=>XenForo_Input::BOOLEAN,
            'use_placeholder'=>XenForo_Input::BOOLEAN,
            'rotate'=>XenForo_Input::BOOLEAN,
            'rotate_zone'=>XenForo_Input::BOOLEAN,
            'randomize_banners'=>XenForo_Input::BOOLEAN,
            'user_zone'=>XenForo_Input::BOOLEAN,
            'auto_rotate'=>XenForo_Input::UINT,
            'slot_count'=>XenForo_Input::UINT,
            'packages'=>XenForo_Input::ARRAY_SIMPLE,
            'display_order' => XenForo_Input::UINT,
            'locations'=>XenForo_Input::ARRAY_SIMPLE,
            'user_criteria' => XenForo_Input::ARRAY_SIMPLE,
            'page_criteria' => XenForo_Input::ARRAY_SIMPLE,
            'user_criteria_not' => XenForo_Input::ARRAY_SIMPLE,
            'page_criteria_not' => XenForo_Input::ARRAY_SIMPLE,
            'active' => XenForo_Input::UINT,
            'price_per_click' => XenForo_Input::UNUM,
        ));

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

        if($item['zoneId']) {
            $writer->setExistingData($item['zoneId']);
        }

        foreach($item['packages'] AS $index=>$package) {
            if(!$package['length'] OR !$package['price'] OR !$package['currency']) {
                unset($item['packages'][$index]);
            }
        }

        $item['packages']=array_merge($item['packages'], array());

        $writer->bulkSet($item);

        $writer->setOption('owners', $this->_input->filterSingle('owners', XenForo_Input::STRING));

        $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::buildAdminLink('xcas/zone'),
            null,
            $redirectParams
        );
    }

    public function actionDelete()
    {
        $item = $this->_assertCorrectZone();

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

        return $this->responseView('XenCentral_AdServer_ViewAdmin_Delete', 'xcas_delete_zone', $viewParams);
    }

    public function actionDisable()
    {
        $zone = $this->_assertCorrectZone();
        $writer = XenForo_DataWriter::create('XenCentral_AdServer_DataWriter_Zone');
        $writer->setExistingData($zone, true);
        $writer->set('active', 0);
        $writer->save();

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

        return $this->responseRedirect(
            XenForo_ControllerResponse_Redirect::SUCCESS,
            XenForo_Link::buildAdminLink('xcas/zone'),
            null,
            array()
        );
    }

    public function actionEnable()
    {
        $zone = $this->_assertCorrectZone();
        $writer = XenForo_DataWriter::create('XenCentral_AdServer_DataWriter_Zone');
        $writer->setExistingData($zone, true);
        $writer->set('active', 1);
        $writer->save();

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

        return $this->responseRedirect(
            XenForo_ControllerResponse_Redirect::SUCCESS,
            XenForo_Link::buildAdminLink('xcas/zone'),
            null,
            array()
        );
    }

    public function actionDoDelete()
    {
        $zone=$this->_assertCorrectZone();

        $writer = XenForo_DataWriter::create('XenCentral_AdServer_DataWriter_Zone');
        $writer->setExistingData($zone['zoneId']);
        $writer->delete();

        $redirectParams = array();

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

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

    public function actionSuggestHook()
    {
        $q = $this->_input->filterSingle('q', XenForo_Input::STRING);

        $hooks=$this->_getZoneModel()->getAvailableHooks($q);

        $view = $this->responseView();
        $view->jsonParams = array(
            'results' => $hooks
        );
        return $view;
    }

    /**
     * @param XenForo_Phrase $current
     * @return array
     */
    protected function _getBreadCrumbs($current=null)
    {
        $breadCrumbs=array(
            'home' => array(
                'href' => XenForo_Link::buildAdminLink('full:xcas/zone'),
                'value' => new XenForo_Phrase('xcas_manage_zones')
            )
        );

        if($current) {
            $requestPaths=XenForo_Application::get('requestPaths');
            $breadCrumbs['current']=array(
                'href'=> $requestPaths['fullUri'],
                'value'=>$current
            );
        }

        return $breadCrumbs;
    }

    protected function _assertCorrectZone()
    {
        $this->_assertManagePermissions();

        $zoneId = $this->_input->filterSingle('zoneId', XenForo_Input::UINT);

        if (!$zoneId) {
            throw $this->getNoPermissionResponseException();
        }

        $zone = $this->_getZoneModel()->getZoneById($zoneId);

        if (!$zone) {
            throw $this->getNoPermissionResponseException();
        }

        if ($zone['owners']) {
            $users = $this->_getUserModel()->getUsersByIds(explode(',', $zone['owners']));
            $user_list = array();
            foreach ($users AS $userId => $user) {
                if ($users[$userId]['username']) {
                    $user_list[$userId] = $users[$userId]['username'];
                }
            }

            $zone['ownerNames'] = implode(", ", $user_list);
        }

        return $zone;
    }

    protected function _assertManagePermissions()
    {
        if(!XenForo_Visitor::getInstance()->hasAdminPermission('xcas_manage_ads')) {
            throw new XenForo_ControllerResponse_Exception(
                $this->responseError(new XenForo_Phrase('xcas_you_are_not_allowed_to_administer_ad_zones_and_banners'))
            );
        }
    }
}
