<?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',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				//'users'=>array('@'),
				'expression'=>AccessManager::checkSessionPermission($this->module->name),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				//'users'=>array('@'),
				'expression'=>AccessManager::checkSessionPermission($this->module->name),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				//'users'=>array('@'),
				'expression'=>AccessManager::checkSessionPermission($this->module->name),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

    public function getParentPermissions($groupId,&$currentGroup) {
        $currentGroup = Groups::model()->findByPk($groupId);
        $parentId = $currentGroup->parent;
        $parentIds = array();
        $parentIds[] = $parentId ;
        while($parentId != '0') {

            $parentIds[] = $parentId;
            $parendGroup = Groups::model()->findByPk($parentId);
            $parentId = $parendGroup->parent;
        }
        $parentIds = array_reverse($parentIds);
        $parentWebPermissions = array();
        foreach ($parentIds as $id) {

            $webPermissions = WebGuiPermissions::model()->findByAttributes(array('groupId'=>$id));
            
            if (isset($webPermissions)) {
                $parentWebPermissions = array_merge($parentWebPermissions , (array)json_decode($webPermissions->permissions ));
            }
        }
       
        return $parentWebPermissions;
    }

	public	function getModuleData(&$currentGroup=null) {
	
	$data = array();
        $groupId = $this->getCurrentGroupId();
		$modules = ModuleManager::getDeclaredModules();
                AccessManager::filterDeclaredModules($modules);
		$id = 0;
		$existingSections = array();
        $parentWebGuiPermissions = $this->getParentPermissions($groupId,$currentGroup);
        $webGuiPermissions = WebGuiPermissions::model()->findByAttributes(array('groupId'=>$groupId));
        if ($webGuiPermissions) {
            $webGuiPermissions = (array)json_decode($webGuiPermissions->permissions);
        } else {
            $webGuiPermissions = array();
        }

//calendar
//calendarGeneral

	$notShown = array('gii','calendarGeneral','calendar','addressbookAddresses','homeUCItem','home');

	foreach ($modules as $moduleName => $modulAttributes) {

            $hasPermission = '0';
            $disabled = '0';
            
            if (array_key_exists($moduleName,(array)$webGuiPermissions)) {
                $hasPermission = '1';
            }

            if (array_key_exists($moduleName,(array)$parentWebGuiPermissions)) {
                $hasPermission = '1';
                $disabled = '1';
            }
            
            
			if ( in_array($moduleName,$notShown)) {
				continue;
			}

			if (isset($modulAttributes['type']) && $modulAttributes['type'] == 'main'){
				$data[] = array(
						'id'=>$id,
						'name'=>__($modulAttributes['sectionTitle']),
						'type'=>'section',
				);
				$existingSections[] = $modulAttributes['section'];
				$id++;
			}
			
			if (!isset($modulAttributes['uiModule']) || $modulAttributes['uiModule'] == false) {
				
				continue;
			}
			
			$data[] = array(
					'id'=>$id,
					'type'=>'module',
					'name'=>$moduleName,
					'section'=>$modulAttributes['section'],
					'hasPermission'=>$hasPermission,
					'disabled'=>$disabled,
					//'sectionTitle'=>$modulAttributes['sectionTitle'],
					//'mainSectionModule'=>$modulAttributes['mainSectionModule'],
					'title'=>$modulAttributes['title'],
					'description'=>$modulAttributes['description'],
					);
			$id++;
		}

		return $data;
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			
			$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('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{

	  if (isset($_POST['saveWebGuiPermissions'])) {
		  $this->actionAdmin();
	  }
	  $currentGroup = null;
	  $data = $this->getModuleData($currentGroup);

	  $dataProvider = new CArrayDataProvider($data,array('pagination'=>false));
  
	  $moduleCcolumn = WebGuiPermissions::model()->getModuleColumn();
	
	  $this->render('admin',array('dataProvider'=>$dataProvider,'moduleColumn'=>$moduleCcolumn,'currentGroup'=>$currentGroup));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {



	    if (isset($_POST['WebGuiPermissions'])) {
            $permissionsArray=array();
            foreach ($_POST['WebGuiPermissions'] as $modileNmae => $hasPermission) {
                if ($hasPermission) {
                    $permissionsArray[$modileNmae ] = $hasPermission;
                } 
            }

            $model = WebGuiPermissions::model()->findByAttributes(array('groupId'=>$this->getCurrentGroupId()));

            if (!$model) {
                $model = new WebGuiPermissions;
            }
            if (!empty($permissionsArray)) {
                $model->groupId = $this->getCurrentGroupId();
                $model->permissions = json_encode( $permissionsArray);
                
                if ( $model->save() ) {
                    AccessManager::getModulesForCurrentSession();
                }
            }else {
                if (!$model->isNewRecord()) {
                    $model->delete();
                } 
            }
        }
    }

	/**
	 * 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=WebGuiPermissions::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}    
            
    public function getNavBarGroupDropdown() {
        $groups = Groups::model()->getNestedGroupList();
        $items = array();
        foreach ($groups as $groupId => $groupLabel) {
            $items[] = array(
                    'label'=>$groupLabel,
                    'url'=>url('adminWebGuiPermissions/default/index',array('id'=>$groupId)),
                    'active'=>'0',
            );
        }
        

        return $items;
    }

    public function getCurrentGroupId() {
        if (!isset($_GET['id'])) {
            return Groups::model()->findByAttributes(array('type'=>'allUsers'))->id;
        } else {

            return $_GET['id'];
        }
    }

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

    public function getGroupColumn() {
        $groupId = $this->getCurrentGroupId();
        $group = Groups::model()->findByPk($groupId);
       
        return array(
        	'header'=>__('WEBGUIPERMISSIONS_HEADER_PERMISSION'),
        	'headerHtmlOptions'=>array('data-translation-id'=>'WEBGUIPERMISSIONS_HEADER_PERMISSION'),
            'name'=>$group->name,
            'value'=>array($this,'renderPermissionsCheckBox'),
        );
    }
}