<?php
class Admin_SubadminsController extends Zend_Controller_Action 
{
	
	public function init()
	{
	    
		//$this->log = Zend_Registry::get('log');
		
		$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->request->module == 'default'?'':DIRECTORY_SEPARATOR . $this->request->module);
		$this->view->global = Zend_Registry::get('config')->global;
        
		require_once 'application/models/admin.php';
		
		$this->admin = new admin();
		
		// check is an XML request or not only allow index to be rendered normally (i.e. full page load)
		if ($this->request->action == 'index' )
		{
			return;
			
		}
			
		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';

	}
	
	public function preDispatch() 
	{
		
		// Check the session is active, otherwise redirect to the login page
		$this->view->userData = $this->admin->getCurrentAdminData();
		
		if( empty($this->view->userData) ) 
		{

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

		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			
			throw new Exception('MasterAdmin rights required.');
			
		}
		
		Atmail_Locale::setupLocaleAndTranslation( $this->view->userData['Language'] );
		
	}
	
	public function indexAction() 
	{
		
		$domains = $this->admin->domainList();
		
		$this->view->domains = array_merge( array( array('DomainName' => '', 'id' => 0) ), $domains);
		$this->view->currentDomain = '';
		$this->view->domain = '';
		
		$this->render('users');
		
	}

	// Load the contact creation page, using the existing editcontact for code re-use
	public function addAction() 
	{
		
		$this->view->edit = true;
		
		// Add the user record for real
		if($this->requestParams['NewContact']) 
		{

			if( $this->view->global['demo'] == 1 )
			{
				throw new Exception('Disabled in online demo');
			}
			
			$this->requestParams['name'] = $this->requestParams['Username'] . '@' . $this->requestParams['domain'];
		
			$result = $this->admin->userAdd($this->requestParams);
        
			// User could not be created
			if( !$result->isSuccess() ) 
			{
			
				jQuery::addMessage( addslashes((string)$result->userAdd->response->message) );
			
			// User was successfully created, show the user, select in the list
			}
			else
			{
			
				$this->view->contact = $this->admin->userView($this->requestParams['name']);

				jQuery('#Users .user_row[contactid=]')->attr('contactid', $this->requestParams['name']);
				jQuery('#Users .user_row[contactid=' . $this->requestParams['name'] . '] .contactRow')->val($this->requestParams['name']);

				jQuery::evalScript("updateUserCount($('#Users li[DomainName=\'" . $this->requestParams['domain'] . "\'] .unread strong'),'1')");
				jQuery::evalScript("updateUserCount($('#Users li[DomainName=] .unread strong'),'1')");

				$this->view->jsonIdsToRender['contact_info'] = 'users/viewuser.phtml';
			
			}

		                      
		}
		else 
		{
			
			// Else show the new contact screen
			$this->view->contact = array();
			$this->view->contact['NewContact'] = 1;
			$this->view->contact['Password'] = $this->admin->generateUserPassword();
			$this->view->defaultUserSettings = Zend_Registry::get('config')->defaultUserSettings;
			$this->view->jsonIdsToRender['contact_info'] = 'users/newuser.phtml'; 
		
		}
		
		//now call ArchiveVault API if enabled
		
		
		$this->render('global/jsonresponse', null, true);                                                                                                 

	}
	
	public function listAction() 
	{
		
		$this->view->pageVolume = 50;
		$page = $this->requestParams['page'];
		if (empty($page)) 
		{
		
		    $this->view->pageNumber = 1;
		    $limit = array(0,$this->view->pageVolume);    
		
		}
		else 
		{
		
		    $this->view->pageNumber = $page;
		    $start = ($page - 1) * $this->view->pageVolume;
		    $limit = array($start,$this->view->pageVolume); 
		
		}

		$this->view->totalUsers = users::count($this->requestParams['domain']);
		$this->view->users = $this->admin->userList($this->requestParams['domain'], $limit);
		$this->view->domain = $this->requestParams['domain'];
		
		$this->view->jsonIdsToRender['address_contacts'] = 'users/listusers.phtml';

		// Render the first user on the list to the page
		if(isset($this->view->users[0]['Account']))
		{
		 
			$this->view->contact = $this->admin->userView($this->view->users[0]['Account']);
			
		}
		
		$this->view->jsonIdsToRender['contact_info'] = 'users/viewuser.phtml';
		
		$this->render('/global/jsonresponse', null, true);                                                                                                 
	
	}

	public function viewAction() 
	{
		
		$this->view->contact = $this->admin->userView($this->requestParams['name'], $this->requestParams['id']);
		
		$this->view->jsonIdsToRender['contact_info'] = 'users/viewuser.phtml';
		
		$this->render('/global/jsonresponse', null, true);                                                                                                 
	
	}

	public function editAction() 
	{
		
		$this->view->edit = true;
		$this->view->contact = $this->admin->userView($this->requestParams['name']);
		$this->view->contact['NewContact'] = 0;
		
		// Decide if to expand the 'more' options div
		foreach(array('UserWorkCompany', 'UserTitle', 'UserDOB', 'UserURL', 'UserWorkTitle', 'UserWorkDept', 'UserInfo') as $field) 
		{
		
			if(!empty($this->view->contact[$field]))
				$this->view->contact['ExpandMoreOptions'] = 1;
		
		}
		
		$this->view->jsonIdsToRender['contact_info'] = 'users/edituser.phtml';
		$this->render('global/jsonresponse', null, true);                                                                                                 

	}

	// Load the contact creation page, using the existing editcontact for code re-use
	public function updateAction() 
	{
		
		if( $this->view->global['demo'] == 1 )
		{
		
			throw new Exception('Disabled in online demo');
		
		}
		
		// 
		//convert fields from UI returned format into standard record format (field => value) for update
		if( isset($this->requestParams['numberFieldName']) ) 
		{
			foreach( $this->requestParams['numberFieldName'] as $k => $fieldName ) 
			{ 
				
				$this->requestParams[$fieldName] = $this->requestParams['numberValue'][$k];
				
			}
			
		}
		
		$result = $this->admin->userUpdate( $this->requestParams );
        
		if( !$result->isSuccess() )
		{
			
        	jQuery::addError( (string)$result->userUpdate->response->msg );

		}
		else 
        {
	
			jQuery::addMessage( (string)$result->userUpdate->response->msg );
			
		}
		
		//TODO: update the visable fields in the list (UserFirstName UserLastName)
			//jQuery('.user_row[contactid=' . $this->requestParams['name'] . '] .contactRow')->val($this->requestParams['name']);
		$this->view->contact = $this->admin->userView($this->requestParams['Account']);
				
		$this->view->jsonIdsToRender['contact_info'] = 'users/viewuser.phtml';

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

	}
	
	public function deleteAction() 
	{

		if( $this->view->global['demo'] == 1 )
		{
		
			throw new Exception('Disabled in online demo');
		
		}

		foreach($this->requestParams['id'] as $name)
		{
			$user = explode('@', $name);
			
			$response = $this->admin->userDelete($name); //, $this->requestParams['id']);
			if($response->isSuccess()) 
			{
			
				jQuery('#Users .user_row[contactid=' . $name . ']')->remove();

				jQuery::evalScript("updateUserCount($('#Users li[DomainName=\'" . $user[1] . "\'] .unread strong'),'-1')");
				jQuery::evalScript("updateUserCount($('#Users li[DomainName=] .unread strong'),'-1')");

			}
			else
			{
						
				jQuery::addError( (string)$result->userDelete->response->message );  
				
			}
			
		}	
		$this->render('/global/jsonresponse', null, true);                                                                                                 

	}
	
	
	public function addphotoAction() 
	{

		if( $this->view->global['demo'] == 1 )
		{
		
			throw new Exception('Disabled in online demo');
		
		}

		$_FILES['UserPhoto']['name'] = makeFSSafe($_FILES['UserPhoto']['name']);
		$filename = APP_ROOT . 'tmp/' . $_FILES['UserPhoto']['name'];
		
		if( !move_uploaded_file($_FILES['UserPhoto']['tmp_name'], $filename))
			echo $this->view->translate('Unable to upload photo');
		
		if(function_exists("gd_info"))
			$this->_createThumbnail($filename , $filename, 110, 110);

		$UserPhotoBase64 = base64_encode(file_get_contents($filename));	
   	
		require_once('contacts.php');
		$this->_contacts = new contacts(array('admin' => true));
		
		$this->_contacts->uploadUserPhoto(array('id' => $this->requestParams['id'], 'GroupID' => $this->requestParams['GroupID'], 'UserPhoto' => $UserPhotoBase64));
		$this->_helper->viewRenderer->setNoRender();

	}
	
	private function _createThumbnail($sourcePath, $destPath, $w, $h, $q = 100) 
	{
		
		require_once 'library/Atmail/ThumbNail.php';
		
		$thumb = new Thumbnail($sourcePath);
		if($thumb->init_success)
		{
			$thumb->resize($w, $h);
			$thumb->cropFromCenter(60);
			$thumb->save($destPath, $q);
		}
	}
	
	public function viewphotoAction() 
	{
		
		require_once('contacts.php');
		
		// TODO: admin a quick hack/workaround to avoid error
		$contacts = new contacts(array('admin' => true));
		
		if (isset($this->requestParams['shadow']))
		{
			$photoContent = users::getPhotoShadow($photoContent, $this->requestParams['id']);
		}
		
		// TODO: Convert all images to jpeg
		$this->getResponse()
			 ->setHeader('Content-Type','image/jpeg')
			 ->appendBody( $contacts->viewUserPhoto($this->requestParams) );
		
		$this->_helper->viewRenderer->setNoRender();
		
	}
	
}
