<?php

class DefaultController extends AnalyticController
{

    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'createReport', 'ajaxRefreshNavBar'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex($id = null)
    {

        $model = $this->getModel($id);
        $items = $this->getNavBarItems(
            $model,
            isset($_GET['range']) ? $_GET['range'] : Statistic::StatisticTimeRangeTypeDay,
            $id
        );
        $this->render('index', array('model' => $model, 'items' => $items));
    }

    public function actionCreateReport()
    {   
        return parent::actionCreateReport();
    }

    public function getDailyOutput($year, $targetId, $DOY)
    {
        
        $attributes = array();
        $attributes["year"] = $year;
        $attributes["target_id"] = $targetId;
        $attributes["target_type"] = $this->getTargetType();
        $attributes["time_range_type"] = Statistic::StatisticTimeRangeTypeDay;
        $attributes["day"] = $DOY;

        $stat = Statistic::model()->findByAttributes($attributes);
        if ($stat == null) {
            $stat = new Statistic();
        }
        $output = "State," . __("ANALYTIC_LEGEND_SUCCESSFULL") . "," . __("ANALYTIC_LEGEND_MISSED");
        for ($i = 0; $i < 24; $i++) {
            $fromHour = sprintf('%02d', $i);
            $toHour = sprintf('%02d', $i + 1);

            if (PhonalisaDate::useMeridianTimeFormat()) {
                $fromHour = DateTime::createFromFormat('H', $fromHour)->format('ga');
            }

            $output .= "\n" . $fromHour . ",";
            $output .= $stat->getAllSuccessCallsForHour($i) . ",";
            $output .= $stat->getAllMissedCallsForHour($i);
        }
        return $output;
    }

    public function getWeeklyOutput($year, $targetId, $DOY)
    {
        $attributes = array();
        $attributes["year"] = $year;
        $attributes["target_id"] = $targetId;
        $attributes["target_type"] = $this->getTargetType();
        $attributes["time_range_type"] = Statistic::StatisticTimeRangeTypeDay;
        $days = array();
        for ($i = 0; $i < 7; $i++) {
            $dayNumber = date('w', strtotime($DOY . "+" . $i . "day"));
            $translatedDay = Yii::app()->locale->getWeekDayName($dayNumber, 'abbreviated');
            $days[$translatedDay] = date('z', strtotime($DOY . "+" . $i . "day")) + 1;
        }
        $output = "State," . __("ANALYTIC_LEGEND_SUCCESSFULL") . "," . __("ANALYTIC_LEGEND_MISSED");

        foreach ($days as $dayName => $dayNumber) {
            $attributes["day"] = $dayNumber;
            $stat = Statistic::model()->findByAttributes($attributes);

            if ($stat == null) {
                $stat = new Statistic();
            }
            $succes = 0;
            $missed = 0;
            foreach (range(0, 23) as $h) {
                $succes = $succes + $stat->getAllSuccessCallsForHour((string) $h);
                $missed = $missed + $stat->getAllMissedCallsForHour((string) $h);
            }

            $output.= "\n" . $dayName . "," . $succes . "," . $missed;
        }

        return $output;
    }

    public function getMonthlyOutput($year, $targetId, $month)
    {

        $attributes = array();
        $attributes["year"] = $year;
        $attributes["target_id"] = $targetId;
        $attributes["target_type"] = $this->getTargetType();
        $attributes["time_range_type"] = Statistic::StatisticTimeRangeTypeDay;
        $DOY = date('z', strtotime($year . '-' . $month . '-01')) + 1;

        $output = "State," . __("ANALYTIC_LEGEND_SUCCESSFULL") . "," . __("ANALYTIC_LEGEND_MISSED") . "\n";

        $daysOfMonth = date('t', mktime(0, 0, 0, (int) $month, 1, (int) $year));

        //for($i=1;$i<(cal_days_in_month(CAL_GREGORIAN, (int)$month, (int)$year)+1);$i++) {
        for ($i = 1; $i < ($daysOfMonth + 1); $i++) {
            $attributes['day'] = $DOY + $i - 1;
            $stat = Statistic::model()->findByAttributes($attributes);

            if (!$stat) {
                $stat = new Statistic();
            }
            $succes = 0;
            $missed = 0;
            foreach (range(0, 23) as $h) {
                $succes = $succes + $stat->getAllSuccessCallsForHour((string) $h);
                $missed = $missed + $stat->getAllMissedCallsForHour((string) $h);
            }
            $output.=$i . '. ,' . $succes . ',' . $missed . "\n";
        }

        return $output;
    }

