<?php
/**
 * @category 	Atmail
 * @package 	Models
 * @subpackage	Domains
 * @copyright 	Copyright (c) 2009-2011 ATMAIL. All rights reserved
 * @license 	See http://atmail.com/license.php for license agreement
 * @author		Brad Kowalczyk brad@staff.atmail.com
 * @author		Atmail (http://atmail.com)
 */
class domains
{
	
	public static function getList()
	{

		$dbTables = new dbTables();
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$select = $dbAdapter->select()->from($dbTables->Domains, 'Hostname');
		$result = $select->query();
		$localDomains = array();
		foreach($result->fetchAll() as $dom) 
		{
		
			$localDomains[] = $dom['Hostname'];
		
		}
		return $localDomains;
		
	}
	
	public static function exists($domain)
	{
		
		$dbTables = new dbTables();
		$dbAdapter = Zend_Registry::get('dbAdapter');
		return $dbAdapter->fetchOne("select 1 from Domains where Hostname = ? limit 1", array($domain));
		
	}
		
   
	public static function getStatus($domain)
	{
		
		$dbTables = new dbTables();
		$dbAdapter = Zend_Registry::get('dbAdapter');
		return $dbAdapter->fetchOne("select Enable from Domains where Hostname = ?", array($domain));
		
	}
	
	public static function lock($domain)
	{
		
		$dbTables = new dbTables();
		$dbAdapter = Zend_Registry::get('dbAdapter');
        $like = $dbAdapter->quote("%@$domain");
        $dbAdapter->query("update Users set UserStatus = 1 where Account like $like and UserStatus = 0 or UserStatus is null");
        $dbAdapter->query("update Domains set Enable = 0 where Hostname = ?", array($domain));

    }

    public static function unlock($domain)
    {

        $dbTables = new dbTables();
        $dbAdapter = Zend_Registry::get('dbAdapter');
        $like = $dbAdapter->quote("%@$domain");
        $dbAdapter->query("update Users set UserStatus = 0 where Account like $like and UserStatus != 0");
        $dbAdapter->query("update Domains set Enable = 1 where Hostname = ?", array($domain));
    }

	public static function delete( $domain )
	{
		
		//enforces referential integrity be forcibly deleting related records
		//CONSIDER alternatively throw error until related records deleted
		$dbTables = new dbTables();
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$like = $dbAdapter->quote("%@$domain");
		
		//delete related users
		$domainUsers = users::getDomainUsers( $domain );
		$dbAdapter->beginTransaction();
		
		foreach( $domainUsers AS $user )
		{
			
			$result = users::deleteUser( $user['Account'] );
			
		}
		
		if( 1 !== $dbAdapter->delete($dbTables->Domains, $dbAdapter->quoteInto("Hostname = ?", $domain)) )
		{
			
			return false;
			
		}
		if( false === $dbAdapter->delete($dbTables->AdminGroup, $dbAdapter->quoteInto("Domain = ?", $domain)) )
		{
			
			return false;
			
		}
		if( 1 < $dbAdapter->delete($dbTables->Groups, $dbAdapter->quoteInto("GroupName = ?", $domain)) )
		{
			
			return false;
			
		}
		$dbAdapter->commit();
		
		return true;
		
	}   

}
