<?php

class DefaultController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array(
                    'index',
                    'create',
                    'update',
                    'delete'
                ),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function renderTimePicker($data, $row, $column)
    {
        $this->renderPartial('timePickerInput', array('data' => $data, 'row' => $row, 'column' => $column));
    }

    public function renderDateTimePicker($data, $row, $column)
    {
        $attributeName = $column->name;
        $name = 'DateTimeRule[' . $data->type . '][' . $row . '][' . $data->id . '][' . $attributeName . ']';

        $datePattern = phpUserDatePattern();
        $userTimeFormat = userPatternForTimeFormat(PhonalisaDate::TimePatternWithoutSeconds, PhonalisaDate::TimePatternWithMeridiem);
        $dateTimePickerPattern = $datePattern . ' ' . $userTimeFormat;
        $value = null;
        if ($data->$attributeName != null && $data->$attributeName != "") {
            $dateTime = DateTimeRule::changeDateTimeWithTimezoneToNormalTime($data->$attributeName);
            $value = PhonalisaDate::convertServerDateTo($dateTimePickerPattern, $dateTime);
        }

        $textHtmlOptions = array(
            "readonly" => "readonly",
            "placeholder" => __("DATE_TIME_RULE_MODEL_DATE_PLACEHOLDER"),
            "class" => "span2 " . $column->name,
            "size" => "16",
            "type" => "text",
            "style" => "width:120px",
            "data-custom-contexthelp-key" => "DATETIMERULE_" . strtoupper($attributeName) . "_CUSTOM_CONTEXT_HELP"
        );

        $startDate = date('Y-m-d H:i');
        $timePickerStartDate = PhonalisaDate::userDateTime($startDate);

        $this->renderPartial(
                'dateTimePickerInput', array(
            'attributeName' => $attributeName,
            'timePickerStartDate' => $timePickerStartDate,
            'dateTimePickerPattern' => $dateTimePickerPattern,
            'textHtmlOptions' => $textHtmlOptions,
            'value' => $value,
            'name' => $name
                )
        );
    }

    public function renderWeekdayCheckBox($data, $row, $column)
    {
        $attributeName = $column->name;
        $name = 'DateTimeRule[' . $data->type . '][' . $row . '][' . $data->id . '][' . $attributeName . ']';
        $checked = $data->$attributeName;
        $htmlOptions = array(
            'value' => '1',
            "data-custom-contexthelp-key" => "DATETIMERULE_WEEKDAY_CHECKBOX_CUSTOM_CONTEXTHELP"
        );

        $this->renderPartial("weekdayCheckbox", array(
            "name" => $name,
            "checked" => $checked,
            "htmlOptions" => $htmlOptions
        ));
    }

    /**
     * Creates a new Profile model and it's DateTimeRule child models.
     */
    public function actionCreate()
    {
        $dateTimeProfile = new DateTimeProfile();
        $dateTimeRule = new DateTimeRule();

        $this->performAjaxValidation($dateTimeProfile);
        $this->performAjaxValidation($dateTimeRule);

        if (isset($_POST['DateTimeProfile'])) {

            $dateTimeProfile->attributes = $_POST['DateTimeProfile'];
            $dateTimeProfile->save();
        }

        if (isset($_POST['DateTimeRule'][DateTimeRuleType::dateRule])) {
            $this->processIncommingDateTimeRuleData($_POST['DateTimeRule'][DateTimeRuleType::dateRule], $dateTimeProfile->id, DateTimeRuleType::dateRule);
        }

        if (isset($_POST['DateTimeRule'][DateTimeRuleType::weekRule])) {
            $this->processIncommingDateTimeRuleData($_POST['DateTimeRule'][DateTimeRuleType::weekRule], $dateTimeProfile->id, DateTimeRuleType::weekRule);
        }

        $this->renderPartialWithContextHelp(
                '_form', array(
            'dateTimeProfile' => $dateTimeProfile,
            'dateTimeRule' => $dateTimeRule,
            'userTimeFormat' => $this->getSudoUserTimeFormat()
                ), false, true
        );
    }

    /**
     * Updates a particular DateTimeProfile model and it's DateTimeRule child models.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        $dateTimeRule = new DateTimeRule();

        $this->performAjaxValidation($model);
        $this->performAjaxValidation($dateTimeRule);

        if (isset($_POST['DateTimeProfile'])) {

            $model->attributes = $_POST['DateTimeProfile'];
            if ($model->save()) {
                $oldRules = DateTimeRule::model()->findAllByAttributes(array('parentId' => $id));
                foreach ($oldRules as $oldRule) {
                    $oldRule->delete();
                }
            }

            if (isset($_POST['DateTimeRule'][DateTimeRuleType::dateRule])) {
                $this->processIncommingDateTimeRuleData($_POST['DateTimeRule'][DateTimeRuleType::dateRule], $id, DateTimeRuleType::dateRule);
            }

            if (isset($_POST['DateTimeRule'][DateTimeRuleType::weekRule])) {
                $this->processIncommingDateTimeRuleData($_POST['DateTimeRule'][DateTimeRuleType::weekRule], $id, DateTimeRuleType::weekRule);
            }
        }

        $this->renderPartialWithContextHelp('_form', array(
            'dateTimeProfile' => $model,
            'dateTimeRule' => $dateTimeRule,
            'userTimeFormat' => $this->getSudoUserTimeFormat()
                ), false, true);
    }

    private function processIncommingDateTimeRuleData($incommingData, $parentId, $type)
    {
        foreach ($incommingData as $dataId => $postAttributes) {
            $ruleModel = $this->getModelFromAttributes($postAttributes);
            if (!$ruleModel) {
                continue;
            } else {
                $ruleModel->parentId = $parentId;
                $ruleModel->type = $type;
                $ruleModel->save();
            }
        }
    }

    private function getModelFromAttributes($postAttributes)
    {
        foreach ($postAttributes as $id => $attributes) {

            unset($postAttributes[$id]['sort']);

            if (!$this->isEmptyPost($attributes)) {
                $model = new DateTimeRule();
                $model->attributes = $attributes;
                return $model;
            }
        }
        return false;
    }

    private function isEmptyPost($attributes)
    {
        $emptyAttributes = true;

        foreach ($attributes as $attributesName => $attributesValue) {

            if (!trim($attributesValue)) {
                $attributes[$attributesName] = null;
            } else {
                $emptyAttributes = false;
            }
        }
        return $emptyAttributes;
    }

    private function getSudoUserTimeFormat()
    {
        $user = app()->user->sudoUserInstance;
        if (!$user) {
            app()->user->logout();
            app()->user->loginRequired();
        }
        return $user->timeFormat;
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            //we only allow deletion via POST request
            $this->loadModel($id)->delete();

            //if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = new DateTimeProfile('search');
        if (isset($_GET['DateTimeProfile'])) {
            $model->attributes = $_GET['DateTimeProfile'];
        }

        $this->render('index', array('model' => $model));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = DateTimeProfile::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'date-time-profile-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
