<?php
/**
 * This file is part of module Interac Email Money Transfer
 *
 *  @author    Bellini Services <bellini@bellini-services.com>
 *  @copyright 2007-2014 bellini-services.com
 *  @license   readme
 *
 * Your purchase grants you usage rights subject to the terms outlined by this license.
 *
 * You CAN use this module with a single, non-multi store configuration, production installation and unlimited test installations of PrestaShop.
 * You CAN make any modifications necessary to the module to make it fit your needs. However, the modified module will still remain subject to this license.
 *
 * You CANNOT redistribute the module as part of a content management system (CMS) or similar system.
 * You CANNOT resell or redistribute the module, modified, unmodified, standalone or combined with another product in any way without prior written (email) consent from bellini-services.com.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

if (!defined('_PS_VERSION_'))
	exit;

class iemt extends PaymentModule
{
	private	$_html = '';
	private $_postErrors = array();
	public $context;

	const BACKWARD_REQUIREMENT = '0.4';

	public function __construct()
	{
		$this->name = 'iemt';
		$this->tab = 'payments_gateways';
		$this->version = '1.12.0';
		$this->author = 'Bellini Services';

        parent::__construct();

		$this->page = basename(__FILE__, '.php');
        $this->displayName = $this->l('Interac Email Money Transfer');
        $this->description = $this->l('Accepts payments by Interac Email Money Transfer');
		$this->confirmUninstall = $this->l('Are you sure you want to delete your details ?');

		if (_PS_VERSION_ < '1.5')
		{
			require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
		}

		if ($this->active)
			$this->loadDefaults();
	}

	/**
	 * Initialize default values
	 */
	protected  function loadDefaults()
	{
		if (defined('_PS_ADMIN_DIR_'))
		{
			/* Backward compatibility */	
			if (_PS_VERSION_ < '1.5')
				$this->backwardCompatibilityChecks();

			/* Upgrade and compatibility checks */
			$this->runUpgrades();
			$this->compatibilityCheck();
		}
	}

	public function install()
	{
		if (!parent::install()
			OR !$this->registerHook('adminOrder')
			OR !$this->registerHook('header')
			OR !$this->registerHook('payment')
			OR !$this->registerHook('paymentReturn'))
			return false;

		/* Set database */
		if (!Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'interac_order` (
		  `id_order` int(10) unsigned NOT NULL,
		  `challenge_answer` varchar(255) NOT NULL,
		  PRIMARY KEY (`id_order`)
		) ENGINE='._MYSQL_ENGINE_.'  DEFAULT CHARSET=utf8'))
			return false;

		copy(dirname(__FILE__).'/mails/en/iemt.html', dirname(__FILE__).'/../../mails/en/iemt.html');
		copy(dirname(__FILE__).'/mails/en/iemt.txt', dirname(__FILE__).'/../../mails/en/iemt.txt');

		if (!Configuration::get('INTERAC_OS_PENDING_PAYMENT'))
		{
			$orderState = new OrderState();
			$orderState->send_email = true;
			$orderState->name = array();
			$orderState->template = array();
			foreach (Language::getLanguages() AS $language)
			{
				$orderState->name[$language['id_lang']] = 'Waiting for Interac Email Payment';
				$orderState->template[$language['id_lang']] = 'iemt';
			}
			$orderState->color = 'lightblue';
			$orderState->hidden = false;
			$orderState->delivery = false;
			$orderState->logable = false;
			$orderState->invoice = false;
			if ($orderState->add())
				copy(dirname(__FILE__).'/../../img/os/'.Configuration::get('PS_OS_CHEQUE').'.gif', dirname(__FILE__).'/../../img/os/'.(int)$orderState->id.'.gif');
			Configuration::updateValue('INTERAC_OS_PENDING_PAYMENT', (int)$orderState->id);
		}

		Configuration::updateValue('INTERAC_PAYMENT_EMAIL', Configuration::get('PS_SHOP_EMAIL'));

		return true;
	}

	public function uninstall()
	{
		if (!parent::uninstall())
			return false;
		return true;
	}

	protected function _postValidation()
	{
		if (Tools::isSubmit('btnSubmit'))
		{
			if (!Tools::getValue('INTERAC_PAYMENT_EMAIL'))
				$this->_postErrors[] = $this->l('The Payment Email is required.');
		}
	}

	protected function _postProcess()
	{
		if (Tools::isSubmit('btnSubmit'))
			Configuration::updateValue('INTERAC_PAYMENT_EMAIL', Tools::getValue('INTERAC_PAYMENT_EMAIL'));

		if (_PS_VERSION_ < '1.5') 
			$this->_html .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('ok').'" /> '.$this->l('Settings updated').'</div>';
		else
			$this->_html .= $this->displayConfirmation($this->l('Settings updated'));
	}

	protected function _displayIemt()
	{
		return $this->fetchTemplate('/views/templates/hook/', 'infos');
	}

	private function _displayForm()
	{
		$this->_html .=
		'<form action="'.Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset>
			<legend><img src="../img/admin/contact.gif" />'.$this->l('Contact details').'</legend>
				<table border="0" width="500" cellpadding="0" cellspacing="0" id="form">
					<tr><td colspan="2">'.$this->l('Please specify the payment email address to be used by customers').'.<br /><br /></td></tr>
					<tr><td width="130" style="height: 35px;">'.$this->l('Payment Email').'</td><td><input type="text" name="INTERAC_PAYMENT_EMAIL" value="'.htmlentities(Tools::getValue('INTERAC_PAYMENT_EMAIL', Configuration::get('INTERAC_PAYMENT_EMAIL')), ENT_COMPAT, 'UTF-8').'" style="width: 300px;" /></td></tr>
					<tr><td colspan="2" align="center"><input class="button" name="btnSubmit" value="'.$this->l('Update settings').'" type="submit" /></td></tr>
				</table>
			</fieldset>
		</form>';
	}

	public function getContent()
	{
		if (_PS_VERSION_ < '1.5') 
			$this->_html = '<h2>'.$this->displayName.'</h2>';

		if (Tools::isSubmit('btnSubmit'))
		{
			$this->_postValidation();
			if (!count($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors as $err)
					if (_PS_VERSION_ < '1.5') 
						$this->_html .= '<div class="alert error">'. $err .'</div>';
					else
						$this->_html .= $this->displayError($err);
		}
		else
			$this->_html .= '<br />';

		$this->_html .= $this->_displayIemt();
		if (_PS_VERSION_ < '1.5') 
			$this->_displayForm();
		else
			$this->_html .= $this->renderForm();

		return $this->_html;
	}

	public function fetchTemplate($path, $name, $extension = false)
	{
		if (_PS_VERSION_ < '1.4')
			$this->context->smarty->currentTemplate = $name;

		return $this->context->smarty->fetch(_PS_MODULE_DIR_.'/iemt/'.$path.$name.'.'.($extension ? $extension : 'tpl'));
	}

	public function hookHeader($params)
	{
		if (!$this->active)
			return;

		// Continue only if we are in the checkout process
		if (Tools::getValue('controller') != 'order-opc' && (!($_SERVER['PHP_SELF'] == __PS_BASE_URI__.'order.php' || $_SERVER['PHP_SELF'] == __PS_BASE_URI__.'order-opc.php' || Tools::getValue('controller') == 'order' || Tools::getValue('controller') == 'orderopc' || Tools::getValue('step') == 3)))
			return;

		if (_PS_VERSION_ < '1.5') 
		{
			Tools::addJS(_PS_JS_DIR_.'jquery/jquery.fancybox-1.3.4.js');
			Tools::addCSS(_PS_CSS_DIR_.'jquery.fancybox-1.3.4.css', 'all');
		}
		else
		{
			$this->context->controller->addJquery();
			$this->context->controller->addJQueryPlugin('fancybox');
		}
	}

	public function hookPayment($params)
	{
		if (!$this->active)
			return;

		$this->context->smarty->assign('mess_error', $this->l('Please provide a challenge answer'));

		return $this->fetchTemplate('/views/templates/front/', 'payment');
	}

	public function execPayment($cart)
	{
		if (!$this->active)
			return;

		$customer = $this->context->customer;  //new Customer($this->context->cookie->id_customer);
		$currency = $this->context->currency;	//new Currency($this->context->cookie->id_currency);
		$total = (float)$cart->getOrderTotal(true, Cart::BOTH);

		//todo: validate $challengeAnswer, redirect to payment page with error
		$challengeAnswer = Tools::getValue('challenge');
		//todo: validate $challengeAnswer, redirect to payment page with error

		$mailVars = array(
			'{shop_phone}' => Configuration::get('PS_SHOP_PHONE'),
			'{payment_email}' => Configuration::get('INTERAC_PAYMENT_EMAIL'),
			'{challenge_answer}' => $challengeAnswer,
		);

		if (_PS_VERSION_ < '1.5')
			$this->validateOrder((int)$cart->id, Configuration::get('INTERAC_OS_PENDING_PAYMENT'), $total, $this->displayName, NULL, $mailVars, (int)$currency->id, false, $customer->secure_key);
		else
			$this->validateOrder((int)$cart->id, Configuration::get('INTERAC_OS_PENDING_PAYMENT'), $total, $this->displayName, NULL, $mailVars, (int)$currency->id, false, $customer->secure_key, $this->context->shop);

		$order = new Order($this->currentOrder);

		if (Validate::isLoadedObject($order))
		{
			Db::getInstance()->Execute('
			INSERT INTO `'._DB_PREFIX_.'interac_order` (`id_order`, `challenge_answer`) 
			VALUES ('.(int)$order->id.', \''.pSQL($challengeAnswer).'\')');
		}

		Tools::redirectLink(__PS_BASE_URI__.'order-confirmation.php?id_cart='.$cart->id.'&id_module='.$this->id.'&id_order='.$this->currentOrder.'&key='.$customer->secure_key);
	}

	public function hookPaymentReturn($params)
	{
		if (!$this->active)
			return;

		if ($params['objOrder']->module != $this->name)
			return;

		$id_order=$params['objOrder']->id;

		$this->context->smarty->assign(array(
			'total' => $params['currency'].$params['total_to_pay'],
			'challengeAnswer' => $this->_getChallengeAnswer((int)($id_order)),
			'paymentEmail' => Configuration::get('INTERAC_PAYMENT_EMAIL'),
			'shopPhone' => Configuration::get('PS_SHOP_PHONE'),
		));

		if (_PS_VERSION_ < '1.5')
			$this->context->smarty->assign('order_name', $params['objOrder']->id);
		else
			$this->context->smarty->assign('order_name', $params['objOrder']->getUniqReference());

		return $this->fetchTemplate('/views/templates/front/', 'confirmation');
	}

	public function hookAdminOrder($params)
	{
		$order = new Order((int) ($params['id_order']));
		$challengeAnswer = $this->_getChallengeAnswer((int)($order->id));

		if (!$challengeAnswer) {
			return false;
		}

		$html = '';
		if (version_compare(_PS_VERSION_, '1.6', '>='))
		{
			$html .= '<div class="col-lg-7"><div class="panel"><h3><i class="icon-money"></i> '.$this->l('Interac Challenge Answer').'</h3><div class="row">'.
					 '<div style="float:left;">' . $this->l('Challenge Answer') . ' : ' . Tools::htmlentitiesUTF8($challengeAnswer) . '</div>'.
					 '</div></div></div>';
		}
		else
		{
			$html .= '<br /><fieldset style="width:400px;"><legend>' . $this->l('Interac Challenge Answer') . '</legend>';
			$html .= $this->l('Challenge Answer') . ' : ' . Tools::htmlentitiesUTF8($challengeAnswer);
			$html .= '</fieldset>';
		}

		return $html;
	}

	private function _getChallengeAnswer($id_order)
	{
		if (!(int)$id_order)
			return false;
		
		return Db::getInstance()->getValue('
		SELECT `challenge_answer` 
		FROM `'._DB_PREFIX_.'interac_order` 
		WHERE `id_order` = '.(int)$id_order);
	}

	/* Check status of backward compatibility module*/
	protected function backwardCompatibilityChecks()
	{
		if (Module::isInstalled('backwardcompatibility'))
		{
			$backward_module = Module::getInstanceByName('backwardcompatibility');
			if (!$backward_module->active)
				$this->warning .= $this->l('To work properly the module requires the backward compatibility module enabled').'<br />';
			elseif ($backward_module->version < iemt::BACKWARD_REQUIREMENT)
				$this->warning .= $this->l('To work properly the module requires at least the backward compatibility module v').iemt::BACKWARD_REQUIREMENT.'.<br />';
		}
		else
			$this->warning .= $this->l('In order to use this module you need to install the backward compatibility module.  You can download this for Free at the Prestashop addons store http://addons.prestashop.com.').'<br />';
	}

	/**
	 * Launch upgrade process
	 */
	public function runUpgrades($install = false)
	{
	}

	private function compatibilityCheck()
	{
		/* For 1.4.3 and less compatibility */
		$updateConfig = array('PS_OS_CHEQUE' => 1, 'PS_OS_PAYMENT' => 2, 'PS_OS_PREPARATION' => 3, 'PS_OS_SHIPPING' => 4,
		'PS_OS_DELIVERED' => 5, 'PS_OS_CANCELED' => 6, 'PS_OS_REFUND' => 7, 'PS_OS_ERROR' => 8, 'PS_OS_OUTOFSTOCK' => 9,
		'PS_OS_BANKWIRE' => 10, 'PS_OS_PAYPAL' => 11, 'PS_OS_WS_PAYMENT' => 12);

		foreach ($updateConfig as $key => $value)
			if (!Configuration::get($key) || (int)Configuration::get($key) < 1)
			{
				if (defined('_'.$key.'_') && (int)constant('_'.$key.'_') > 0)
					Configuration::updateValue($key, constant('_'.$key.'_'));
				else
					Configuration::updateValue($key, $value);
			}
	}

	public function renderForm()
	{
		$fields_form = array(
			'form' => array(
				'legend' => array(
					'title' => $this->l('Contact details'),
					'icon' => 'icon-envelope'
				),
				'input' => array(
					array(
						'type' => 'text',
						'label' => $this->l('Payment Email'),
						'name' => 'INTERAC_PAYMENT_EMAIL',
						'size' => 100,
						'required' => true
					),
				),
				'submit' => array(
					'title' => $this->l('Save'),
				)
			),
		);

		$helper = new HelperForm();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$this->fields_form = array();
		$helper->id = (int)Tools::getValue('id_carrier');
		$helper->identifier = $this->identifier;
		$helper->submit_action = 'btnSubmit';
		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->tpl_vars = array(
			'fields_value' => $this->getConfigFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);

		return $helper->generateForm(array($fields_form));
	}

	public function getConfigFieldsValues()
	{
		return array(
			'INTERAC_PAYMENT_EMAIL' => Tools::getValue('INTERAC_PAYMENT_EMAIL', Configuration::get('INTERAC_PAYMENT_EMAIL')),
		);
	}
}
?>