<?php

use Joomla\CMS\Factory;

require_once realpath(dirname(__FILE__)."/../client/ZohoOAuthPersistenceInterface.php");
require_once realpath(dirname(__FILE__)."/../common/ZohoOAuthException.php");

class ZohoOAuthPersistenceHandler implements ZohoOAuthPersistenceInterface
{
	public function saveOAuthData($zohoOAuthTokens)
	{
		$db_link=null;
		try{
			self::deleteOAuthTokens($zohoOAuthTokens->getUserEmailId(),$zohoOAuthTokens->getClientId());
			$db_link=self::getMysqlConnection();
			$query 	= $db_link->getQuery(true);

			// Insert columns.
			$columns = array('useridentifier', 'clientid', 'accesstoken', 'expirytime');

			// Insert values.
			$values = array($db_link->q($zohoOAuthTokens->getUserEmailId()), $db_link->q($zohoOAuthTokens->getClientId()),  $db_link->q($zohoOAuthTokens->getAccessToken()),$db_link->q($zohoOAuthTokens->getExpiryTime()));

			// In some cases the refresh_token does not exists (as is generated first time -- dunno why)
			$refresh_token = $zohoOAuthTokens->getRefreshToken();
			if (!empty($refresh_token)) {
				$columns[] = 'refreshtoken';
				$values[] = $db_link->q($refresh_token);
			}

			// Prepare the insert query.
			$query
				->insert($db_link->qn('#__rsform_zohocrm_oauthtokens'))
				->columns($db_link->qn($columns))
				->values(implode(',', $values));

			// Inserting
			$db_link->setQuery($query);
			if (!$db_link->execute()) {
				throw new Exception("OAuth token insertion failed.");
			}
			
		}
		catch (Exception $ex)
		{
			throw $ex;
		}
	}
	
	public function getOAuthTokens($userEmailId,$clientid)
	{
		$db_link=null;
		$oAuthTokens=new ZohoOAuthTokens();
		try{
			$db_link=self::getMysqlConnection();
			$query 	= $db_link->getQuery(true);

			$query->select('*')
				->from('#__rsform_zohocrm_oauthtokens')
				->where($db_link->qn('useridentifier').'='.$db_link->q($userEmailId))
				->where($db_link->qn('clientid').'='.$db_link->q($clientid));
			$db_link->setQuery($query);

			if($token = $db_link->loadObject()){

				$oAuthTokens->setExpiryTime($token->expirytime);
				$oAuthTokens->setRefreshToken($token->refreshtoken);
				$oAuthTokens->setAccessToken($token->accesstoken);
				$oAuthTokens->setUserEmailId($token->useridentifier);
			} else {
				throw new ZohoOAuthException("No Tokens exist for the given user-identifier,Please generate and try again.");
			}
		}
		catch (Exception $ex)
		{
			throw $ex;
		}

		return $oAuthTokens;
	}
	
	public function deleteOAuthTokens($userEmailId, $clientid)
	{
		$db_link=null;
		try{
			$db_link=self::getMysqlConnection();
			$query 	= $db_link->getQuery(true);

			// the conditions
			$conditions = array(
				$db_link->qn('useridentifier') . ' = '. $db_link->q($userEmailId),
				$db_link->qn('clientid') . ' = '. $db_link->q($clientid),
			);

			$query->delete($db_link->quoteName('#__rsform_zohocrm_oauthtokens'));
			$query->where($conditions);

			$db_link->setQuery($query);

			$result = $db_link->execute();

			if (!$result) {
				throw new Exception("Deleting  oauthtokens failed.");
			}
		}
		catch (Exception $ex)
		{
			throw $ex;
		}
	}
	
	public function getMysqlConnection()
	{
		$db = Factory::getDbo();
		
		return $db;
	}
}
?>