<?php
/**
 * @category 	Atmail
 * @package 	Models
 * @subpackage	Groups
 * @copyright 	Copyright (c) 2009-2011 ATMAIL. All rights reserved
 * @license 	See http://atmail.com/license.php for license agreement
 * @author		Allan Wrethman allan@staff.atmail.com
 * @author		Atmail (http://atmail.com)
 */
class groups
{

	public static function create( $data )
	{

		$dbAdapter = Zend_Registry::get('dbAdapter');
		$dbTables = new dbTables();
		
		$requiredFields = array('GroupName');
		foreach( $requiredFields as $requiredField )
		{
			if( empty( $data[$requiredField]) ) 
			{
			
				return array('response' => array('message' => 'Missing required argument creating group ' . $requiredField), 'status' => 'failed');
				
			}
		
		}
	   
		if( self::exists($data['GroupName']) )
		{

			return array('response' => array('message' => 'Can not create group. Duplicate name already exists'), 'status' => 'failed');

		}
		
		
		$allowedFields = array('GroupName', 'POP3Support', 'IMAPSupport', 'GroupwareZone', 'Sync', 'Webmail', 'Calendar', 'SharedAbook', 'WebSyncShared', 'WebSyncGlobal', 'PushSupport', 'licenseType');
		$newRecordData = array();  
		foreach( $allowedFields as $allowedField )
		{
			
			$newRecordData[$allowedField] = $data[$allowedField];
			
		}
		
		$result = $dbAdapter->insert( $dbTables->Groups, $newRecordData );
		if( $result === false )
		{
			
			return array('response' => array('message' => 'Can not create group.'), 'status' => 'failed');
			
		}   
		else
		{
			
			return array('status' => 'success');
			
		}

	}   

	public static function get( $groupName )
	{

		$dbAdapter = Zend_Registry::get('dbAdapter');
		$dbTables = new dbTables();
		$matches = $dbAdapter->select()
							 ->from( $dbTables->Groups )
							 ->where( 'GroupName = ?', $groupName )
							 ->query()
							 ->fetchAll();
		if( count($matches) > 0 )
			return $matches[0];
		else
			return false;

	}

	public static function exists( $groupName )
	{

		if( !isset($groupName) )
		{

			throw new Exception( 'exists: required argument missing' );

		}
		
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$dbTables = new dbTables();
		$matches = $dbAdapter->select()
							 ->from( $dbTables->Groups )
							 ->where( 'GroupName = ?', $groupName )
							 ->query() 
							 ->fetchAll();
		return count($matches)>0?true:false;

	}

	public static function getList( $namesOnly = true )
	{

		$dbAdapter = Zend_Registry::get('dbAdapter');
		$dbTables = new dbTables();
		$rows = $dbAdapter->select()
							 ->from( $dbTables->Groups )
							 ->order('GroupName')
							 ->query()
							 ->fetchAll();

		if( !$namesOnly )
			return $rows;
		
		$GroupNames = array();
		foreach($rows as $row) 
		{

			$GroupNames[] = $row['GroupName'];

		}
		return $GroupNames;

	}
   
