<?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_Banner extends XenCentral_AdServer_ControllerAdmin_Abstract
{
    public function actionIndex()
    {
        // redirect to manage zone page that shows banners as well
        return $this->responseRedirect(
                XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL,
                XenForo_Link::buildAdminLink('xcas/zone')
        );
    }

    public function actionCropImage()
    {
        $attachment_id = $this->_input->filterSingle('attachment_id', XenForo_Input::UINT);

        $temp_hash = $this->_input->filterSingle('temp_hash', XenForo_Input::STRING);

        $attachment = $this->_getAttachmentModel()->getAttachmentById($attachment_id);

        if (!$attachment) {
            return $this->getNotFoundResponse();
        }

        $attachment = $this->_getAttachmentModel()->prepareAttachment($attachment);

        if (!$temp_hash OR $temp_hash != $attachment['temp_hash']) {
            return $this->getNotFoundResponse();
        }

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

        if (!$zone_id) {
            return $this->getNotFoundResponse();
        }

        $errors = array();

        $attachment = $this->_getZoneModel()->cropAttachment(
                $zone_id,
                $attachment,
                $this->_input->filterSingle('x1', XenForo_Input::UNUM),
                $this->_input->filterSingle('y1', XenForo_Input::UNUM),
                $this->_input->filterSingle('w', XenForo_Input::UNUM),
                $this->_input->filterSingle('h', XenForo_Input::UNUM),
                $errors
        );

        if ($errors OR $attachment == false) {
            return $this->responseError($errors);
        }

        $this->getRouteMatch()->setResponseType('json');

        return $this->responseView(
                'XenCentral_AdServer_ViewAdmin_Banner_Crop',
                '',
                array(
                        'attachment' => $attachment
                )
        );
    }

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

        $defaultBanner = $this->_getBannerModel()->getDefaultBanner();

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

        if(!$zoneId) {
            return $this->getNotFoundResponse();
            /*$viewParams = array(
                    'title' => new XenForo_Phrase('xcas_choose_zone'),
                    'zoneOptions' => $this->_getZoneModel()->getZoneOptions(),
                    'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_choose_zone')),
            );

            return $this->responseView('XenCentral_AdServer_ViewAdmin_ChooseZone', 'xcas_choose_zone', $viewParams);*/
        }

        $defaultBanner['zoneId'] = $zoneId;

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

        $attachmentHash = null;

        $attachmentParams = $this->_getZoneModel()->getAttachmentParams($zone, array(
                'zone_id' => $zone['zoneId']
        ), null, null, $attachmentHash);

        $viewParams = array(
                'title' => new XenForo_Phrase('xcas_add_banner'),
                'item' => $defaultBanner,
                'zoneOptions' => $this->_getZoneModel()->getZoneOptions(),
                'breadCrumbs' => $this->_getBreadCrumbs(new XenForo_Phrase('xcas_add_banner')),
                'attachmentParams' => $attachmentParams,
                'attachmentConstraints' => $this->_getBannerModel()->getUploadConstraints($zone),
        );

        return $this->responseView('XenCentral_AdServer_ViewAdmin_BannerAdd', 'xcas_add_banner', $viewParams);
    }

    public function actionEdit()
    {
        $item = $this->_assertCorrectBanner();
        $zone=$this->_getZoneModel()->getZoneObjectById($item['zoneId']);

        $attachmentHash = null;

        $attachmentParams = $this->_getZoneModel()->getAttachmentParams($zone, array(
                'zone_id' => $zone['zoneId'],
                'banner_id' => $item['bannerId']
        ), null, null, $attachmentHash);

        $attachmentModel = $this->_getAttachmentModel();

        $attachments = $attachmentModel->getAttachmentsByContentId('banner', $item['bannerId']);

        $attachments=$this->_getBannerModel()->prepareBannerAttachments($attachments);

        $viewParams = array(
                'title' => new XenForo_Phrase('xcas_edit_banner'),
                'zoneOptions' => $this->_getZoneModel()->getZoneOptions(),
                'item' => $item,
                'breadCrumbs' => $this->_getBreadCrumbs($item['title']),
                'attachmentParams' => $attachmentParams,
                'attachmentConstraints' => $this->_getBannerModel()->getUploadConstraints($zone),
                'attachments' => $attachments,
        );

        return $this->responseView('XenCentral_AdServer_ViewAdmin_BannerEdit', 'xcas_add_banner', $viewParams);
    }

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

        $this->_assertManagePermissions();

        $item = $this->_input->filter(array(
                'bannerId' => XenForo_Input::UINT,
                'title' => XenForo_Input::STRING,
                'url' => XenForo_Input::STRING,
                'code' => XenForo_Input::STRING,
                'mobile_view_code' => XenForo_Input::STRING,
                'tablet_view_code' => XenForo_Input::STRING,
                'status' => XenForo_Input::STRING,
                'text' => XenForo_Input::STRING,
                'zoneId' => XenForo_Input::UINT,
                'impressions_left' => XenForo_Input::INT,
                'display_order' => XenForo_Input::UINT,
                'active' => XenForo_Input::UINT,
                'is_placeholder' => XenForo_Input::UINT,
                'safe_mode' => XenForo_Input::BOOLEAN,
                'active_from' => XenForo_Input::DATE_TIME,
                'active_to' => XenForo_Input::DATE_TIME,
        ));

        $options = $this->_input->filter(array(
                'username' => XenForo_Input::STRING,
                'active_from_time' => XenForo_Input::STRING,
                'active_to_time' => XenForo_Input::STRING,
        ));

        $attachment_hash = $this->_input->filterSingle('attachment_hash', XenForo_Input::STRING);

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

        $writer->setExtraData(XenForo_DataWriter_DiscussionMessage::DATA_ATTACHMENT_HASH, $attachment_hash);

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

        $writer->bulkSet($item);

        $writer->setOption('active_to_time', $options['active_to_time']);
        $writer->setOption('active_from_time', $options['active_from_time']);
        $writer->setOption('username', $options['username']);

        $tagger = null;

        if ($this->_getBannerModel()->canEditTags($item)) {
            /** @var XenForo_Model_Tag $tagModel */
            $tagModel = $this->getModelFromCache('XenForo_Model_Tag');
            $tagger = $tagModel->getTagger('banner');
            if ($item['bannerId']) {
                $tagger->setContent($item['bannerId']);
            }

            $tagger->setPermissionsFromContext(array())
                ->setTags($tagModel->splitTags(
                    $this->getInput()->filterSingle('tags', XenForo_Input::STRING)
                ));
            $writer->mergeErrors($tagger->getErrors());
        }

        $writer->preSave();

        $bannerId=$writer->save();

        if ($tagger) {
            if (!$item['bannerId']) {
                $tagger->setContent($bannerId, true);
            }
            $tagger->save();
        }

        XenCentral_AdServer_Cron::updateBannerStatus();

        $redirectParams = array();

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

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

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

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

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

        XenCentral_AdServer_Cron::updateBannerStatus();

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

    public function actionApprove()
    {
        $banner = $this->_assertCorrectBanner();
        $writer = XenForo_DataWriter::create('XenCentral_AdServer_DataWriter_Banner');
        $writer->setExistingData($banner, true);
        $writer->set('status', 'inactive');
        $writer->save();

        XenCentral_AdServer_Cron::updateBannerStatus();

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

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

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

    public function actionDoDelete()
    {
        $banner = $this->_assertCorrectBanner();

        $writer = XenForo_DataWriter::create('XenCentral_AdServer_DataWriter_Banner');
        $writer->setExistingData($banner['bannerId']);
        $writer->delete();

        $redirectParams = array();

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

    /**
     * @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 _assertCorrectBanner()
    {
        $this->_assertManagePermissions();

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

        if (!$bannerId) {
            throw $this->getErrorOrNoPermissionResponseException(new XenForo_Phrase('xcas_banner_not_found'));
        }

        $banner = $this->_getBannerModel()->getBannerById($bannerId);

        if (!$banner) {
            throw $this->getErrorOrNoPermissionResponseException(new XenForo_Phrase('xcas_banner_not_found'));
        }

        $banner = $this->_getBannerModel()->prepareBanner($banner);
        if ($banner['user_id']) {
            $users = $this->_getUserModel()->getUsersByIds(explode(',', $banner['user_id']));
            $user_list = array();
            foreach ($users AS $userId => $user) {
                if($users[$userId]['username']) {
                    $user_list[$userId] = $users[$userId]['username'];
                }
            }
            $banner['username'] = implode(", ", $user_list);
        }
        return $banner;
    }

    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'))
            );
        }
    }

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