<?php
/**
* Module RegistrationAlerts
*
*   @author    Agence Bondaty and Co
*   @copyright 2104 prestaman by Bondaty and Co
*   @license   single
*
* support@bondaty-and-co.fr
* http://www.bondaty-and-co.fr
*/

if (!defined('_CAN_LOAD_FILES_'))
	exit;


class RegistrationAlerts extends Module
{
	private $html = '';

	private $merchant_mails;

	const __RA_MAIL_DELIMITOR__ = "\n";

	public function __construct()
	{
		$this->name = 'registrationalerts';
		$this->tab = 'administration';
		$this->version = '1.1';
		$this->author = 'Bondaty and Co';
		$this->module_key = 'bc2fb0def7540924a5f2440d16fb5aeb';
		$this->need_instance = 0;

		parent::__construct();

		if ($this->id)
			$this->init();

		$this->displayName = $this->l('Registration alerts');
		$this->description = $this->l('sends an e-mail notification when a customer registers.');
		$this->confirmUninstall = $this->l('Are you sure you want to uninstall');
	}

	private function init()
	{
		$this->merchant_mails = Configuration::get('RA_MERCHANT_MAILS');
	}

	public function install()
	{
		if (!parent::install() || !$this->registerHook('createAccount'))
			return false;

		Configuration::updateValue('RA_MERCHANT_MAILS', Configuration::get('PS_SHOP_EMAIL'));
		return true;
	}

	public function uninstall()
	{
		Configuration::deleteByName('RA_MERCHANT_MAILS');
		return parent::uninstall();
	}

	public function getContent()
	{
		$this->postProcess();

		$this->html = '<h2>'.$this->displayName.'</h2>';
		$this->html .= $this->displayForm();

		return $this->html;
	}

	private function postProcess()
	{
		$errors = array();

		if (Tools::isSubmit('submitRAMerchant'))
		{
			$emails = Tools::getValue('ra_merchant_mails');

			if (!$emails || empty($emails))
				$errors[] = $this->l('Please type one (or more) e-mail address');
			else
			{
				$emails = explode("\n", $emails);
				foreach ($emails as $k => $email)
				{
					$email = trim($email);
					if (!empty($email) && !Validate::isEmail($email))
					{
						$errors[] = $this->l('Invalid e-mail:').' '.Tools::safeOutput($email);
						break;
					}
					elseif (!empty($email) && count($email) > 0)
						$emails[$k] = $email;
					else
						unset($emails[$k]);
				}

				$emails = implode(self::__RA_MAIL_DELIMITOR__, $emails);

				if (!Configuration::updateValue('RA_MERCHANT_MAILS', $emails))
					$errors[] = $this->l('Cannot update settings');
			}
		}

		if (count($errors) > 0)
			echo $this->displayError(implode('<br />', $errors));

		$this->init();
	}

	public function displayForm()
	{
		return '<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset>
				<legend><img src="'.$this->_path.'logo.gif" />'.$this->l('Merchant notifications').'</legend>
				<div style="clear:both;">&nbsp;</div>
				<label>'.$this->l('E-mail addresses:').' </label>
				<div class="margin-form">
					<div style="float:left; margin-right:10px;">
						<textarea name="ra_merchant_mails" rows="10" cols="40">'
						.Tools::safeOutput(Tools::getValue('ra_merchant_mails',
						str_replace(self::__RA_MAIL_DELIMITOR__, "\n", $this->merchant_mails))).'</textarea>
					</div>
					<div style="float:left;">
						'.$this->l('One e-mail address per line (e.g. you@example.com)').'
					</div>
				</div>
				<div style="clear:both;">&nbsp;</div>
				<div class="margin-form">
					<input type="submit" value="'.$this->l('   Save   ').'" name="submitRAMerchant" class="button" />
				</div>
			</fieldset>
		</form>';
	}

	public function hookCreateAccount()
	{
	Mail::Send(
			$this->context->language->id,
			'registrationalert',
			$this->l('New member registration!'),
			array(
				'{firstname}' => Tools::getValue('firstname'),
				'{lastname}' => Tools::getValue('lastname'),
				'{email}' => Tools::getValue('email'),
				'{company}' => Tools::getValue('company'),
				'{siret}' => Tools::getValue('siret'),
				'{ape}' => Tools::getValue('ape'),
				'{vat_number}' => Tools::getValue('vat_number'),
				'{website}' => Tools::getValue('website'),
				'{state}' => State::getNameById($cookie->id_lang, Tools::getValue('id_state')),
				'{country}' => Country::getNameById($cookie->id_lang, Tools::getValue('id_country')),
				'{address1}' => Tools::getValue('address1'),
				'{address2}' => Tools::getValue('address2'),
				'{postcode}' => Tools::getValue('postcode'),
				'{city}' => Tools::getValue('city'),
				'{phone}' => Tools::getValue('phone'),
				'{phone_mobile}' => Tools::getValue('phone_mobile'),
				'{other}' => Tools::getValue('other')),
			explode(self::__RA_MAIL_DELIMITOR__, $this->merchant_mails),
			null,
			Configuration::get('PS_SHOP_EMAIL'),
			Configuration::get('PS_SHOP_NAME'),
			null,
			null,
			dirname(__FILE__).'/mails/');
	}
}