    public function getYearlyOutput($year, $targetId)
    {
        $attributes = array();
        $attributes["year"] = $year;
        $attributes["target_id"] = $targetId;
        $attributes["target_type"] = $this->getTargetType();
        $attributes["time_range_type"] = Statistic::StatisticTimeRangeTypeMonth;

        $output = "State," . __("ANALYTIC_LEGEND_SUCCESSFULL") . "," . __("ANALYTIC_LEGEND_MISSED") . "\n";
        for ($month = 1; $month <= 12; $month++) {
            $attributes['month'] = $month;
            $stat = Statistic::model()->findByAttributes($attributes);
            if ($stat == null) {
                $stat = new Statistic();
            }
            $succes = isset($stat->counter_success) ? $stat->counter_success : 0;

            $output.= Yii::app()->locale->getMonthName($month, 'abbreviated');
            $output.=',' . $succes . ',' . $stat->getAllMissedCalls() . "\n";
        }

        return $output;
    }

    public function getNavbarItems($model, $rangeType, $id, $date = null, $week = null)
    {

        $targetDropdownValues = $this->getNavBarTargetDropdown();
        $currentModel = $model->findByPk($id);

        if (!$currentModel) {
            $currentModel = $model;
        }

        if ($currentModel->getFormattedName()) {

            $dropdownLabel = $currentModel->formattedName;
        } else {

            $dropdownLabel = __('STATISTIC_NO_DATA');
        }

        $items = array(
            array(
                'class' => 'bootstrap.widgets.TbMenu',
                'id' => 'targetDropdown',
                'encodeLabel' => false,
                'items' => array(
                    !$targetDropdownValues ? array('label' => CHtml::encode($dropdownLabel), 'url' => '#') :
                        array(
                        'class' => 'bootstrap.widgets.TbMenu',
                        'items' => $targetDropdownValues,
                        '---',
                        'label' => CHtml::encode($dropdownLabel),
                        'linkOptions' => array(
                            'data-translation-id' => 'ANALYTICS_TARGET_DROPDOWN_LABEL',
                        ),
                        ),
                    array(
                        'label' => Statistic::readable($rangeType),
                        'items' => $this->getNavRangeDropdown($model, $rangeType),
                        'linkOptions' => array(
                            'data-translation-target' => 'ANALYTICS_TARGET_DROPDOWN_LABEL',
                        ),
                    ),
                ),
            ),
            $rangeType == Statistic::StatisticTimeRangeTypeDay ? $this->getParentView(
                'dayPicker',
                array(
                    'model' => $model
                )
            ) : '',
            $rangeType == Statistic::StatisticTimeRangeTypeWeek ? $this->getParentView(
                'weekPicker',
                array(
                    'model' => $model,
                    'date' => $date,
                    'week' => $week
                )
            ) : '',
            $rangeType == Statistic::StatisticTimeRangeTypeMonth ? $this->getParentView(
                'monthPicker',
                array(
                    'model' => $model
                )
            ) : '',
            $rangeType == Statistic::StatisticTimeRangeTypeYear ? $this->getParentView(
                'yearPicker',
                array(
                    'model' => $model
                )
            ) : '',
            $this->renderPartial('toggleViewModeButton', array('model' => $model), true)
        );

        return $items;
    }

    public function actionAjaxRefreshNavBar($id, $date, $week = null)
    {
        if (!$week) {
            $week = (int) date('W');
        }
        $model = $this->getModel($id);
        $items = $this->getNavBarItems(
            $model,
            isset($_GET['range']) ? $_GET['range'] : Statistic::StatisticTimeRangeTypeDay,
            $id,
            $date,
            $week
        );
        echo $this->renderPartial('navbar', array('items' => $items), true, true);
    }

