<?php
class Api_ContactController extends Atmail_Controller_Base
{
	
	public function init()
	{
		//TODO: extend authentication to support multiple user levels/roles/groups 
		require_once 'application/models/api.php';
		$this->api = new api();
		
		$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'?'':'/' . $this->_request->module);
		
		$this->_helper->viewRenderer->setNoRender();
		
		// Load all the params
		$this->requestParams = $this->getRequest()->getParams();

		// Use Cookie auth
		if( !Atmail_FormAuth::authenticated() )
		{

			return $this->_forward('timeout', 'mail', 'api', $this->requestParams);
			
		} 
		
		
		$this->userData = Zend_Auth::getInstance()->getStorage()->read();
		$this->userData = Atmail_Password::processUser($this->userData);
		
		// Load the session
		$this->session = new Zend_Session_Namespace(ATMAIL_NAMESPACE);
		
		// Load the contacts class
		$this->_contacts = new contacts( array('Account' => $this->userData['Account']) );

		// Find the users settings ( used for theme )
		$this->view->UserSettings = Zend_Registry::get('UserSettings');
		
		// Used to determine the contact in the global addressbook
		$this->view->Account = $this->userData['Account'];
		
		// Load the system settings
		$this->_globalConfig = Zend_Registry::get('config')->global;		
						
	}

    public function updateAction() {
        $params = $this->getRequest()->getParams();
        unset($params['api']);
        unset($params['module']);
        unset($params['controller']);
	    unset($params['action']);

        $id = isset( $params['id'] )? $params['id'] : NULL;
        $groupId = $params['groupId'];

        unset($params['groupId']);

        //TODO: do fields check


        try
        {
            if(!$id)
            {
	            $contact = array(
		            'contact' => $params,
	            );

	            $id = $this->_contacts->addContact($contact);

                if($groupId) {

                    $this->_contacts->addContactToGroup(
                        array(
                            'id' => $id,
                            'GroupID' => $groupId,
                        )
                    );
                }
            }
            else
            {
	            $contact = $params;
                $this->_contacts->updateContact($contact);
            }

            $contact = $this->_contacts->getContact($id, $groupId);

            $this->renderJson( $contact );
        }
        catch(Atmail_Exception $e)
        {
            $this->renderFail($e);
        }


    }
	
	public function indexAction() {
		//$this->restserver->handle( array('method' => 'index') );
			
	}
	
	public function createAction() {
		$params = $this->getRequest()->getParams();
		//$params['method'] = 'domainCreate';		
		//$this->restserver->handle($params);
	}

	public function listAction()
	{

		// TODO: Implement filter class, ask the server for only XYZ fields ( not all, reduce JSON packet )
		$contactsAll = $this->_contacts->getContacts($this->requestParams);

		// Add the API call to fetch the last message for the contact
		if (isset($this->requestParams['LastMessage'])) {
			$contactsFilter = array();
			$i = 0;

			foreach ($contactsAll as $contact) {
				$contactsAll[$i]['LastMessage'] = "Last message $i";
				$i++;
			}
		}

		if (isset($this->requestParams['Fields']) && is_array($this->requestParams['Fields'])) {
			$contactsFilter = array();
			$i = 0;

			foreach ($contactsAll as $contact) {

				foreach ($this->requestParams['Fields'] as $field) {
					if (isset($contact[$field]))
						$contactsFilter[$i][$field] = $contact[$field];
					else
						$contactsFilter[$i][$field] = 'null';

				}

				$i++;

			}

			// Export a filtered contact list
			$resultList = $contactsFilter;

		}
		else {
			// Export all contacts
			$resultList = $contactsAll;

		}

		for($i=0; $i<count($resultList); ++$i) {
			$resultList[$i]['isMyProfile'] = $resultList[$i]['Global'] == '1' && $resultList[$i]['Account'] == $this->userData['Account']? '1' : '0';
		}

		$this->renderJson($resultList);

	}

	public function deleteAction() {

		$param = $this->getRequest()->getParams();

		$ids = $param['id'];
		if(!is_array($ids)) {
			$ids = array( $ids );
		}

		try{
			foreach($ids as $id)
			{
				$param['id'] = $id;
				$this->_contacts->deleteContact($param);
			}
			$this->renderSuccess();
		}
		catch(Atmail_Exception $e) {
			$this->renderFail($e);
		}
	
	}

	public function deletefromgroupAction() {

		$requestParams = $this->getRequest()->getParams();
		// Loop for each element selected to delete

		if (!is_array($requestParams['id'])) {
			$requestParams['id'] = array($requestParams['id']);
		}

		foreach($requestParams['id'] as $id) {
			$response = $this->_contacts->deleteContactGroup(array('id' => $id, 'GroupID' => $requestParams['GroupID']));
		}

		$this->renderSuccess();

	}
	
	public function viewAction() {
		
		$contact = $this->_contacts->getContact($this->requestParams['id'], $this->requestParams['GroupID']);
        $this->renderJson($contact);

	}

	public function addtogroupAction() {
		$requestParams = $this->getRequest()->getParams();
		$status = 1;

		if(!is_array($requestParams['id']))
		{
			$requestParams['id'] = array($requestParams['id']);
		}

		if($requestParams['GroupID'] < 0 && ($requestParams['GroupID'] != GROUP_SHARED && $requestParams['GroupID'] != GROUP_FAV))
		{
			$this->renderJson(array(
				'result' => 'failed',
				'error' => $this->view->translate('You are not allow to drop contacts to that folder.')
			));

			return;
		}

		foreach($requestParams['id'] as $id)
		{
			if($requestParams['GroupID'] == GROUP_SHARED)
			{
				//shared contact, update
				$this->_contacts->updateContact(array('Shared' => 1, 'id' => $id));
			}
			else if ($requestParams['GroupID'] == GROUP_FAV)
			{
				// 'add' the contact to the favourite group by flagging it as such
				$this->_contacts->updateContact(array('Favourite' => 1, 'id' => $id));
			}
			else
			{
				$groupIDs = $this->_contacts->getGroupIdsFromAbookId(array('id' => $id));

				$found = false;
				foreach($groupIDs as $groupID)
				{
					if($groupID['GroupID'] == GROUP_AUTO)
					{
						$found = true;
						break;
					}
				}

				if($found)
				{
					// remove the contact from the auto group
					$response = $this->_contacts->deleteContactGroup(array('id' => $id, 'GroupID' => GROUP_AUTO));
					jQuery('.address_row[contactid=' . $id . ']')->remove();

				}

				$status = $this->_contacts->addContactToGroup(array('GroupID' => $requestParams['GroupID'], 'id' => $id));
				$this->_contacts->updateContact(array('Shared' => 0, 'id' => $id));
			}
		}

		// If the contact was successfully added ( Without a duplicate, update the count )
		if($status == 1)
		{

		}

		$this->renderSuccess();

	}
}