	public static function update( $groupName, $data )
	{

		if( !self::exists( $groupName) && !isset($data['inherit']) )
			return array('response' => array('message' => 'Can not update group. Does not exist'), 'status' => 'failed');
                                                                                                                                                   
		//prevent setting PushSupport = 1 if not licensed
		//if( strlen(Zend_Registry::get('config')->reg['serialKey']) != 64 && array_key_exists('PushSupport', $data) && $data['PushSupport'] == '1' )
		//	return array('response' => array('message' => 'Setting lot allowed', 'errorCode' => 1), 'status' => 'failed');
		
		//if groupType==domain and inherit then update Users set Ugroup = default where Ugroup = domain (dont update all users cos some may be members of User group)
		//if groupType==domain and !inherit then update into ( or delete old and create new ) - then make sure all users on domain Ugroup default updated to new Ugroup
		//if groupType==user then record must already exist
		
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$dbTables = new dbTables();
		
		//currently changing key is not allowed
		$allowedDbFields = array('GroupDescription', 'POP3Support', 'IMAPSupport', 'GroupwareZone', 'Sync', 'Webmail', 'Calendar', 'Carddav', 'SharedAbook', 'WebSyncShared', 'WebSyncGlobal', 'PushSupport', 'CalDAVServer','CardDAVServer','WebDAVRootUrl', 'WebDavEnabled', 'StorageTabEnabled', 'FileSharingEnabled', 'licenseType');
		$dataPrepared = array();
		foreach( $allowedDbFields as $allowedField )
			if( isset($data[$allowedField]) )
				$dataPrepared[$allowedField] = $data[$allowedField];

		$checkPushLic = false;

		if( isset($data['groupType']) && $data['groupType'] == 'domain' )
		{
			$groupDefaultUsers = users::getGroupUsers( 'default' );
			$groupMainUsers = users::getGroupUsers( $groupName );

			//unpack Accounts for intersection
			$groupUsers = array();
			foreach( $groupDefaultUsers as $k => $user )
				$groupUsers[$k] = $user['Account'];
			foreach( $groupMainUsers as $k => $user )
				$groupUsers[$k] = $user['Account'];
			$domainUsers = users::getDomainUsers( $groupName );
			//unpack Accounts for intersection
			foreach( $domainUsers as $k => $user )
				$domainUsers[$k] = $user['Account'];

			// only update domain users that are Ugroup default (intersection: where users are in both arrays)
			$intersectedUsers = array_intersect( $groupUsers, $domainUsers );

			if( $checkPushLic )
			{
				$newPushUsersC = count($intersectedUsers);
//Zend_Registry::get('log')->debug( "\n" . print_r($newPushUsersC, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$newPushUsersC in domain group \n");
                if( $newPushUsersC > 0 && $newPushUsersC > $remainingSeats )
					return array('response' => array('message' => 'Switching to Push1 interit0: Unable to apply changes, insuffucient Push seats left'), 'status' => 'failed');
				
			}
				
			foreach( $intersectedUsers as $Account )
			//	$result = users::saveAllUserData( $Account, array('Users' => array('Ugroup' => $groupName)) );
            {
                //Check to see if user is a member of a different group before applying group change
                $AccountInfo = users::getAllUserData($Account);
                if($AccountInfo['Groups']['GroupName'] == "default" || $AccountInfo['Groups']['GroupName'] == $groupName)
                {
                    //If account is NOT a member of a different group
                    if( $data['inherit'] == '1')
                    {
                        //If domain set to inherit global settings
                        $result = users::saveAllUserData( $Account, array('Users' => array('Ugroup' => 'default')));
                    }
                    else
                    {
                        $result = users::saveAllUserData( $Account, array('Users' => array('Ugroup' => $groupName)) );
                    }
                }
            }
				
			$where = $dbAdapter->quoteInto('GroupName = ?', $groupName);
			$rowsAffected = $dbAdapter->delete( $dbTables->Groups, $where );
			$dataPrepared['GroupName'] = $groupName;
			$result = $dbAdapter->insert( $dbTables->Groups, $dataPrepared );
			return array('status' => 'success');
		}
		else
		{
			
			$groupUsers = users::getGroupUsers( $groupName );
			if( $checkPushLic )
			{

				$newPushUsersC = count($groupUsers);
                if( $newPushUsersC > 0 && $newPushUsersC > $remainingSeats )
					return array('response' => array('message' => 'UpdateGroup: Unable to apply changes, insufficient Push seats left'), 'status' => 'failed');
			
			}
			$where = $dbAdapter->quoteInto('GroupName = ?', $groupName);
			$rowsAffected = $dbAdapter->update( $dbTables->Groups, $dataPrepared, $where );
			
		}   
		
		if( $rowsAffected < 2 )
			return array('status' => 'success');
		else
			return array('response' => array('message' => 'Warning multiple groups with same name updated to current settings'), 'status' => 'success');

	}

	public static function delete( $groupName )
	{

		$dbAdapter = Zend_Registry::get('dbAdapter');
		$dbTables = new dbTables();
		//if( domains::exists( $groupName) )
		//{
		//	return array('response' => array('message' => 'Can not delete group while related domain exists'), 'status' => 'failed');

		//}
		//else
		//{

			$where = $dbAdapter->quoteInto('GroupName = ?', $groupName);
		    $affectedRows = $dbAdapter->delete( $dbTables->Groups, $where );
			
			if( $affectedRows == 0 )
			{
			
				return array('response' => array('message' => 'Unable to delete group'), 'status' => 'failed');
			
			}
			else
			{
			
				return array('status' => 'success'); 
			
			}

		//}

	}

}
