<?php 
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include (PATH_TO_ROOT."webcati/init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.gridData.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");

class mailTreeMan extends TreeDataManipulator {
	public function insertItemAction()
	{
		
		$return = parent::insertItemAction();
		$def = $this->db->get('_user',$_SESSION['UserInfo']['id'],'mail_account_default',DB_WARPIT_MAIN);
		$this->db->ChangeDatabase(DB_WARPIT_USERSPOOL);
		if($def)
		{
				$row = $this->db->get('_SMTP_accounts',$def);
				$sql = "UPDATE _Emails SET id_account = $def,mail_from = '{$row['mail_from']}',mail_from_label = '{$row['mail_from_label']}' WHERE id = ".$this->insertId;
				$this->db->SQLexecute($sql);
		}
		else 
		{
			$row = $this->db->get('_SMTP_accounts');
			if(count($row) == 1)
			{
				$row = $row[0];
				$sql = "UPDATE _Emails SET id_account = {$row['id']},mail_from = '{$row['mail_from']}',mail_from_label = '{$row['mail_from_label']}' WHERE id = ".$this->insertId;
				$this->db->SQLexecute($sql);
			}
		}
		return $return;
	}
}

class SMTPaccountsMan extends GridDataManipulator{
	
	public function selectAction()
	{
	
			$this->fetchSelect();
			
			$def = $this->db->get('_user',$_SESSION['UserInfo']['id'],'mail_account_default',DB_WARPIT_MAIN);
			
			foreach ($this->arr as &$row) {
				if($row['id'] == $def)
					$row['userDefault'] = true;
				else
					$row['userDefault'] = false;
			}
			
					
			return parent::selectAction();			
	}
	
	public function updateAction()
	{
		if($_POST['field'] == 'userDefault')
		{
			$value = $_POST['value']== 1 ? $_POST['id'] : 0;
			$this->db->ChangeDatabase(DB_WARPIT_MAIN);
			$this->db->SQLexecute("UPDATE _user SET mail_account_default = $value WHERE id = ".$_SESSION['UserInfo']['id'] );
			return "{success:true}";
		}
		return parent::updateAction();
		
	}
	
}
	
	
	$db->ChangeDatabase($_POST['database']);
	if($_POST['RMcomp'] == 'grid')
		$manipulator = new SMTPaccountsMan($db,$_POST['RMtable']);
	else 
		$manipulator = new mailTreeMan($db,$_POST['RMtable']);	
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		echo '{success:false,error:"Unknown action!"}';	
	}

?>