<?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_Main extends XenCentral_AdServer_ControllerAdmin_Abstract
{
    protected function _preDispatch($action)
    {
        parent::_preDispatch($action);
        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'))
            );
        }
    }

    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 actionResetStats()
    {
        if ($this->isConfirmedPost()) {
            $this->_getStatsModel()->resetStats();
            $this->_getCacheModel()->clean();
            return $this->responseView('XenCentral_AdServer_ViewAdmin_ResetStats', 'xcas_stats_are_removed');
        }

        return $this->responseView('XenCentral_AdServer_ViewAdmin_ResetStats', 'xcas_reset_stats');
    }

    public function actionExportStatsExport()
    {
        $conditions = $this->_input->filter(array(
            'start_date' => XenForo_Input::DATE_TIME,
            'end_date' => XenForo_Input::DATE_TIME,
            'zoneId' => XenForo_Input::STRING,
            'export_type' => XenForo_Input::STRING,
        ));

        if ($conditions['end_date'] == 0 OR $conditions['end_date']>time()) {
            $conditions['end_date'] = time();
        }

        if ($conditions['start_date'] > $conditions['end_date']) {
            $conditions['start_date'] = $conditions['end_date'] - 7 * 86400;
        }

        if($conditions['zoneId']>0) {
            $banners=$this->_getBannerModel()->getZoneBanners($conditions['zoneId']);
        } else {
            $banners=$this->_getBannerModel()->getAllBanners();
        }

        $bannersStatisticsArray = $this->_getStatsModel()->getBannerStatisticsForExport($banners, $conditions);
        $zoneImpressionsArray = $this->_getStatsModel()->getZoneStatisticsForExport($conditions);

        $this->_routeMatch->setResponseType('raw');

        $viewParams = array(
            'zone' => $zoneImpressionsArray,
            'banner' => $bannersStatisticsArray,
            'conditions' => $conditions,

        );
        return $this->responseView('XenCentral_AdServer_ViewAdmin_Export', '', $viewParams);


    }


    public function actionExportStats()
    {

        $zones = $this->_getZoneModel()->getActiveZones();

        return $this->responseView('XenCentral_AdServer_ViewAdmin_ExportStats', 'xcas_export_stats', array('zones' => $zones));
    }

    public function actionManageCredits()
    {
        $viewParams = array();

        $criteriaHelper = $this->_getCriteriaHelper();
        $viewParams += $criteriaHelper->getDataForUserSearchForm();
        $viewParams['criteria'] = $criteriaHelper->getDefaultUserSearchCriteria();

        return $this->responseView('XenCentral_AdServer_ViewAdmin_ManageCredits', 'xcas_manage_credits', $viewParams);
    }

    public function actionCreditLogSearch()
    {
        return $this->responseView(
                'XenCentral_AdServer_ViewAdmin_CreditTransaction_Search',
                'xcas_credit_transaction_search',
                array()
        );
    }

    public function actionCreditLog()
    {
        $logId = $this->_input->filterSingle('log_id', XenForo_Input::UINT);

        if ($logId) {
            $transaction = $this->_getCreditLogModel()->getUserTransactionById($logId);
            if (!$transaction) {
                return $this->responseError(new XenForo_Phrase('requested_log_entry_not_found'));
            }

            $viewParams = array(
                    'transaction' => $transaction
            );

            return $this->responseView('XenCentral_AdServer_ViewAdmin_CreditTransaction_View', 'xcas_credit_transaction_details', $viewParams);
        }

        $conditions = $this->_input->filter(array(
                'transaction_id' => XenForo_Input::STRING,
                'username' => XenForo_Input::STRING,
                'user_id' => XenForo_Input::UINT
        ));

        if ($conditions['username']) {
            /** @var XenForo_Model_User $userModel */
            $userModel = $this->getModelFromCache('XenForo_Model_User');
            $user = $userModel->getUserByName($conditions['username']);
            if (!$user) {
                return $this->responseError(new XenForo_Phrase('requested_user_not_found'));
            }

            $conditions['user_id'] = $user['user_id'];
            $conditions['username'] = '';
        }

        foreach ($conditions AS $condition => $value) {
            if (!$value) {
                unset($conditions[$condition]);
            }
        }

        $page = $this->_input->filterSingle('page', XenForo_Input::UINT);
        $perPage = 20;

        $totalTransactions = $this->_getCreditLogModel()->countTransactionLogs($conditions);

        $creditTransactions = $this->_getCreditLogModel()->getUserTransactions($conditions, array(
                'page' => $page,
                'perPage' => $perPage
        ));

        $viewParams = array(
                'transactions' => $creditTransactions,
                'totalTransactions' => $totalTransactions,
                'page' => $page,
                'perPage' => $perPage,
                'conditions' => $conditions
        );

        return $this->responseView('XenCentral_AdServer_ViewAdmin_CreditTransaction_List', 'xcas_credit_transaction_list', $viewParams);
    }

    public function actionSaveCredits()
    {
        $criteria = $this->_input->filterSingle('criteria', XenForo_Input::JSON_ARRAY);
        $criteria = $this->_filterUserSearchCriteria($criteria);

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

        $page = 1;
        $usersPerPage = 100000;


        $fetchOptions = array(
            'perPage' => $usersPerPage,
            'page' => $page,
            'join' => XenForo_Model_User::FETCH_USER_FULL,
            'order' => $order,
            'direction' => $direction,
            XenCentral_AdServer_Model_XenForo_User::FETCH_USER_CREDITS=>1
        );

        $userModel = $this->_getUserModel();

        $criteriaPrepared = $this->_prepareUserSearchCriteria($criteria);

        $totalUsers = $userModel->countUsers($criteriaPrepared);
        if (!$totalUsers) {
            return $this->responseError(new XenForo_Phrase('no_users_matched_specified_criteria'));
        }

        if ($this->getInput()->filterSingle('active', XenForo_Input::BOOLEAN)) {
            if ($totalUsers == 1) {
                $users = $userModel->getUsers($criteriaPrepared, $fetchOptions);
                $user = reset($users);
                return $this->responseMessage(
                    new XenForo_Phrase('xcas_one_user_matching_criteria', array('username' => $user['username'], 'credit' => $user['ad_credit']))
                );
            }
            return $this->responseMessage(
                new XenForo_Phrase('xcas_x_users_matching_criteria', array('x' => $totalUsers))
            );
        }

        $users = $userModel->getUsers($criteriaPrepared, $fetchOptions);

        $creditCount = $this->getInput()->filterSingle('credit_count', XenForo_Input::UNUM);
        $mode = $this->getInput()->filterSingle('mode', XenForo_Input::STRING);

        foreach ($users AS $user) {
            $currentCredits = floatval($user['ad_credit']);
            switch ($mode) {
                case 'set':
                    $currentCredits = $creditCount;
                    break;
                case 'add':
                    $currentCredits = $creditCount + $currentCredits;
                    break;
                case 'subtract':
                    $currentCredits = $currentCredits - $creditCount;
                    break;
            }
            if($user['ad_credit']!=$currentCredits) {
                $user['ad_credit']=$currentCredits;
                $userModel->updateAdServerUserInfo($user);
                $this->_getCreditLogModel()->logAdminCredit($user['user_id'], time(), XenForo_Visitor::getUserId(), $mode, $creditCount);
            }
        }

        // do actual update
        return $this->responseMessage(
            new XenForo_Phrase('xcas_x_user_invites_are_updated', array(
                'count'=> $totalUsers
            ))
        );
    }

    /**
     * @return XenCentral_AdTrading_Model_XenForo_User
     */
    protected function _getXfUserModel()
    {
        return $this->getModelFromCache('XenForo_Model_User');
    }

    protected function _filterUserSearchCriteria(array $criteria)
    {
        return $this->_getCriteriaHelper()->filterUserSearchCriteria($criteria);
    }

    protected function _prepareUserSearchCriteria(array $criteria)
    {
        return $this->_getCriteriaHelper()->prepareUserSearchCriteria($criteria);
    }

    /**
     * @return XenForo_ControllerHelper_UserCriteria
     */
    protected function _getCriteriaHelper()
    {
        return $this->getHelper('UserCriteria');
    }

    /**
     * @return XenCentral_AdServer_Model_XenForo_User
     */
    protected function _getUserModel()
    {
        return $this->getModelFromCache('XenForo_Model_User');
    }

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


}