    public function getModel($id = null)
    {
        $model = null;
        $permission = new Permissions();
        $user = app()->user->realUserInstance;
        if (!$user) {
            app()->user->logout();
            app()->user->loginRequired();
        }

        $permissionsByModelType[] = $permission->getPermissionsArray(
            array('groupId' => $user->group, 'type' => 'statisticGroup'),
            true
        );
        $permissionsByModelType[] = $permission->getPermissionsArray(
            array('groupId' => $user->group, 'type' => 'statisticQueues'),
            true
        );
        $itemIds = array();
        foreach ($permissionsByModelType as $permissions) {
            foreach ($permissions as $permissionAttributes) {
                $itemIds[] = $permissionAttributes['itemId'];
            }
        }
        //add child groups to permissions array
        foreach ($itemIds as $itemId) {
            $group = Groups::model()->findByPk($itemId);
            if ($group) {
                foreach ($group->getChildren(true) as $child) {
                    $itemIds[] = $child->id;
                }
            }
        }
        // return Model by Pk if user has permission
        if ($id) {
            if (in_array($id, $itemIds)) {

                foreach ($this->getAvailableModels() as $modelName) {
                    $model = $modelName::model()->findByPk($id);
                    if ($model && $model->extension) {
                        return $model;
                    }
                }
            }
        }

        // return the first found model with extension from permissions array
        // FIXME : may be sort them by formatted name
        foreach ($this->getAvailableModels() as $modelName) {
            foreach ($itemIds as $id) {
                $model = $modelName::model()->findByPk($id);
                if ($model && $model->extension) {
                    return $model;
                }
            }
        }
        // if there is no model with extension and/or permission return a new model
        return new Groups();
    }

    public function getNavBarTargetDropdown(&$model = null)
    {
        $items = array();
        $user = app()->user->sudoUserInstance;
        if (!$user) {
            app()->user->logout();
            app()->user->loginRequired();
        }
        $permission = new Permissions();
        $this->getNavEntrys($items, $user, $permission, 'Groups');
        $this->getNavEntrys($items, $user, $permission, 'Queue');
        return $items;
    }

    public function getNavEntrys(&$items, $user, $permission, $modelName)
    {

        if ($modelName == 'Groups') {

            $permissions = $permission->getPermissionsArray(
                array('groupId' => $user->group, 'type' => 'statisticGroup'),
                true
            );
        } else {
            $permissions = $permission->getPermissionsArray(
                array('groupId' => $user->group, 'type' => 'statisticQueues'),
                true
            );
        }

        $allGroups = array();
        if (empty($permissions)) {
            return;
        }

        $headerIsSet = false;
        foreach ($permissions as $id => $attributes) {

            $group = $modelName::model()->findByPk($attributes['itemId']);
            if ($group && $group->extension) {
                if (!$headerIsSet) {
                    $items[] = array(
                        'label' => $modelName == "Groups" ? __('GROUPS') : __('QUEUES'),
                        'active' => '0',
                    );
                    $headerIsSet = true;
                }
            }

            if ($modelName == "Groups") {
                $children = $group->getChildren(true);
                $groups = array_merge(array($group), $children);
                foreach ($groups as $group) {
                    if ($group->extension) {
                        $allGroups[$group->name] = $group;
                    }
                }
            } else {
                if ($group->extension) {
                    $allGroups[$group->name] = $group;
                }
            }
        }

        //sorting Groups by Name
        ksort($allGroups);
        $allGroups = array_values($allGroups);
        $type = $modelName == "Groups" ? Statistic::StatisticTargetTypeGroup : Statistic::StatisticTargetTypeQueue;
        $range = isset($_GET['range']) ? $_GET['range'] : 0;

        foreach ($allGroups as $group) {
            if ($group->extension) {
                $items[] = array(
                    'label' => '<' . $group->extension . '> ' . CHtml::encode($group->name),
                    'url' => url(
                        'analyticsDailyReport/default/index',
                        array(
                            'id' => $group->id,
                            'type' => $type,
                            'range' => $range
                        )
                    ),
                    'active' => '0',
                    'linkOptions' => array(
                        'class' => 'target',
                        'data-model-id' => $group->id,
                        'data-target-type' => $modelName == "Groups" ? Statistic::StatisticTargetTypeGroup : Statistic::StatisticTargetTypeQueue,
                    )
                );
            }
        }
    }
}
