<?php
class Admin_DomainController extends Zend_Controller_Action 
{
	
	public function init()
	{
	    
		//$this->log = Zend_Registry::get('log');
		$this->view->addHelperPath('library/Atmail/View/Helper/', 'Atmail_View_Helper');
		$this->_helper->pluginCall('initAdminController', $this);
		
		$this->request  = $this->getRequest();
		$this->requestParams = $this->request->getParams();
		
		$this->view->baseUrl = $this->request->getBaseUrl();
		$this->view->appBaseUrl = $this->request->getBaseUrl() . (strpos($this->request->getBaseUrl(),'index.php')?'':'/index.php');
		$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
		$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->requestParams['module']=='default'?'':'/' . $this->requestParams['module']);
		$this->view->global = Zend_Registry::get('config')->global;
		
		$this->_helper->viewRenderer->setNoRender();
		if( !isset($this->view->errors) )
		{
			    
			$this->view->errors = array();
			
		}
		if( !isset($this->view->notices) )    
		{
			
			$this->view->notices = array();
			
		}
	 	if( !isset($this->view->jsonIdsToRender) )    
		{
			
			$this->view->jsonIdsToRender = array();
			
		}
		require_once 'library/jQuery/jQuery.php';
		require_once 'application/models/admin.php';

		$this->admin = new admin();
        $this->adminInfo = $this->view->userData = $this->admin->getCurrentAdminData();

	}
	
	public function preDispatch() 
	{
		
		// Check the session is active, otherwise redirect to the login page
        // Commented out below, it is set in init() so should not be needed here as well
		//$this->view->userData = $this->admin->getCurrentAdminData();
		
		if( empty($this->view->userData) ) 
		{

			$this->_forward( 'timeout', 'index', 'default' );
			return;			

		}
		
		Atmail_Locale::setupLocaleAndTranslation( $this->view->userData['Language'] );
		
	}
	
	public function fetchAction() 
	{

		$this->view->domains = $this->admin->domainList(array('page' => ($this->requestParams['page'] + 1), 'pageSize' => $this->requestParams['pageSize']));
		
		$total = 0;
		$html = '';
		foreach($this->view->domains as $domain)
		{
			$total ++;
			$html .= '<li style=\"display:none;\" GroupID=\"\" groupType=\"domain\" DomainName=\"' . $domain['DomainName'] . '\" id=\"\" class=\"' . (($this->view->currentDomain == $domain['DomainName']) ? ' current' : '') . '\"><a class=\"groupLink\" href=\"#\"><span class=\"label\"><span class=\"' . (($domain['enabled'] == 1)? 'labelname' : 'domain_disabled') . '\">' . $domain['DomainName'] . '</span>' . (($domain['totalUsers']==0) ? '<span class=\"unread\" style=\"display:none;\">' : '<span class=\"unread\">') . '<strong>' . $domain['totalUsers'] . '</strong></span></span></a></li>';
		}

		if($total)
		{
			jQuery::evalScript('if(!$("#Users").is(".ui-tabs-hide")) { $("#secondary #nav_secondary li[grouptype=\"domain\"]:last", "#Users").after("' . $html . '"); $("#secondary #nav_secondary li[grouptype=\"domain\"]:hidden", "#Users").each(function() { $(this).find("a.groupLink").bind("click", function() { listUsersClick(this) } ); $(this).slideDown("normal"); } ); }');
		}
		
		
		if($this->requestParams['page'] + 1 <= $this->requestParams['total'])
		{
			jQuery::evalScript('if(!$("#Users").is(".ui-tabs-hide")) $.php("' . $this->view->moduleBaseUrl . '/domain/fetch/page/' . ($this->requestParams['page'] + 1). '/total/' . $this->requestParams['total'] . '/pageSize/' . $this->requestParams['pageSize'] . '");');
		}
		
		$this->render('global/jsonresponse', null, true);
	}
	
	public function createAction() 
	{
		$this->_helper->pluginCall("createDomainAction");
        
		if( $this->view->global['demo'] == 1 ) 
		{
		
			jQuery::addError('Disabled in online demo');
			jQuery::evalScript('$(\'li[NewDomain=1]\').remove()');
			$this->render('global/jsonresponse', null, true);
			return;
		
		}
		
		// Check to see if the username form field only contains legal characters
		$findIllegalInput = new Zend_Validate_Regex("/[^a-zA-Z0-9_.-]/");
		$foundIllegalInNewGroupName = $findIllegalInput->isValid($this->requestParams['newGroupName']);
		
        if ( $foundIllegalInNewGroupName )
		{
		
			jQuery::addError('Failed adding new ' . ($this->requestParams['type']=='domain'?'domain':($this->requestParams['type']=='user'?'user group':'group')) . ': ' . "Bad characters");
			jQuery::evalScript('$(\'li[newgroup=1]\').remove()');
			$this->render('global/jsonresponse', null, true);
            return;
		}
		
		if( $this->requestParams['type'] == 'domain' )
		{
			
			$result = $this->admin->domainCreate( $this->requestParams['newGroupName'] );
		
		}
		else if( $this->requestParams['type'] == 'user' )
		{
			
			$result = $this->admin->groupCreate( array('groupName' => $this->requestParams['newGroupName']) );
			
		}
		
		if($result['status'] != 'failed') 
		{

			// Remove the NewDomain flag
			jQuery::evalScript('$(\'li[groupname=' . $this->requestParams['newGroupName'] . ']\').each( function () 
			{ 
				
				$(this).attr(\'newgroup\', \'0\');
				
			})');

		}
		else
		{

			jQuery::addError('Failed adding new ' . ($this->requestParams['type']=='domain'?'domain':($this->requestParams['type']=='user'?'user group':'group')) . ': ' . $result['response']);
			jQuery::evalScript('$(\'li[newgroup=1]\').remove()');

		}

		$this->render('global/jsonresponse', null, true);

	}

	public function removeAction() 
	{
		$this->_helper->pluginCall("startRemoveDomainAction");
        
		if( $this->view->global['demo'] == 1 )
		{
			
			throw new Exception('Disabled in online demo');
			
		}
		
		//TODO: discover if it is a user group or domain and delete accordingly.
		
		$result = $this->admin->domainDelete($this->requestParams['name']);

		if($result['status'] != 'failed') 
		{
		
			// Remove the NewDomain flag
			jQuery::evalScript('$(\'li[DomainName=' . $this->requestParams['name'] . ']\').remove()');
			
		}
		else
		{
			
			throw new Exception($result['response']);
			
		}

        $this->_helper->pluginCall("endRemoveDomainAction");
		$this->render('/global/jsonresponse', null, true);                                                                                                 
	}
	
	public function removegroupAction() 
	{
		$this->_helper->pluginCall("startRemoveGroupAction");
        
		if( $this->view->global['demo'] == 1 )
		{
			
			throw new Exception('Disabled in online demo');
			
		}
		
		//TODO: discover if it is a user group or domain and delete accordingly.
		
		$result = $this->admin->groupDelete($this->requestParams['groupname']);

		if($result['status'] != 'failed') 
		{
		
			// Remove the NewDomain flag
			jQuery::evalScript('$(\'li[groupname=' . $this->requestParams['groupname'] . ']\').remove()');
			
		}
		else
		{
			
			throw new Exception($result['response']);
			
		}

        $this->_helper->pluginCall("endRemoveGroupAction");
        
		$this->render('/global/jsonresponse', null, true);                                                                                                 
	}
	

	public function viewAction() 
	{
		
		$this->view->contact = $this->admin->userView($this->requestParams['name']);
		$this->view->jsonIdsToRender['contact_info'] = 'users/viewuser.phtml';
		$this->render('/global/jsonresponse', null, true);                                                                                                 
	
	}
	
	public function checkAction() 
	{
		
		$result = $this->admin->domainCheck($this->requestParams['name']);
		
		if($result['status'] == 'failed')
		{
			 
			throw new Exception($result['response']);
			
		}
		
		$this->render('/global/jsonresponse', null, true);
		                              
	}
	
	public function disableAction()
	{
        if( $this->view->global['demo'] == 1 ) 
		{
		
			throw new Exception('Disabled in online demo');
		
		}
		
		$result = $this->admin->domainLock($this->requestParams['name']);

		if($result['status'] != 'failed')  
		{
		
			// Remove the NewDomain flag
			jQuery::evalScript('$("#Users #folder_unlock a").removeClass("disabled");$("#Users #folder_lock a").addClass("disabled"); $("#Users li.current a span span").addClass("domain_disabled")');
		
		}
		else
		{
		
			throw new Exception($result['response']);
		
		}

		$this->render('/global/jsonresponse', null, true);
		
    }
    
	public function enableAction()
	{
        if( $this->view->global['demo'] == 1 ) 
		{
		
			throw new Exception('Disabled in online demo');
		
		}
		
		$result = $this->admin->domainUnlock($this->requestParams['name']);

		if($result['status'] != 'failed')  
		{
		
			// Remove the NewDomain flag
			jQuery::evalScript('$("#Users #folder_lock a").removeClass("disabled"); $("#Users #folder_unlock a").addClass("disabled"); $("#Users li.current a span span").removeClass("domain_disabled")');
		
		}
		else
		{
		
			throw new Exception($result['response']);
		
		}

		$this->render('/global/jsonresponse', null, true);

    }	

}
