<?php

class BankWire extends PaymentModule
{
	private $_html = '';
	private $_postErrors = array();
	
	public  $home;
	public  $owner;
	public	$iban_1;
	public	$iban_2;
	public	$iban_3;
	public	$bic;
	public	$currencies;

	function __construct()
	{
		$this->name = 'bankwire';
		$this->tab = 'Payment';
		$this->version = 0.1;

		$config = Configuration::getMultiple(array('BANK_WIRE_HOME', 'BANK_WIRE_OWNER', 'BANK_WIRE_IBAN', 'BANK_WIRE_BIC', 'BANK_WIRE_CURRENCIES'));
		if (isset($config['BANK_WIRE_HOME']))
			$this->home = $config['BANK_WIRE_HOME'];
		if (isset($config['BANK_WIRE_OWNER']))
			$this->owner = $config['BANK_WIRE_OWNER'];
		if (isset($config['BANK_WIRE_IBAN']))
		{
			$iban = explode('-', $config['BANK_WIRE_IBAN']);
			$this->iban_1 = $iban[0];
			$this->iban_2 = $iban[1];
			$this->iban_3 = $iban[2];
		}
		if (isset($config['BANK_WIRE_BIC']))
			$this->bic = $config['BANK_WIRE_BIC'];
		if (isset($config['BANK_WIRE_CURRENCIES']))
			$this->currencies = $config['BANK_WIRE_CURRENCIES'];
		parent::__construct();

		/* The parent construct is required for translations */
		$this->page = basename(__FILE__, '.php');
		$this->displayName = $this->l('Bank Wire');
		$this->description = $this->l('Module accepting payments by bank wire');
		if (!isset($this->home) OR !isset($this->owner) OR !isset($this->iban_1) OR !isset($this->bic))
			$this->warning = $this->l('Bank branch, account owner, IBAN and BIC must be configured in order to use this module correctly');
		if (!Configuration::get('BANK_WIRE_CURRENCIES'))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				$authorized_currencies[] = $currency['id_currency'];
			Configuration::updateValue('BANK_WIRE_CURRENCIES', implode(',', $authorized_currencies));
		}
	}

	function install()
	{
		parent::install();
		$this->registerHook('payment');
		$this->registerHook('paymentReturn');
		$currencies = Currency::getCurrencies();
		$authorized_currencies = array();
		foreach ($currencies as $currency)
			$authorized_currencies[] = $currency['id_currency'];
		Configuration::updateValue('BANK_WIRE_CURRENCIES', implode(',', $authorized_currencies));
}

	function uninstall()
	{
		Configuration::deleteByName('BANK_WIRE_HOME');
		Configuration::deleteByName('BANK_WIRE_OWNER');
		Configuration::deleteByName('BANK_WIRE_IBAN');
		Configuration::deleteByName('BANK_WIRE_BIC');
		Configuration::deleteByName('BANK_WIRE_CURRENCIES');
		parent::uninstall();
	}

	private function _postValidation()
	{
		if (isset($_POST['btnSubmit']))
		{
			if (empty($_POST['home']))
				$this->_postErrors[] = $this->l('bank branch is required.');
			elseif (empty($_POST['owner']))
				$this->_postErrors[] = $this->l('account owner is required.');
			elseif (empty($_POST['iban_1']))
				$this->_postErrors[] = $this->l('IBAN country code is required.');
			elseif (empty($_POST['iban_2']))
				$this->_postErrors[] = $this->l('IBAN key check is required.');
			elseif (empty($_POST['iban_3']))
				$this->_postErrors[] = $this->l('IBAN BBAN is required.');
			elseif (empty($_POST['bic']))
				$this->_postErrors[] = $this->l('BIC is required.');
		}
		elseif (isset($_POST['currenciesSubmit']))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				if (isset($_POST['currency_'.$currency['id_currency']]) AND $_POST['currency_'.$currency['id_currency']])
					$authorized_currencies[] = $currency['id_currency'];
			if (!count($authorized_currencies))
				$this->_postErrors[] = $this->l('at least one currency is required.');
		}
	}

	private function _postProcess()
	{
		if (isset($_POST['btnSubmit']))
		{
			Configuration::updateValue('BANK_WIRE_HOME', $_POST['home']);
			Configuration::updateValue('BANK_WIRE_OWNER', $_POST['owner']);
			Configuration::updateValue('BANK_WIRE_IBAN', implode('-', array($_POST['iban_1'], $_POST['iban_2'], $_POST['iban_3'])));
			Configuration::updateValue('BANK_WIRE_BIC', $_POST['bic']);
		}
		elseif (isset($_POST['currenciesSubmit']))
		{
			$currencies = Currency::getCurrencies();
			$authorized_currencies = array();
			foreach ($currencies as $currency)
				if (isset($_POST['currency_'.$currency['id_currency']]) AND $_POST['currency_'.$currency['id_currency']])
					$authorized_currencies[] = $currency['id_currency'];
			Configuration::updateValue('BANK_WIRE_CURRENCIES', implode(',', $authorized_currencies));
		}
		$this->_html .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('ok').'" /> '.$this->l('Settings updated').'</div>';
	}

	private function _displayBankWire()
	{
		$this->_html .= '<img src="../modules/bankwire/bankwire.jpg" style="float:left; margin-right:15px;"><b>'.$this->l('This module allows you to accept payments by bank wire.').'</b><br /><br />
		'.$this->l('If the client chooses this payment mode, the order will change its status into a \'Waiting for payment\' status.').'<br />
		'.$this->l('So you need to confirm manually your order as soon as you receive this wire.').'<br /><br /><br />';
	}

	private function _displayForm()
	{
		$this->_html .=
		'<form action="'.$_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 bank wire account details for customers').'.<br /><br /></td></tr>
					<tr><td width="130" style="height: 35px;">'.$this->l('Account owner').'</td><td><input type="text" name="owner" value="'.Tools::getValue('owner', $this->owner).'" style="width: 300px;" /></td></tr>
					<tr>
						<td width="130" style="vertical-align: top;">'.$this->l('Bank branch').'</td>
						<td style="padding-bottom:15px;"><textarea name="home" rows="3" cols="53">'.Tools::getValue('home', $this->home).'</textarea></td>
					</tr>
					<tr>
						<td width="130" style="height: 35px; vertical-align: top;">'.$this->l('IBAN').'</td>
						<td>
							<input type="text" name="iban_1" value="'.Tools::getValue('iban_1', $this->iban_1).'" style="width: 20px;" maxlength="2" />&nbsp;&nbsp;
							&nbsp;&nbsp;<input type="text" name="iban_2" value="'.Tools::getValue('iban_2', $this->iban_2).'" style="width: 20px;" maxlength="2" />&nbsp;&nbsp;
							<input type="text" name="iban_3" value="'.Tools::getValue('iban_3', $this->iban_3).'" style="width: 230px;" maxlength="30" />
							<div style="margin-top:5px;">
								<div style="float:left; width:55px; font-size:10px;">'.$this->l('Country').'<br />'.$this->l('Code').'</div>
								<div style="float:left; width:60px; font-size:10px;">'.$this->l('Key').'<br />'.$this->l('Check').'</div>
								<div style="float:left; width:200px; font-size:10px;text-align:center;">'.$this->l('BBAN').'</div>
							</div>
						</td>
					</tr>
					<tr><td width="130" style="height: 35px;">'.$this->l('BIC').'</td><td><input type="text" name="bic" value="'.Tools::getValue('bic', $this->bic).'" style="width: 300px;" maxlength="11" /></td></tr>
					<tr><td colspan="2" align="center"><br /><input class="button" name="btnSubmit" value="'.$this->l('Update settings').'" type="submit" /></td></tr>
				</table>
			</fieldset>
		</form>
		<br /><br />
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
			<fieldset>
			<legend><img src="../img/t/15.gif" />'.$this->l('Authorized currencies').'</legend>
				<table border="0" width="500" cellpadding="0" cellspacing="0" id="form">
					<tr><td colspan="2">'.$this->l('Currencies authorized for bank wire payment. Customers will be able to send wire using theses currencies').'.<br /><br /></td></tr>
					<tr>
						<td width="130" style="height: 35px; vertical-align:top">'.$this->l('Currencies').'</td>
						<td>';
						$currencies = Currency::getCurrencies();
						$authorized_currencies = array_flip(explode(',', Configuration::get('BANK_WIRE_CURRENCIES')));
						foreach ($currencies as $currency)
							$this->_html .= '<label style="float:none; "><input type="checkbox" value="true" name="currency_'.$currency['id_currency'].'"'.(isset($authorized_currencies[$currency['id_currency']]) ? ' checked="checked"' : '').' />&nbsp;<span style="font-weight:bold;">'.$currency['name'].'</span> ('.$currency['sign'].')</label><br />';
			$this->_html .='
						</td>
					</tr>
					<tr><td colspan="2" align="center"><br /><input class="button" name="currenciesSubmit" value="'.$this->l('Update settings').'" type="submit" /></td></tr>
				</table>
			</fieldset>
		</form>';
	}

	function getContent()
	{
		$this->_html = '<h2>'.$this->displayName.'</h2>';
	
		if (!empty($_POST))
		{
			$this->_postValidation();
			if (!count($this->_postErrors))
				$this->_postProcess();
			else
				foreach ($this->_postErrors AS $err)
					$this->_html .= '<div class="alert error">'. $err .'</div>';
		}
		else
			$this->_html .= '<br />';
	
		$this->_displayBankWire();
		$this->_displayForm();
	
		return $this->_html;
	}

	function execPayment($cart)
	{
		global $cookie, $smarty;

		$currencies = Currency::getCurrencies();
		$authorized_currencies = array_flip(explode(',', $this->currencies));
		$currencies_used = array();
		foreach ($currencies as $key => $currency)
			if (isset($authorized_currencies[$currency['id_currency']]))
				$currencies_used[] = $currencies[$key];
		$smarty->assign(array(
			'currency_default' => new Currency(Configuration::get('PS_CURRENCY_DEFAULT')),
			'currencies' => $currencies_used,
			'total' => number_format($cart->getOrderTotal(true, 3), 2, '.', ''),
			'isoCode' => Language::getIsoById(intval($cookie->id_lang)),
			'bankwireHome' => nl2br2($this->home),
			'bankwireOwner' => $this->owner,
			'bankwireIban' => implode('-', array($this->iban_1, $this->iban_2, $this->iban_3)),
			'bankwireBic' => $this->bic,
			'this_path' => $this->_path
		));

		return $this->display(__FILE__, 'payment_execution.tpl');
	}

	function hookPayment($params)
	{
		global $smarty;

		$smarty->assign('this_path', $this->_path);
		return $this->display(__FILE__, 'payment.tpl');
	}

	function hookPaymentReturn($params)
	{
		global $smarty;
		$state = $params['objOrder']->getCurrentState();
		if ($state == _PS_OS_BANKWIRE_ OR $state == _PS_OS_OUTOFSTOCK_)
			$smarty->assign(array(
				'total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false, false),
				'bankwireHome' => nl2br2($this->home),
				'bankwireOwner' => $this->owner,
				'bankwireIban' => (($this->iban_1 AND $this->iban_2 AND $this->iban_3) ? implode('-', array($this->iban_1, $this->iban_2, $this->iban_3)) : ''),
				'bankwireBic' => $this->bic,
				'status' => 'ok',
				'id_order' => $params['objOrder']->id
			));
		else
			$smarty->assign('status', 'failed');
		return $this->display(__FILE__, 'payment_return.tpl');
	}

}

?>