<modification>
	<name>Email Templates</name>
	<code>emailtemplates</code>
	<author>Opencart-Templates</author>
	<version>3.0.5.91</version>
	<link>https://www.opencart-templates.co.uk/advanced_professional_email_template</link>
	<file path="admin/controller/mail/affiliate.php" email_template="admin.affiliate_approve">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: admin.affiliate_approve
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
				'key' => 'admin.affiliate_approve',
				'customer_id' => $customer_info['customer_id'],
				'customer_group_id' => $customer_info['customer_group_id'],
				'language_id' => $customer_info['language_id'],
				'store_id' => $customer_info['store_id']
			);

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                $template->addData($customer_info);

                if (!empty($args[0]['custom_field'])) {
                    $this->load->model('account/custom_field');

                    $custom_fields = $this->model_account_custom_field->getCustomFields($customer_info['customer_group_id']);

                    foreach ($custom_fields as $custom_field) {
                        if (isset($args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                            $custom_field_key = 'custom_field_' . ($custom_field['location'] != 'account' ? $custom_field['location'] . '_' : '') . $custom_field['custom_field_id'];
                            $custom_field_value = $args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']];

                            $template->data[$custom_field_key . '_name'] = $custom_field['name'];
                            $template->data[$custom_field_key . '_value'] = '';

                            if ($custom_field['custom_field_value']) {
                                foreach ($custom_field['custom_field_value'] as $custom_field_value_info) {
                                    if (is_array($custom_field_value)) {
                                        if (in_array($custom_field_value_info['custom_field_value_id'], $custom_field_value)) {
                                            $template->data[$custom_field_key . '_value_' . $custom_field_value_info['custom_field_value_id']] = $custom_field_value_info['name'];
                                        }
                                    } else {
                                        if ($custom_field_value_info['custom_field_value_id'] == $custom_field_value) {
                                            $template->data[$custom_field_key . '_value'] = $custom_field_value_info['name'];
                                        }
                                    }
                                }
                            } else {
                                $template->data[$custom_field_key . '_value'] = $custom_field_value;
                            }
                        }
                    }
                }

                if ($store_info) {
                    $store_url = $store_info['url'] . 'index.php?route=affiliate/login';
                } else {
                    $store_url = HTTP_CATALOG . 'index.php?route=affiliate/login';
                }

                $template->data['account_login'] = $store_url . '&amp;email=' . $customer_info['email'];

                if (!empty($template->data['button_account_login'])) {
                    $template->data['account_login_text'] = $template->data['button_account_login'];
                } else {
                    $template->data['account_login_text'] = $template->data['account_login'];
                }
			    // Prepared mail: admin.affiliate_approve
            }
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
		// Send mail: admin.affiliate_approve
		if ($template && $template->check()) {
		    $template->build();
		    $template->hook($mail);
        }

		$mail->send();

		$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setText($this->load->view('mail/affiliate_approve', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setText($this->load->view('mail/affiliate_approve', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setText($this->load->view('mail/affiliate_approve', $data));]]></add>
    </operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/affiliate_approve', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate_approve', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate_approve', $data));]]></add>
    </operation>
</file>

	<file path="admin/controller/mail/affiliate.php" email_template="admin.affiliate_deny">
	<operation>
		<search index="1"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: admin.affiliate_deny
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
				'key' => 'admin.affiliate_deny',
				'customer_id' => $customer_info['customer_id'],
				'customer_group_id' => $customer_info['customer_group_id'],
				'language_id' => $customer_info['language_id'],
				'store_id' => $customer_info['store_id']
			);

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
			    $template->addData($customer_info);
			    // Prepared mail: admin.affiliate_deny
            }
		]]></add>
	</operation>
	<operation>
		<search index="1"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
		// Send mail: admin.affiliate_deny
		if ($template && $template->check()) {
		    $template->build();
            $template->hook($mail);
        }

		$mail->send();

		$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setText($this->load->view('mail/affiliate_deny', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setText($this->load->view('mail/affiliate_deny', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setText($this->load->view('mail/affiliate_deny', $data));]]></add>
    </operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/affiliate_deny', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate_deny', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate_deny', $data));]]></add>
    </operation>
</file>

	<file path="admin/controller/mail/customer.php" email_template="admin.customer_approve">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: admin.customer_approve
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
				'key' => 'admin.customer_approve',
				'customer_id' => $customer_info['customer_id'],
				'customer_group_id' => $customer_info['customer_group_id'],
				'language_id' => $customer_info['language_id'],
				'store_id' => $customer_info['store_id']
			);

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                $template->addData($customer_info);

                if (!empty($args[0]['custom_field'])) {
                    $this->load->model('account/custom_field');

                    $custom_fields = $this->model_account_custom_field->getCustomFields($customer_info['customer_group_id']);

                    foreach ($custom_fields as $custom_field) {
                        if (isset($args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                            $custom_field_key = 'custom_field_' . ($custom_field['location'] != 'account' ? $custom_field['location'] . '_' : '') . $custom_field['custom_field_id'];
                            $custom_field_value = $args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']];

                            $template->data[$custom_field_key . '_name'] = $custom_field['name'];
                            $template->data[$custom_field_key . '_value'] = '';

                            if ($custom_field['custom_field_value']) {
                                foreach ($custom_field['custom_field_value'] as $custom_field_value_info) {
                                    if (is_array($custom_field_value)) {
                                        if (in_array($custom_field_value_info['custom_field_value_id'], $custom_field_value)) {
                                            $template->data[$custom_field_key . '_value_' . $custom_field_value_info['custom_field_value_id']] = $custom_field_value_info['name'];
                                        }
                                    } else {
                                        if ($custom_field_value_info['custom_field_value_id'] == $custom_field_value) {
                                            $template->data[$custom_field_key . '_value'] = $custom_field_value_info['name'];
                                        }
                                    }
                                }
                            } else {
                                $template->data[$custom_field_key . '_value'] = $custom_field_value;
                            }
                        }
                    }
                }

                $template->data['account_login'] = $store_url . '&amp;email=' . $customer_info['email'];

                if (!empty($template->data['button_account_login'])) {
                    $template->data['account_login_text'] = $template->data['button_account_login'];
                } else {
                    $template->data['account_login_text'] = $template->data['account_login'];
                }
			    // Prepared mail: admin.customer_approve
            }
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
		// Send mail: admin.customer_approve
		if ($template && $template->check()) {
		    $template->build();
		    $template->hook($mail);

            $mail->send();

            $this->model_extension_module_emailtemplate->sent();
        }]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/customer_approve', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/customer_approve', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/customer_approve', $data));]]></add>
    </operation>
</file>

	<file path="admin/controller/customer/customer.php" email_template="admin.customer_create">
	<operation>
		<search index="0"><![CDATA[if (isset($this->request->post['status'])) {]]></search>
		<add position="before"><![CDATA[
		$this->load->language('extension/module/emailtemplate/customer');

		$data['entry_notify'] = $this->language->get('entry_notify');

		if (isset($this->request->post['notify'])) {
			$data['notify'] = $this->request->post['notify'];
		} else {
			$data['notify'] = true;
		}
		]]></add>
	</operation>
</file>

<file path="admin/view/template/customer/customer_form.twig" email_template="admin.customer_create">
	<operation>
        <search index="0"><![CDATA[<legend>{{ text_other }}</legend>]]></search>
		<add position="after"><![CDATA[                          {% if not customer_id %}
                        <div class="form-group">
                          <label class="col-sm-2 control-label" for="input-notify">{{ entry_notify }}</label>
                          <div class="col-sm-10">
                            <div class="btn-group btn-group-toggle" data-toggle="buttons">
                              <label class="btn btn-default danger{{ notify == 0 ? ' active' }}" data-toggle="tooltip" title="{{ text_no }}">
                                <input type="radio" name="notify" value="0" {{ notify == 0 ? ' checked="checked" ' }}/><i class="fa fa-fw fa-times"></i>
                              </label>
                              <label class="btn btn-default success{{ notify == 1 ? ' active' }}" data-toggle="tooltip" title="{{ text_yes }}">
                                <input type="radio" name="notify" value="1" {{ notify == 1 ? ' checked="checked" ' }}/><i class="fa fa-fw fa-check"></i>
                              </label>
                            </div>
                          </div>
                        </div>
                      {% endif %}]]></add>
	</operation>
</file>

	<file path="admin/controller/mail/customer.php" email_template="admin.customer_deny">
	<operation>
		<search index="1"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: admin.customer_deny
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
				'key' => 'admin.customer_deny',
				'customer_id' => $customer_info['customer_id'],
				'customer_group_id' => $customer_info['customer_group_id'],
				'language_id' => $customer_info['language_id'],
				'store_id' => $customer_info['store_id']
			);

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
			    $template->addData($customer_info);
			    // Prepared mail: admin.customer_deny
            }
		]]></add>
	</operation>
	<operation>
		<search index="1"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
		// Send mail: admin.customer_deny
		if ($template && $template->check()) {
		    $template->build();
            $template->hook($mail);

            $mail->send();

            $this->model_extension_module_emailtemplate->sent();
        }]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/customer_deny', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/customer_deny', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/customer_deny', $data));]]></add>
    </operation>
</file>

	<file path="admin/controller/customer/customer.php" email_template="admin.customer_history">
    <operation error="skip">
        <search index="0"><![CDATA[$this->model_customer_customer->addHistory($customer_id, $this->request->post['comment']);]]></search>
        <ignoreif><![CDATA[$this->model_customer_customer->addHistory($customer_id, $this->request->post['comment'], $history_notify]]></ignoreif>
        <add position="replace"><![CDATA[$history_notify = !empty($this->request->post['history_notify']) ? true : false;

                $this->model_customer_customer->addHistory($customer_id, $this->request->post['comment'], $history_notify);]]></add>
    </operation>
    <operation error="skip">
        <search index="0"><![CDATA[$this->model_customer_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment']);]]></search>
        <ignoreif><![CDATA[$this->model_customer_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment'], $history_notify]]></ignoreif>
        <add position="replace"><![CDATA[$history_notify = !empty($this->request->post['history_notify']) ? true : false;

                $this->model_customer_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment'], $history_notify);]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[$customer_info = $this->model_customer_customer->getCustomer($this->request->get['customer_id']);]]></search>
        <add position="after" offset="1"><![CDATA[
        $this->document->addScript('view/javascript/summernote/summernote.js');
		$this->document->addScript('view/javascript/summernote/opencart.js');
		$this->document->addStyle('view/javascript/summernote/summernote.css');

        $this->load->language('extension/module/emailtemplate/customer');

		$this->load->model('extension/module/emailtemplate');

		$templates = $this->model_extension_module_emailtemplate->getTemplates(array(
			'emailtemplate_key' => 'admin.customer_history'
		));

		$data['language_id'] = array();

		$data['template_options'] = array();

		foreach($templates as $row) {
			$data['template_options'][] = array(
				'value' => $row['emailtemplate_id'],
				'label' => $row['emailtemplate_label'] . (!empty($row['emailtemplate_default']) ? ' (' . strip_tags($this->language->get('text_default')) . ')': '')
			);
		}

		$data['user_token'] = $this->session->data['user_token'];

        if (isset($this->request->post['language_id'])) {
			$data['language_id'] = $this->request->post['language_id'];
		} elseif (!empty($customer_info)) {
			$data['language_id'] = $customer_info['language_id'];
		} else {
			$data['language_id'] = $this->config->get('config_language_id');
		}

        if (isset($this->request->post['store_id'])) {
			$data['store_id'] = $this->request->post['store_id'];
		} elseif (!empty($customer_info)) {
			$data['store_id'] = $customer_info['store_id'];
		} else {
			$data['store_id'] = $this->config->get('config_store_id');
		}
        ]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA['comment'    => $result['comment'],]]></search>
        <add position="replace"><![CDATA['comment'    => html_entity_decode($result['comment'], ENT_QUOTES, 'UTF-8'),
        		'notify'    => $this->language->get($result['notified'] ? 'text_yes' : 'text_no'),]]></add>
    </operation>
</file>

<file path="admin/model/customer/customer.php" email_template="admin.customer_history">
    <operation>
        <search index="0"><![CDATA[function addHistory($customer_id, $comment]]></search>
        <ignoreif><![CDATA[function addHistory($customer_id, $comment, $notify = false]]></ignoreif>
        <add position="replace"><![CDATA[function addHistory($customer_id, $comment, $notify = false]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[$this->db->query("INSERT INTO " . DB_PREFIX . "customer_history SET]]></search>
        <ignoreif><![CDATA[notified = '" . (int)$notify]]></ignoreif>
        <add position="replace"><![CDATA[$this->db->query("INSERT INTO " . DB_PREFIX . "customer_history SET notified = '" . (int)$notify . "', ]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[$this->db->query("INSERT INTO " . DB_PREFIX . "customer_history]]></search>
        <ignoreif><![CDATA[$customer_history_id = $this->db->getLastId();]]></ignoreif>
        <add position="after"><![CDATA[
        $customer_history_id = $this->db->getLastId();

        return $customer_history_id;]]></add>
    </operation>
    <operation error="skip">
        <search index="0"><![CDATA[comment = '" . $this->db->escape(strip_tags($comment)) . "']]></search>
        <add position="replace"><![CDATA[comment = '" . $this->db->escape((string)$comment) . "']]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[SELECT comment, date_added]]></search>
        <add position="replace"><![CDATA[SELECT comment, date_added, notified]]></add>
    </operation>
</file>

<file path="admin/view/template/customer/customer_history.twig" email_template="admin.customer_history">
<operation>
    <search index="0"><![CDATA[{{ column_comment }}</td>]]></search>
    <add position="after"><![CDATA[        <td class="text-left">{{ column_notify }}</td>]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[{{ history.comment }}</td>]]></search>
    <add position="after"><![CDATA[        <td class="text-left">{{ history.notify }}</td>]]></add>
</operation>
</file>

<file path="admin/view/template/customer/customer_form.twig" email_template="admin.customer_history">
<operation>
    <search index="0"><![CDATA[id="input-comment" class="form-control]]></search>
    <add position="replace"><![CDATA[data-toggle="summernote" id="input-comment" class="form-control summernote]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[id="input-comment"]]></search>
    <add position="after"><![CDATA[
                  {% if customer_id %}
                      </div>
                  </div>
                  <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="input-history-notify">{{ entry_notify }}</label>
                    <div class="col-sm-10">
                      <div class="btn-group btn-group-toggle" data-toggle="buttons">
                        <label class="btn btn-default danger active" data-toggle="tooltip" title="{{ text_no }}">
                          <input type="radio" name="history_notify" value="0" checked="checked" /><i class="fa fa-fw fa-times"></i>
                        </label>
                        <label class="btn btn-default success" data-toggle="tooltip" title="{{ text_yes }}">
                          <input type="radio" name="history_notify" id="input-history-notify" value="1" /><i class="fa fa-fw fa-check"></i>
                        </label>
                      </div>
                    </div>
                  </div>
                  <div class="row form-group form-group-history-notify" style="display:none">
                    <label class="col-sm-2 col-form-label" for="input-templates">{{ entry_template }}</label>
                    <div class="col-sm-10">
                      <select id="input-templates" name="emailtemplate_id" class="form-control">
                        <option value="">{{ text_select }}</option>
                        {% for item in template_options %}
                          <option value="{{ item.value }}">{{ item.label }}</option>
                        {% endfor %}
                      </select>
                  {% endif %}
		]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[$('#button-history').on('click']]></search>
    <add position="after"><![CDATA[  if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
  	  if (CKEDITOR.instances["input-comment"]) {
		  CKEDITOR.instances["input-comment"].updateElement();
	  } else {
		  CKEDITOR.instances["comment"].updateElement();
	  }
  }

  if ($("textarea[name='comment']").val().replace(/(<([^>]+)>)/ig,"") == '') {
    $("textarea[name='comment']").val('');
  }]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[data: 'comment=' + encodeURIComponent($('#tab-history textarea[name=\'comment\']').val()),]]></search>
    <add position="replace"><![CDATA[data: $('#tab-history :input').serialize(),]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[$('#tab-history textarea[name=\'comment\']').val('');]]></search>
    <add position="after"><![CDATA[if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
			  if (CKEDITOR.instances["input-comment"]) {
				  CKEDITOR.instances["input-comment"].setData('');
			  } else {
				  CKEDITOR.instances["comment"].setData('');
			  }
	        } else if ($.fn.summernote) {
              $('#tab-history textarea[name=comment]').summernote('reset');
            }

			$('select[name=history_notify] > option:selected').prop('selected', false);

           	$('.form-group-history-notify').hide().each(function(){
           		$(this).find('input[type=checkbox]').prop('checked', false);
           		$(this).find('input[type=radio][value!=0]').prop('selected', false);
           		$(this).find('input[type=radio][value=0]').prop('selected', true);
           		$(this).find('option:selected').prop('selected', false);
           	});]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[{{ footer }}]]></search>
    <add position="before"><![CDATA[
<script type="text/javascript"><!--
(function($){
  $(document).ready(function(){
    var $comment = $('#tab-history textarea[name=comment]');

    $('input[name=history_notify]').on('change', function(){
      $('.form-group-history-notify').toggle($(this).val() == 1 ? true : false);
    });

    $('select[name=emailtemplate_id]').change(function() {
      var val = $(this).val();

      if (!val || ($comment.val() != '' && $comment.val() != '<p><br></p>' && !confirm("{{ warning_template_content }}"))) return;

	  $comment.val('');

      $.ajax({
        url: 'index.php?route=extension/module/emailtemplate/fetch_template&output=comment&user_token={{ user_token }}',
        type: 'get',
        data: 'emailtemplate_id=' + val + '&store_id={{ store_id }}' + '&language_id={{ language_id }}' + '&customer_id={{ customer_id }}',
        dataType: 'html',
        success: function(html) {
          if (html) {
            $comment.val(html);

            if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
              if (CKEDITOR.instances["input-comment"]) {
                CKEDITOR.instances["input-comment"].setData(html);
              } else {
                CKEDITOR.instances["comment"].setData(html);
              }
            } else if ($.fn.summernote) {
				$comment.summernote('code', html);
			}
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    });
  });
})(jQuery);
//--></script>]]></add>
</operation>
</file>

	<file path="admin/controller/mail/reward.php" email_template="admin.customer_reward">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: admin.customer_reward
			$this->load->model('customer/customer');
			$this->load->model('sale/order');
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
			    'key' =>'admin.customer_reward',
			    'customer_id' => $customer_info['customer_id'],
				'customer_group_id' => $customer_info['customer_group_id'],
				'language_id' => $customer_info['language_id'],
				'store_id' => $customer_info['store_id']
            );

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                $template->addData($customer_info, 'customer');

                if ($order_id) {
                	$order_info = $this->model_sale_order->getOrder($order_id);
                	if ($order_info) {
                		$template->addData($order_info, 'order');
					}
                }

                $template->data['customer_reward_points'] = $points ? $points : 0;
                $template->data['customer_reward_description'] = $description ? $description : '';
                $template->data['customer_reward_total'] = $this->model_customer_customer->getRewardTotal($customer_id);

                $template->data['reward_received'] = sprintf($template->data['text_reward_received'], $template->data['customer_reward_points']);
                $template->data['reward_total'] = sprintf($template->data['text_reward_total'], $template->data['customer_reward_total']);

                $template->data['text_reward_subject'] = sprintf($template->data['text_reward_subject'], $store_name);
			    // Prepared mail: admin.customer_reward
			}
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
			// Send mail: admin.customer_reward
            if ($template && $template->check()) {
                $template->build();
			    $template->hook($mail);

                $mail->send();

                $this->model_extension_module_emailtemplate->sent();
            }]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/reward', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/reward', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/reward', $data));]]></add>
    </operation>
</file>

	<file path="admin/controller/mail/transaction.php" email_template="admin.customer_transaction">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: admin.customer_transaction
			$this->load->model('customer/customer');
			$this->load->model('sale/order');
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
			    'key' =>'admin.customer_transaction',
			    'customer_id' => $customer_info['customer_id'],
				'customer_group_id' => $customer_info['customer_group_id'],
				'language_id' => $customer_info['language_id'],
				'store_id' => $customer_info['store_id']
            );

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                $template->data['amount'] = $amount;
                $template->data['description'] = $description;

                $template->addData($customer_info, 'customer');

                if ($order_id) {
                    $order_info = $this->model_sale_order->getOrder($order_id);

                    $template->addData($order_info, 'order');
                }

                $affiliate_info = $this->model_customer_customer->getAffiliate($customer_info['customer_id']);

                if ($affiliate_info) {
                    $template->addData($affiliate_info, 'affiliate');
                }

                $template->data['customer_transaction_received'] = $this->currency->format($amount, $this->config->get('config_currency'));
                $template->data['customer_transaction_total'] = $this->currency->format($this->model_customer_customer->getTransactionTotal($customer_id), $this->config->get('config_currency'));

                $template->data['transaction_received'] = sprintf($template->data['text_transaction_received'], $template->data['customer_transaction_received']);
                $template->data['transaction_total'] = sprintf($template->data['text_transaction_total'], $template->data['customer_transaction_total']);
			    // Prepared mail: admin.customer_transaction
            }
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
			// Send mail: admin.customer_transaction
            if ($template && $template->check()) {
                $template->build();
			    $template->hook($mail);

                $mail->send();

                $this->model_extension_module_emailtemplate->sent();
            }]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/transaction', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/transaction', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/transaction', $data));]]></add>
    </operation>
</file>


	<file path="admin/controller/marketing/contact.php" email_template="admin.newsletter">
	<operation>
		<search index="0"><![CDATA[$data['breadcrumbs'] = array();]]></search>
		<add position="before"><![CDATA[
        $this->document->addScript('view/javascript/summernote/summernote.js');
        $this->document->addScript('view/javascript/summernote/opencart.js');
        $this->document->addStyle('view/javascript/summernote/summernote.css');

		$this->load->model('localisation/language');
		$this->load->model('extension/module/emailtemplate');

		$this->load->language('extension/module/emailtemplate/newsletter');

        $templates = $this->model_extension_module_emailtemplate->getTemplates(array(
			'emailtemplate_key' => 'admin.newsletter'
		));

		$data['email_templates'] = array();

		foreach($templates as $row) {
			$data['email_templates'][] = array(
				'value' => $row['emailtemplate_id'],
				'label' => $row['emailtemplate_label'] . (!empty($row['emailtemplate_default']) ? ' (' . strip_tags($this->language->get('text_default')) . ')': '')
			);
		}

		$data['languages'] = $this->model_localisation_language->getLanguages();

        $data['user_token'] = $this->session->data['user_token'];
	]]></add>
	</operation>
    <operation>
        <search index="0"><![CDATA[if (!$this->request->post['subject']) {]]></search>
        <add position="replace" offset="6"><![CDATA[if (empty($json['error'])) {
				$this->load->model('localisation/language');

				$languages = $this->model_localisation_language->getLanguages();

				foreach ($languages as $language) {
					if (empty($this->request->post['subject'][$language['language_id']])) {
						$json['error']['subject'][$language['language_id']] = $this->language->get('error_subject');
					}

					if (empty($this->request->post['message'][$language['language_id']]) || trim(strip_tags(html_entity_decode($this->request->post['message'][$language['language_id']], ENT_QUOTES, 'UTF-8'))) == '') {
						$json['error']['message'][$language['language_id']] = $this->language->get('error_message');
					}
				}

				if (!empty($json['error'])) {
					$json['error']['warning'] = $this->language->get('error_warning');
				}
			}]]></add>
    </operation>
	<operation info="Add extra info into email array. Regex to be backwards compatible with 3.0.1.*">
		<search regex="true"><![CDATA[~\$emails\[.*?\] = \$customer_info\['email'\];~]]></search>
		<add position="replace"><![CDATA[$email_total = isset($this->request->post['customer']) ? count($this->request->post['customer']) : 1;;

									$emails[] = array(
										'customer' => $customer_info,
										'email' => $customer_info['email'],
										'customer_id' => $customer_info['customer_id'],
										'store_id' => $customer_info['store_id'],
										'language_id' => $customer_info['language_id']
									);]]></add>
	</operation>
	<operation info="Add extra info into email array">
		<search><![CDATA[$emails[$result['customer_id']] = $result['email'];]]></search>
		<add position="replace"><![CDATA[$emails[] = array(
								'email' => $result['email'],
								'customer_id' => isset($result['customer_id']) ? $result['customer_id'] : 0,
								'store_id' => isset($result['store_id']) ? $result['store_id'] : 0,
								'language_id' => isset($result['language_id']) ? $result['language_id'] : 0
							);]]></add>
	</operation>
	<operation info="affiliate_all">
		<search index="2"><![CDATA[$emails[] = $result['email'];]]></search>
		<add position="replace"><![CDATA[$emails[] = array(
								'email' => $result['email'],
								'affiliate_id' => $result['affiliate_id']
							);]]></add>
	</operation>
	<operation info="affiliate">
		<search><![CDATA[$emails[] = $affiliate_info['email'];]]></search>
		<add position="replace"><![CDATA[$email_total = 1;

									$emails[] = array(
										'affiliate' => $affiliate_info,
										'email' => $affiliate_info['email'],
										'affiliate_id' => $affiliate_info['affiliate_id']
									);]]></add>
	</operation>
	<operation info="newsletter, customer_all, product">
		<search><![CDATA[$emails[] = $result['email'];]]></search>
		<add position="replace"><![CDATA[$emails[] = array(
								'email' => $result['email'],
								'customer_id' => isset($result['customer_id']) ? $result['customer_id'] : 0,
								'store_id' => isset($result['store_id']) ? $result['store_id'] : 0,
								'language_id' => isset($result['language_id']) ? $result['language_id'] : 0
							);]]></add>
	</operation>

	<operation info="Move message into foreach">
		<search index="0"><![CDATA[foreach ($emails as $email) {]]></search>
		<add/>
	</operation>
	<operation>
		<search index="0"><![CDATA[$message  = '<html ]]></search>
		<add position="before"><![CDATA[					if (isset($this->request->get['sent_total'])) {
                        $sent_total = $this->request->get['sent_total'];
                    } else {
                        $sent_total = 0;
                    }

		            foreach ($emails as $email_info) {
						$email = is_array($email_info) ? $email_info['email'] : $email_info;

						if (!empty($email_info['language_id'])) {
							$language_id = $email_info['language_id'];
						} else {
							$language_id = $this->config->get('config_language_id');
						}

						if (isset($email_info['store_id']) && $this->request->post['store_id'] == 0) {
 							$store_id = $email_info['store_id'];
						} else {
							$store_id = $this->request->post['store_id'];
						}

						// Prepare mail: admin.newsletter
						$this->load->model('extension/module/emailtemplate');

						$template_load = array(
							'key' => 'admin.newsletter',
							'language_id' => $language_id,
							'email' => $email,
							'store_id' => $store_id
						);

						if (isset($email_info['customer']) && isset($email_info['customer']['customer_id'])) {
							$template_load['customer_id'] = $email_info['customer']['customer_id'];
						} elseif (!empty($email_info['customer_id'])) {
                            $template_load['customer_id'] = $email_info['customer_id'];
                        } else {
                            $this->load->model('customer/customer');

                            $customer_info = $this->model_customer_customer->getCustomerByEmail($email);

                            if ($customer_info) {
                                $template_load['customer_id'] = $email_info['customer_id'];
                            }
						}

						if (!empty($this->request->post['emailtemplate_id'])) {
                            $template_load['emailtemplate_id'] = $this->request->post['emailtemplate_id'];
                        }

                        // Disable preference checking if not newsletter
                        $module_status = ($this->config->get('module_emailtemplate_newsletter_status') && $this->config->get('module_emailtemplate_newsletter_preference'));
                        if ($module_status && isset($this->request->post['to']) && in_array($this->request->post['to'], array('customer', 'customer_all'))) {
                            $template_load['disable_newsletter_preference'] = true;
                        }

						$template = $this->model_extension_module_emailtemplate->load($template_load);

                        if ($template) {
                            if (isset($email_info['customer'])) {
                                $template->addData($email_info['customer']);
                                unset($email_info['customer']);
                            } elseif (isset($template_load['customer_id'])) {
                                $customer_info = $this->model_customer_customer->getCustomer($template_load['customer_id']);

                                if ($customer_info) {
                                    $template->addData($customer_info);
                                }
                            }

                            if (isset($email_info['affiliate'])) {
                                $template->addData($email_info['affiliate']);
                                unset($email_info['affiliate']);
                            } elseif (isset($email_info['affiliate_id'])) {
                                $affiliate_info = $this->model_sale_affiliate->getAffiliate($email_info['affiliate_id']);
                                $template->addData($affiliate_info);
                            }

                            if (!empty($this->request->post['subject'][$language_id])) {
                                $template->data['emailtemplate']['subject'] = $this->request->post['subject'][$language_id];
                            } else {
                                $template->data['emailtemplate']['subject'] = $this->config->get('config_name');
                            }

                            if (!empty($this->request->post['preview'][$language_id])) {
                                $template->data['emailtemplate']['preheader_preview'] = $this->request->post['preview'][$language_id];
                            }

                            if (!empty($this->request->post['message'][$language_id]) && is_array($this->request->post['message'])) {
                                $template->data['message'] = $this->request->post['message'][$language_id];
                            } else {
                                $template->data['message'] = '';
                            }

                            if (is_array($email_info)) {
                                $template->addData($email_info);
                            } else {
                                $template->addData('email', $email_info);
                            }
						    // Prepared mail: admin.newsletter
                        }
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[<title>' . $this->request->post['subject'] . '</title>]]></search>
		<add position="replace"><![CDATA[<title></title>]]></add>
	</operation>
    <operation>
		<search index="0"><![CDATA[$mail->setSubject(html_entity_decode($this->request->post['subject'], ENT_QUOTES, 'UTF-8'));]]></search>
		<add position="replace"></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[html_entity_decode($this->request->post['message'],]]></search>
		<add position="replace"><![CDATA[html_entity_decode(($template ? $template->data['message'] : ''),]]></add>
	</operation>
    <operation>
        <search index="0"><![CDATA[if ($emails) {]]></search>
        <ignoreif><![CDATA[$json['error']['email'] = $this->language->get('error_email');]]></ignoreif>
        <add position="replace"><![CDATA[if (!$emails) {
                    $json['error']['email'] = $this->language->get('error_email');
                } else {]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[$mail->send();]]></search>
        <add position="after" offset="1"><![CDATA[					if ($json['next'] && $sent_total) {
						$json['next'] .= '&sent_total=' . $sent_total;
        			}

        			$json['success'] = sprintf($this->language->get('text_sent'), $sent_total, $email_total);]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[$mail->send();]]></search>
        <add position="replace"><![CDATA[// Send mail: admin.newsletter
							if ($template && $template->check()) {
								if ($template->data['message']) {
									$template->data['message'] = $template->replaceContent($template->data['message']);
								}

								$template->build();

                                // Disable preference checking if not newsletter
                                $module_status = ($this->config->get('module_emailtemplate_newsletter_status') && $this->config->get('module_emailtemplate_newsletter_preference'));
                                if ($module_status && isset($this->request->post['to']) && in_array($this->request->post['to'], array('customer', 'customer_all'))) {
                                    $template->data['emailtemplate']['preference'] = false;
                                }

								$mail->setSubject($template->data['emailtemplate']['subject']);

								if (trim(strip_tags($template->data['emailtemplate']['content1'])) == '') {
                                    $template->fetch(null, $template->data['message']);
								}

								$template->hook($mail);

								$mail->send();

								$this->model_extension_module_emailtemplate->sent();

								$sent_total++;
							}]]></add>
    </operation>
	<operation>
		<search index="0"><![CDATA[$this->load->view('marketing/contact']]></search>
		<add position="replace"><![CDATA[$this->load->view('extension/module/emailtemplate/marketing_contact']]></add>
	</operation>
</file>

<file path="catalog/controller/account/newsletter.php" email_template="admin.newsletter">
	<operation>
	    <search index="0"><![CDATA[class ControllerAccountNewsletter extends Controller {]]></search>
	   	<ignoreif><![CDATA[public function unsubscribe(]]></ignoreif>
	   	<add position="after"><![CDATA[	public function unsubscribe() {
        $this->response->redirect($this->url->link('extension/module/emailtemplate_newsletter/unsubscribe'));
 	}
 	  ]]></add>
	</operation>
</file>

	<file path="admin/controller/mail/return.php" email_template="admin.return_history">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
				// Prepare mail: admin.return_history
				$this->load->model('extension/module/emailtemplate');
				$this->load->model('sale/order');

				$order_info = $this->model_sale_order->getOrder($return_info['order_id']);

                $template_load = array(
                    'key' => 'admin.return_history',
                    'customer_id' => $return_info['customer_id']
                );

                if (isset($order_info['store_id'])) {
                    $template_load['store_id'] = $order_info['store_id'];
                    $template_load['payment_method'] = $order_info['payment_code'];
                    $template_load['shipping_method'] = $order_info['shipping_code'];
                }

                if (!empty($this->request->post['emailtemplate_id'])) {
                    $template_load['emailtemplate_id'] = $this->request->post['emailtemplate_id'];
                }

                if (isset($order_info['language_id'])) {
					$language_id = $order_info['language_id'];
				} elseif (!empty($return_info['customer_id'])) {
				    $this->load->model('customer/customer');

		            $customer_info = $this->model_customer_customer->getCustomer($return_info['customer_id']);

                    $language_id = $customer_info['language_id'];
				} else {
				    $language_id = $this->config->get('config_language_id');
				}

				$template_load['language_id'] = $language_id;

				$template = $this->model_extension_module_emailtemplate->load($template_load);

                if ($template) {
                    $this->load->model('localisation/language');

                    $language_info = $this->model_localisation_language->getLanguage($language_id);

                    if ($language_info) {
                        $language_code = $language_info['code'];
                    } else {
                        $language_code = $this->config->get('config_language');
                    }

                    $language = new Language($language_code);
                    $language->load($language_code);
                    $language->load('mail/return');
                    $language->load('extension/module/emailtemplate/return');

                    $template->addData($return_info);

                    if ($return_info['product_id']) {
                        $this->load->model('catalog/product');

                        $product_info = $this->model_catalog_product->getProduct($return_info['product_id']);

                        $template->addData($product_info, 'product');
                    }

                    if ($order_info) {
                        $template->addData($order_info, 'order');

                        $template->data['order_id'] = $order_info['order_id'];

                        $template->data['order_total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

                        $template->data['return_link'] = $order_info['store_url'] . 'index.php?route=account/return/info&return_id=' . $return_id;
                    } else {
                        $template->data['return_link'] = HTTP_CATALOG . 'index.php?route=account/return/info&return_id=' . $return_id;
                    }

                    if (!empty($template->data['button_return_link'])) {
                        $template->data['return_link_text'] = $template->data['button_return_link'];
                    } else {
                        $template->data['return_link_text'] = $template->data['return_link'];
                    }

                    $return_reason_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "return_reason WHERE return_reason_id = '" . (int)$return_info['return_reason_id'] . "' AND language_id = '" . (int)$language_id . "'");

                    if ($return_reason_query->row) {
                        $template->data['reason'] = $return_reason_query->row['name'];
                    }

                    $return_status_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "return_status WHERE return_status_id = '" . (int)$return_info['return_status_id'] . "' AND language_id = '" . (int)$language_id . "'");

                    if ($return_status_query->row) {
                        $template->data['return_status'] = $return_status_query->row['name'];
                    }

                    $template->data['return_id'] = $return_id;

                    $template->data['date_added'] = date($language->get('date_format_short'), strtotime($return_info['date_added']));

                    $template->data['comment'] = (!empty($comment)) ? (strcmp($comment, strip_tags($html_str = html_entity_decode($comment, ENT_QUOTES, 'UTF-8'))) == 0) ? nl2br($comment) : $html_str : '';

                    $template->data['opened'] = $return_info['opened'] ? $language->get('text_yes') : $language->get('text_no');

                    $template->data['text_subject'] = sprintf($language->get('text_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'), $return_id);
				    // Prepared mail: admin.return_history
                }
			]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
				// Send mail: admin.return_history
				if ($template && $template->check()) {
				    $template->build();
				    $template->hook($mail);

                    $mail->send();

                    $this->model_extension_module_emailtemplate->sent();
                }]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/return', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/return', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/return', $data));]]></add>
    </operation>
    <operation error="skip" info="Bug fix">
        <search index="0"><![CDATA[$language_info = $this->model_localisation_language->getLanguage($return_info['language_id']);]]></search>
        <ignoreif><![CDATA[$this->load->model('localisation/language');]]></ignoreif>
        <add position="before"><![CDATA[				$this->load->model('localisation/language');
        ]]></add>
    </operation>
</file>

<file path="admin/controller/sale/return.php" email_template="admin.return_history">
	<operation>
		<search index="0"><![CDATA[protected function getForm() {]]></search>
		<add position="after"><![CDATA[
				$this->document->addScript('view/javascript/summernote/summernote.js');
				$this->document->addScript('view/javascript/summernote/opencart.js');
				$this->document->addStyle('view/javascript/summernote/summernote.css');

				$this->load->model('extension/module/emailtemplate');

				$this->load->language('mail/return');
				$this->load->language('extension/module/emailtemplate/return');

				$data['entry_summary'] = $this->language->get('entry_summary');
				$data['entry_template'] = $this->language->get('entry_template');
				$data['text_select'] = $this->language->get('text_select');
				$data['warning_template_content'] = $this->language->get('warning_template_content');

				$templates = $this->model_extension_module_emailtemplate->getTemplates(array(
					'emailtemplate_key' => 'admin.return_history'
				));

				$data['template_options'] = array();

				foreach($templates as $row) {
					$data['template_options'][] = array(
						'value' => $row['emailtemplate_id'],
						'label' => $row['emailtemplate_label'] . (!empty($row['emailtemplate_default']) ? strip_tags($this->language->get('text_default')) : '')
					);
				}

				$data['user_token'] = $this->session->data['user_token'];
		]]></add>
	</operation>
	<operation>
		<search><![CDATA[$data['order_id'] = $return_info['order_id'];]]></search>
		<add position="after"><![CDATA[
				$this->load->model('sale/order');

				$order_info = $this->model_sale_order->getOrder($return_info['order_id']);

				if ($order_info) {
					$data['language_id'] = $order_info['language_id'];
					$data['store_id'] = $order_info['store_id'];
				} else {
					$data['language_id'] = $this->config->get('config_language_id');
					$data['store_id'] = 0;
				}]]></add>
	</operation>
	<operation error="skip">
		<search><![CDATA[$data['comment'] = $this->request->post['comment'];]]></search>
		<add position="replace"><![CDATA[$data['comment'] = html_entity_decode($this->request->post['comment'], ENT_QUOTES, 'UTF-8');]]></add>
	</operation>
	<operation>
		<search><![CDATA[$data['comment'] = $return_info['comment'];]]></search>
		<add position="replace"><![CDATA[$data['comment'] = html_entity_decode($return_info['comment'], ENT_QUOTES, 'UTF-8');]]></add>
	</operation>
	<operation>
		<search><![CDATA[nl2br($result['comment'])]]></search>
		<add position="replace"><![CDATA[html_entity_decode($result['comment'], ENT_QUOTES, 'UTF-8')]]></add>
	</operation>
</file>

<file path="admin/view/template/sale/return_form.twig" email_template="admin.return_history">
	<operation>
		<search index="0"><![CDATA[id="input-history-comment" class="form-control"]]></search>
		<add position="replace"><![CDATA[id="input-history-comment" class="form-control summernote" data-toggle="summernote"]]></add>
	</operation>
	<operation error="skip" info="Version conflict">
		<search index="0"><![CDATA[<input type="checkbox" name="notify" value="1" id="input-notify"/>]]></search>
		<add position="replace"><![CDATA[<input type="checkbox" name="notify" value="1" id="input-notify" />]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[<input type="checkbox" name="notify" value="1" id="input-notify" />]]></search>
		<add position="replace"><![CDATA[
          		  <div class="checkbox"><label><input type="checkbox" name="notify" value="1" id="input-notify" data-toggle="collapse" data-target=".form-group-notify" autocomplete="off" /></label></div>
                </div>
              </div>

              <div class="form-group form-group-notify collapse">
                <label class="col-sm-2 control-label" for="input-templates">{{ entry_template }}</label>
                <div class="col-sm-10">
                  <select id="input-templates" name="emailtemplate_id" class="form-control" autocomplete="off">
	 				<option value=''>{{ text_select }}</option>
	            	{% for item in template_options %}
	            		<option value="{{ item.value }}">{{ item.label }}</option>
	            	{% endfor %}
            	  </select>]]></add>
	</operation>
    <operation>
		<search index="0"><![CDATA[{{ footer }}]]></search>
		<add position="before"><![CDATA[
<script type="text/javascript"><!--
			(function($) {
				$(document).ready(function() {
			    	var $comment = $('#input-history-comment');

					$('select[name=emailtemplate_id]').change(function() {
						var val = $(this).val();
						var $comment = $('#input-history-comment');

						if (!val || ($comment.val() != '' && $comment.val() != '<p><br /></p>' && !confirm("{{ warning_template_content }}"))) return;

						$.ajax({
							url: 'index.php?route=extension/module/emailtemplate/fetch_template&output=comment&user_token={{ user_token }}',
							type: 'get',
							data: 'id=' + val + '&store_id={{ store_id }}' + '&language_id={{ language_id }}' + '&order_id={{ order_id }}' + '&return_id={{ return_id }}',
							dataType: 'html',
							success: function(html) {
								if (typeof CKEDITOR !== "undefined" && CKEDITOR.instances["input-history-comment"]) {
								  CKEDITOR.instances["input-history-comment"].setData(html);
								} else if ($.fn.summernote) {
                                    $comment.summernote('code', html);
                                } else {
									$comment.val(html);
								}
							},
							error: function(xhr, ajaxOptions, thrownError) {
								console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
							}
						});
					});

				});
			})(jQuery);
		//--></script>
		]]></add>
	</operation>
    <operation>
		<search index="0"><![CDATA[$('#button-history').on('click', function(e) {]]></search>
		<add position="after"><![CDATA[
	if (typeof CKEDITOR !== "undefined" && CKEDITOR.instances["input-history-comment"]) {
	  CKEDITOR.instances["input-history-comment"].updateElement();
	}

	if ($("#input-history-comment").val() == '<br />' || $("#input-history-comment").val() == '<p><br></p>') {
		$("#input-history-comment").val('');
	}
]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA['&comment=' + encodeURIComponent($('#tab-history textarea[name=\'comment\']').val())]]></search>
		<add position="replace"><![CDATA['&comment=' + encodeURIComponent($('#input-history-comment').val()) + '&show_summary=0' + '&emailtemplate_id=' + encodeURIComponent($('select[name=\'emailtemplate_id\']').val())]]></add>
	</operation>
    <operation>
		<search index="0"><![CDATA[$('#tab-history textarea[name=\'comment\']').val('');]]></search>
		<add position="after"><![CDATA[
	  if (typeof CKEDITOR !== "undefined" && CKEDITOR.instances["input-history-comment"]) {
		CKEDITOR.instances["input-history-comment"].setData('');
	  } else if ($.fn.summernote) {
        $('#input-history-comment').summernote('reset');
      }

	  $('#input-templates').each(function(){ this.selectedIndex = this.defaultSelected });]]></add>
	</operation>
</file>

<file path="catalog/controller/account/return.php" email_template="admin.return_history">
	<operation>
		<search><![CDATA[nl2br($result['comment'])]]></search>
		<add position="replace"><![CDATA[html_entity_decode($result['comment'], ENT_QUOTES, 'UTF-8')]]></add>
	</operation>
</file>

	<file path="admin/controller/sale/voucher.php" email_template="admin.voucher">
	<operation>
	    <search index="0,1"><![CDATA[$mail->setHtml($this->load->view('mail/voucher', $data));]]></search>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/voucher', $data));]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
	    <add position="before"><![CDATA[							// Prepare mail: admin.voucher
	    					$this->load->model('extension/module/emailtemplate');

							$template_load = array(
							    'key' => 'admin.voucher',
							    'customer_id' => $order_info['customer_id'],
							    'customer_group_id' => $order_info['customer_group_id'],
							    'language_id' => $order_info['language_id'],
							    'store_id' => $order_info['store_id'],
                                'payment_method' => $order_info['payment_code'],
                                'shipping_method' => $order_info['shipping_code']
                            );

							$template = $this->model_extension_module_emailtemplate->load($template_load);

                            if ($template) {
                                $template->addData($order_info);

                                if (!empty($data)) $template->addData($data);

                                $template->data['store_id'] = $order_info['store_id'];

                                $template->data['language_id'] = $order_info['language_id'];

                                $template->addData($voucher_info);

                                $template->addData($voucher_theme_info);

                                if ($voucher_theme_info['image'] && file_exists(DIR_IMAGE . $voucher_theme_info['image'])) {
                                    $template->data['image'] = $template->data['store_url'] . 'image/' . $voucher_theme_info['image'];

                                    list($template->data['image_width'], $template->data['image_height']) = getimagesize(DIR_IMAGE . $voucher_theme_info['image']);
                                }

                                $template->data['amount'] = $this->currency->format($voucher_info['amount'], $order_info['currency_code'], $order_info['currency_value']);

                                $template->data['text_heading'] = sprintf($template->data['text_heading'], $template->data['store_name']);

                                $template->data['voucher_url'] = $template->data['store_url'];

                                if (!empty($template->data['button_voucher_url'])) {
                                    $template->data['voucher_url_text'] = $template->data['button_voucher_url'];
                                } else {
                                    $template->data['voucher_url_text'] = $template->data['voucher_url'];
                                }
							}]]></add>
	</operation>
	<operation>
	    <search index="0"><![CDATA[$mail->send();]]></search>
	    <add position="replace"><![CDATA[// Send mail: admin.voucher
	    					if ($template && $template->check()) {
	    					    $template->build();
							    $template->hook($mail);
                            }

							$mail->send();

							$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
	<operation>
	    <search index="1"><![CDATA[$mail = new Mail(]]></search>
	    <add position="before"><![CDATA[	    					$this->load->model('extension/module/emailtemplate');

							$template_load = array('key' => 'admin.voucher');

							$template = $this->model_extension_module_emailtemplate->load($template_load);

							if ($template) {
                                if (!empty($data)) $template->addData($data);

                                $template->addData($voucher_info);

                                $template->addData($voucher_theme_info);

                                if ($voucher_theme_info['image'] && file_exists(DIR_IMAGE . $voucher_theme_info['image'])) {
                                    $template->data['image'] = $template->data['store_url'] . 'image/' . $voucher_theme_info['image'];

                                    list($template->data['image_width'], $template->data['image_height']) = getimagesize(DIR_IMAGE . $voucher_theme_info['image']);
                                }

                                $template->data['amount'] = $this->currency->format($voucher_info['amount'], $this->config->get('config_currency'), $this->currency->getValue($this->config->get('config_currency')));

                                $template->data['text_heading'] = sprintf($template->data['text_heading'], $template->data['store_name']);

                                $template->data['voucher_url'] = $template->data['store_url'];

                                if (!empty($template->data['button_voucher_url'])) {
                                    $template->data['voucher_url_text'] = $template->data['button_voucher_url'];
                                } else {
                                    $template->data['voucher_url_text'] = $template->data['voucher_url'];
                                }
							    // Prepared mail: admin.voucher
							}
		]]></add>
	</operation>
	<operation>
	    <search index="1"><![CDATA[$mail->send();]]></search>
	    <add position="replace"><![CDATA[if ($template) {
	                            $template->build();
							    $template->hook($mail);

                                $mail->send();

                                $this->model_extension_module_emailtemplate->sent();
				            }]]></add>
	</operation>
</file>

	<file path="catalog/controller/mail/affiliate.php" email_template="affiliate.register">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
		// Prepare mail: affiliate.register
		$this->load->model('account/customer');

		if ($this->customer && $this->customer->isLogged()) {
			$customer_id = $this->customer->getId();
		} else {
			$customer_id = $args[0];
		}

		$customer_info = $this->model_account_customer->getCustomer($customer_id);

		if (!$customer_info) {
			trigger_error('Unable to find customer: ' . $args[0]['customer_id']);
			return false;
		}

		$this->load->model('extension/module/emailtemplate');

		$template_load = array(
		    'key' => 'affiliate.register',
		    'customer_id' => $customer_info['customer_id'],
		    'customer_group_id' => $customer_info['customer_group_id'],
		    'language_id' => $customer_info['language_id'],
		    'store_id' => $customer_info['store_id']
        );

		$template = $this->model_extension_module_emailtemplate->load($template_load);

        if ($template) {
            if (!empty($data)) $template->addData($data);

            $template->addData($args[1], 'affiliate');

            $template->addData($customer_info, 'customer');

            $template->data['affiliate_login'] = $this->url->link('affiliate/login');

            if (!empty($template->data['button_affiliate_login'])) {
                $template->data['affiliate_login_text'] = $template->data['button_affiliate_login'];
            } else {
                $template->data['affiliate_login_text'] = $template->data['affiliate_login'];
            }

            if (!empty($args[0]['custom_field'])) {
                $this->load->model('account/custom_field');

                $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                foreach ($custom_fields as $custom_field) {
                        if (isset($args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                            $custom_field_key = 'custom_field_' . ($custom_field['location'] != 'account' ? $custom_field['location'] . '_' : '') . $custom_field['custom_field_id'];
                            $custom_field_value = $args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']];

                            $template->data[$custom_field_key . '_name'] = $custom_field['name'];
                            $template->data[$custom_field_key . '_value'] = '';

                            if ($custom_field['custom_field_value']) {
                                foreach ($custom_field['custom_field_value'] as $custom_field_value_info) {
                                    if (is_array($custom_field_value)) {
                                        if (in_array($custom_field_value_info['custom_field_value_id'], $custom_field_value)) {
                                            $template->data[$custom_field_key . '_value_' . $custom_field_value_info['custom_field_value_id']] = $custom_field_value_info['name'];
                                        }
                                    } else {
                                        if ($custom_field_value_info['custom_field_value_id'] == $custom_field_value) {
                                            $template->data[$custom_field_key . '_value'] = $custom_field_value_info['name'];
                                        }
                                    }
                                }
                            } else {
                                $template->data[$custom_field_key . '_value'] = $custom_field_value;
                            }
                        }
                    }
            }

            $template->data['customer_group'] = $customer_group_info['name'];

            if ($customer_group_info && ($this->config->get('config_affiliate_approval') || $customer_group_info['approval'])) {
                $template->data['affiliate_text'] = $this->language->get('text_approval');
            } else {
                $template->data['affiliate_text'] = $this->language->get('text_login');
            }
            // Prepared mail: affiliate.register
        }
]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: affiliate.register
		if ($template && $template->check()) {
		    $template->build();
		    $template->hook($mail);
        }

		$mail->send();

		$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search index="0"><![CDATA[$mail->setHtml($this->load->view('mail/affiliate', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/mail/affiliate.php" email_template="affiliate.register">
	<operation>
		<search index="1"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
		// Prepare mail: affiliate.register_admin
		$affiliate_info = $args[1];

		if ($this->customer && $this->customer->isLogged()) {
			$customer_id = $this->customer->getId();
		} else {
			$customer_id = $args[0];
		}

		$customer_info = $this->model_account_customer->getCustomer($customer_id);

		if (!$customer_info) {
			trigger_error('Unable to find customer: ' . $args[0]['customer_id']);
			return false;
		}

		// Load template
		$this->load->model('extension/module/emailtemplate');

		$template_load = array(
		    'key' => 'affiliate.register_admin',
		    'customer_id' => $customer_info['customer_id'],
		    'customer_group_id' => $customer_info['customer_group_id'],
		    'language_id' => $customer_info['language_id'],
		    'store_id' => $customer_info['store_id']
        );

		$template = $this->model_extension_module_emailtemplate->load($template_load);

        if ($template) {
            // Add data to: affiliate.register_admin
            $template->addData($args[1], 'affiliate');

            $template->addData($customer_info, 'customer');

            if (!empty($data)) $template->addData($data);

            $template->data['affiliate_login'] = $this->url->link('affiliate/login');

            if (!empty($template->data['button_affiliate_login'])) {
                $template->data['affiliate_login_text'] = $template->data['button_affiliate_login'];
            } else {
                $template->data['affiliate_login_text'] = $template->data['affiliate_login'];
            }

            if (!empty($args[0]['custom_field'])) {
                $this->load->model('account/custom_field');

                $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                foreach ($custom_fields as $custom_field) {
                    if (isset($args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                        $custom_field_key = 'custom_field_' . ($custom_field['location'] != 'account' ? $custom_field['location'] . '_' : '') . $custom_field['custom_field_id'];
                        $custom_field_value = $args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']];

                        $template->data[$custom_field_key . '_name'] = $custom_field['name'];
                        $template->data[$custom_field_key . '_value'] = '';

                        if ($custom_field['custom_field_value']) {
                            foreach ($custom_field['custom_field_value'] as $custom_field_value_info) {
                                if (is_array($custom_field_value)) {
                                    if (in_array($custom_field_value_info['custom_field_value_id'], $custom_field_value)) {
                                        $template->data[$custom_field_key . '_value_' . $custom_field_value_info['custom_field_value_id']] = $custom_field_value_info['name'];
                                    }
                                } else {
                                    if ($custom_field_value_info['custom_field_value_id'] == $custom_field_value) {
                                        $template->data[$custom_field_key . '_value'] = $custom_field_value_info['name'];
                                    }
                                }
                            }
                        } else {
                            $template->data[$custom_field_key . '_value'] = $custom_field_value;
                        }
                    }
                }
            }

            $template->data['customer_group'] = $customer_group_info['name'];

            if (defined('HTTP_ADMIN')) {
                $admin_url = HTTP_ADMIN;
            } elseif ($this->config->get('config_ssl')) {
                $admin_url = $this->config->get('config_ssl') . 'admin/';
            } else {
                $admin_url = $this->config->get('config_url') . 'admin/';
            }

            if ($customer_group_info && ($this->config->get('config_affiliate_approval') || $customer_group_info['approval'])) {
                $template->data['subject'] = $template->data['text_approve_subject_admin'];

                $template->data['affiliate_link'] = $admin_url . 'index.php?route=customer/customer_approval&filter_type=affiliate&filter_email=' . $customer_info['email'];

                $template->data['status'] = $template->data['text_admin_approve'];
            } else {
                $template->data['subject'] = $template->data['text_subject_admin'];

                $template->data['affiliate_link'] = $admin_url . 'index.php?route=customer/customer/edit&customer_id=' . $affiliate_info['customer_id'];

                $template->data['status'] = $template->data[$affiliate_info['status'] ? 'text_enabled' : 'text_disabled'];
            }

            if (isset($template->data['button_affiliate_link']) && $template->data['button_affiliate_link'] != 'button_affiliate_link') {
                $template->data['affiliate_link_text'] =  $template->data['button_affiliate_link'];
            } else {
                $template->data['affiliate_link_text'] =  $template->data['affiliate_link'];
            }
		    // Prepared mail: affiliate.register_admin
		}
]]></add>
	</operation>
	<operation>
		<search index="1"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: affiliate.register_admin
			if ($template && $template->check()) {
			    $template->build();
			    $template->hook($mail);
            }

			$mail->send();

			$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search index="0"><![CDATA[$mail->setHtml($this->load->view('mail/affiliate_alert', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate_alert', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/affiliate_alert', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/mail/forgotten.php" email_template="customer.forgotten">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[			// Prepare mail: customer.forgotten
			$this->load->model('extension/module/emailtemplate');

			$this->load->model('account/customer');

			$customer_info = $this->model_account_customer->getCustomerByEmail($args[0]);

			$template_load = array('key' => 'customer.forgotten');

			if ($customer_info) {
				$template_load['customer_id'] = $customer_info['customer_id'];
				$template_load['customer_group_id'] = $customer_info['customer_group_id'];
				$template_load['language_id'] = $customer_info['language_id'];
			}

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                if (!empty($data)) {
                    $template->addData($data);
                }

                if (isset($this->request->post['email'])) {
                    $template->addData($this->request->post['email']);
                }

                if ($customer_info) {
                    $template->addData($customer_info, 'customer');
                }

                if (!empty($template->data['text_greeting'])) {
                    $template->data['text_greeting'] = sprintf($template->data['text_greeting'], $template->data['store_name']);
                }

                if (isset($template->data['text_ip'])) {
                    $template->data['text_ip'] = sprintf($template->data['text_ip'], $this->request->server['REMOTE_ADDR']);
                }

                $template->data['password_link'] = $this->url->link('account/reset', 'email=' . urlencode($args[0]) . '&code=' . $args[1]);

                if (!empty($template->data['button_password_link'])) {
                    $template->data['password_link_text'] = $template->data['button_password_link'];
                } else {
                    $template->data['password_link_text'] = $template->data['password_link'];
                }

                $template->data['account_login'] = $this->url->link('account/login');

                if (!empty($template->data['button_account_login'])) {
                    $template->data['account_login_text'] = $template->data['button_account_login'];
                } else {
                    $template->data['account_login_text'] = $template->data['account_login'];
                }
			    // Prepared mail: customer.forgotten
            }
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: customer.forgotten
			if ($template && $template->check()) {
			    $template->build();
			    $template->hook($mail);

                $mail->send();

                $this->model_extension_module_emailtemplate->sent();
            }]]></add>
	</operation>
    <operation error="skip">
        <search index="0"><![CDATA[$mail->setHtml($this->load->view('mail/forgotten', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/forgotten', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/forgotten', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/mail/register.php" email_template="customer.register">
    <operation>
        <search index="0"><![CDATA[public function index(]]></search>
        <ignoreif><![CDATA[if ($this->request->get['route'] == 'affiliate/register') {]]></ignoreif>
        <add position="after"><![CDATA[        if ($this->request->get['route'] == 'affiliate/register') {
            return null;
        }
        ]]></add>
    </operation>
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: customer.register
			$this->load->model('account/customer');
			$this->load->model('extension/module/emailtemplate');

			$this->load->language('extension/module/emailtemplate/customer');

			if (!empty($args[0]['customer_id'])) {
				$customer_info = $this->model_account_customer->getCustomer($args[0]['customer_id']);
			} else {
				$customer_info = $this->model_account_customer->getCustomerByEmail($args[0]['email']);
			}

			if (empty($customer_info)) {
                trigger_error('Unable to find customer by email: ' . $args[0]['email']);
                return false;
            }

			$template_load = array(
			    'key' => 'customer.register',
			    'customer_id' => $customer_info['customer_id'],
			    'customer_group_id' => $customer_info['customer_group_id'],
			    'language_id' => $customer_info['language_id'],
			    'store_id' => $customer_info['store_id']
            );

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                $template->addData($args[0]);

                $template->addData($customer_info, 'customer');

                $template->data['newsletter'] = $this->language->get((isset($args[0]['newsletter']) && $args[0]['newsletter'] == 1) ? 'text_yes' : 'text_no');

                $template->data['account_login'] = $this->url->link('account/login');

                if (!empty($template->data['button_account_login'])) {
                    $template->data['account_login_text'] = $template->data['button_account_login'];
                } else {
                    $template->data['account_login_text'] = $template->data['account_login'];
                }

                if (!empty($args[0]['custom_field'])) {
                    $this->load->model('account/custom_field');

                    $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                    foreach ($custom_fields as $custom_field) {
                        if (isset($args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                            $custom_field_key = 'custom_field_' . ($custom_field['location'] != 'account' ? $custom_field['location'] . '_' : '') . $custom_field['custom_field_id'];
                            $custom_field_value = $args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']];

                            $template->data[$custom_field_key . '_name'] = $custom_field['name'];
                            $template->data[$custom_field_key . '_value'] = '';

                            if ($custom_field['custom_field_value']) {
                                foreach ($custom_field['custom_field_value'] as $custom_field_value_info) {
                                    if (is_array($custom_field_value)) {
                                        if (in_array($custom_field_value_info['custom_field_value_id'], $custom_field_value)) {
                                            $template->data[$custom_field_key . '_value_' . $custom_field_value_info['custom_field_value_id']] = $custom_field_value_info['name'];
                                        }
                                    } else {
                                        if ($custom_field_value_info['custom_field_value_id'] == $custom_field_value) {
                                            $template->data[$custom_field_key . '_value'] = $custom_field_value_info['name'];
                                        }
                                    }
                                }
                            } else {
                                $template->data[$custom_field_key . '_value'] = $custom_field_value;
                            }
                        }
                    }
                }

                $template->data['customer_group'] = $customer_group_info['name'];

                if ($customer_group_info['approval']) {
                    $template->data['customer_text'] = $this->language->get('text_approval');
                } else {
                    $template->data['customer_text'] = $this->language->get('text_login');
                }

                if (!empty($customer_info['address_id'])) {
                    $this->load->model('account/address');

                    $address = $this->model_account_address->getAddress($customer_info['address_id']);

                    if ($address) {
                        $country = '';
                        $iso_code_2 = '';
                        $iso_code_3 = '';
                        $address_format = '';
                        $zone = '';
                        $zone_code = '';

                        if (!empty($address['country_id'])) {
                            $this->load->model('localisation/country');

                            $country_info = $this->model_localisation_country->getCountry($address['country_id']);

                            if ($country_info) {
                                $country = $country_info['name'];
                                $iso_code_2 = $country_info['iso_code_2'];
                                $iso_code_3 = $country_info['iso_code_3'];
                                $address_format = $country_info['address_format'];
                            }
                        }

                        if (!empty($address['zone_id'])) {
                            $this->load->model('localisation/zone');

                            $zone_info = $this->model_localisation_zone->getZone($address['zone_id']);

                            if ($zone_info) {
                                $zone = $zone_info['name'];
                                $zone_code = $zone_info['code'];
                            }
                        }

                        $address_data = array(
                            'address_id'     => $customer_info['address_id'],
                            'firstname'      => $address['firstname'],
                            'lastname'       => $address['lastname'],
                            'company'        => $address['company'],
                            'address_1'      => $address['address_1'],
                            'address_2'      => $address['address_2'],
                            'postcode'       => $address['postcode'],
                            'city'           => $address['city'],
                            'zone_id'        => $address['zone_id'],
                            'zone'           => $zone,
                            'zone_code'      => $zone_code,
                            'country_id'     => $address['country_id'],
                            'country'        => $country,
                            'iso_code_2'     => $iso_code_2,
                            'iso_code_3'     => $iso_code_3
                        );

                        $find = array();
                        $replace = array();

                        foreach(array_keys($address_data) as $key) {
                            $find[$key] = '{'.$key.'}';
                            $replace[$key] =  $address_data[$key];
                        }

                        if (isset($address['custom_field']) && is_array($address['custom_field'])) {
                            foreach ($address['custom_field'] as $custom_field_id => $custom_field) {
                                $find[] = '{custom_field_' . $custom_field_id . '}';
                                $replace[] = isset($custom_field['value']) ? $custom_field['value'] : '';
                            }
                        }

                        if (!$address_format) {
                            $address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                        }

                        $template->data['address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $address_format))));
                        $template->data['address_zone'] = $zone;
                        $template->data['address_country'] = $country;
                    }
                }
			    // Prepared mail: customer.register
			}
	]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: customer.register
			if ($template && $template->check()) {
			    $template->build();
			    $template->hook($mail);

                $mail->send();

                $this->model_extension_module_emailtemplate->sent();
            }]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/register', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/register', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/register', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/mail/register.php" email_template="customer.register_admin">
    <operation>
        <search index="0"><![CDATA[public function index(]]></search>
        <ignoreif><![CDATA[if ($this->request->get['route'] == 'affiliate/register') {]]></ignoreif>
        <add position="after"><![CDATA[        if ($this->request->get['route'] == 'affiliate/register') {
            return null;
        }
        ]]></add>
    </operation>
	<operation>
		<search index="1"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[		// Prepare mail: customer.register_admin
		$this->load->model('account/customer');
		$this->load->model('extension/module/emailtemplate');

		$this->load->language('extension/module/emailtemplate/customer');

		if (!empty($args[0]['customer_id'])) {
			$customer_info = $this->model_account_customer->getCustomer($args[0]['customer_id']);
		} else {
			$customer_info = $this->model_account_customer->getCustomerByEmail($args[0]['email']);
		}

		if (empty($customer_info)) {
            trigger_error('Unable to find customer by email: ' . $args[0]['email']);
            return false;
        }

		$template_load = array(
		    'key' => 'customer.register_admin',
            'customer_id' => $customer_info['customer_id'],
            'customer_group_id' => $customer_info['customer_group_id'],
            'language_id' => $customer_info['language_id'],
            'store_id' => $customer_info['store_id']
        );

		$template = $this->model_extension_module_emailtemplate->load($template_load);

        if ($template) {
            $template->addData($args[0]);

            $template->addData($customer_info, 'customer');

            $template->data['newsletter'] = $this->language->get((isset($args[0]['newsletter']) && $args[0]['newsletter'] == 1) ? 'text_yes' : 'text_no');

            if (!empty($args[0]['custom_field'])) {
                $this->load->model('account/custom_field');

                $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                foreach ($custom_fields as $custom_field) {
                    if (isset($args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                        $custom_field_key = 'custom_field_' . ($custom_field['location'] != 'account' ? $custom_field['location'] . '_' : '') . $custom_field['custom_field_id'];
                        $custom_field_value = $args[0]['custom_field'][$custom_field['location']][$custom_field['custom_field_id']];

                        $template->data[$custom_field_key . '_name'] = $custom_field['name'];
                        $template->data[$custom_field_key . '_value'] = '';

                        if ($custom_field['custom_field_value']) {
                            foreach ($custom_field['custom_field_value'] as $custom_field_value_info) {
                                if (is_array($custom_field_value)) {
                                    if (in_array($custom_field_value_info['custom_field_value_id'], $custom_field_value)) {
                                        $template->data[$custom_field_key . '_value_' . $custom_field_value_info['custom_field_value_id']] = $custom_field_value_info['name'];
                                    }
                                } else {
                                    if ($custom_field_value_info['custom_field_value_id'] == $custom_field_value) {
                                        $template->data[$custom_field_key . '_value'] = $custom_field_value_info['name'];
                                    }
                                }
                            }
                        } else {
                            $template->data[$custom_field_key . '_value'] = $custom_field_value;
                        }
                    }
                }
            }

            if (!empty($args[0]['address_1'])) {
                $country = '';
                $iso_code_2 = '';
                $iso_code_3 = '';
                $address_format = '';
                $zone = '';
                $zone_code = '';

                if (!empty($args[0]['country_id'])) {
                    $this->load->model('localisation/country');

                    $country_info = $this->model_localisation_country->getCountry($args[0]['country_id']);

                    if ($country_info) {
                        $country = $country_info['name'];
                        $iso_code_2 = $country_info['iso_code_2'];
                        $iso_code_3 = $country_info['iso_code_3'];
                        $address_format = $country_info['address_format'];
                    }
                }

                if (!empty($args[0]['zone_id'])) {
                    $this->load->model('localisation/zone');

                    $zone_info = $this->model_localisation_zone->getZone($args[0]['zone_id']);

                    if ($zone_info) {
                        $zone = $zone_info['name'];
                        $zone_code = $zone_info['code'];
                    }
                }

                $address_data = array(
                    'firstname'      => $args[0]['firstname'],
                    'lastname'       => $args[0]['lastname'],
                    'company'        => $args[0]['company'],
                    'address_1'      => $args[0]['address_1'],
                    'address_2'      => $args[0]['address_2'],
                    'postcode'       => $args[0]['postcode'],
                    'city'           => $args[0]['city'],
                    'zone_id'        => $args[0]['zone_id'],
                    'zone'           => $zone,
                    'zone_code'      => $zone_code,
                    'country_id'     => $args[0]['country_id'],
                    'country'        => $country,
                    'iso_code_2'     => $iso_code_2,
                    'iso_code_3'     => $iso_code_3
                );

                $find = array();
                $replace = array();

                foreach(array_keys($address_data) as $key) {
                    $find[$key] = '{'.$key.'}';
                    $replace[$key] =  $address_data[$key];
                }

                if (isset($address['custom_field']) && is_array($address['custom_field'])) {
                    foreach ($address['custom_field'] as $custom_field_id => $custom_field) {
                        $find[] = '{custom_field_' . $custom_field_id . '}';
                        $replace[] = isset($custom_field['value']) ? $custom_field['value'] : '';
                    }
                }

                if (!$address_format) {
                    $address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                }

                $template->data['address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $address_format))));
                $template->data['address_zone'] = $zone;
                $template->data['address_country'] = $country;
            }

            if (!empty($customer_info['address_id'])) {
                $this->load->model('account/address');

                $address = $this->model_account_address->getAddress($customer_info['address_id']);

                if ($address) {
                    $country = '';
                    $iso_code_2 = '';
                    $iso_code_3 = '';
                    $address_format = '';
                    $zone = '';
                    $zone_code = '';

                    if (!empty($address['country_id'])) {
                        $this->load->model('localisation/country');

                        $country_info = $this->model_localisation_country->getCountry($address['country_id']);

                        if ($country_info) {
                            $country = $country_info['name'];
                            $iso_code_2 = $country_info['iso_code_2'];
                            $iso_code_3 = $country_info['iso_code_3'];
                            $address_format = $country_info['address_format'];
                        }
                    }

                    if (!empty($address['zone_id'])) {
                        $this->load->model('localisation/zone');

                        $zone_info = $this->model_localisation_zone->getZone($address['zone_id']);

                        if ($zone_info) {
                            $zone = $zone_info['name'];
                            $zone_code = $zone_info['code'];
                        }
                    }

                    $address_data = array(
                        'address_id'     => $customer_info['address_id'],
                        'firstname'      => $address['firstname'],
                        'lastname'       => $address['lastname'],
                        'company'        => $address['company'],
                        'address_1'      => $address['address_1'],
                        'address_2'      => $address['address_2'],
                        'postcode'       => $address['postcode'],
                        'city'           => $address['city'],
                        'zone_id'        => $address['zone_id'],
                        'zone'           => $zone,
                        'zone_code'      => $zone_code,
                        'country_id'     => $address['country_id'],
                        'country'        => $country,
                        'iso_code_2'     => $iso_code_2,
                        'iso_code_3'     => $iso_code_3
                    );

                    $find = array();
                    $replace = array();

                    foreach(array_keys($address_data) as $key) {
                        $find[$key] = '{'.$key.'}';
                        $replace[$key] =  $address_data[$key];
                    }

                    if (isset($address['custom_field']) && is_array($address['custom_field'])) {
                        foreach ($address['custom_field'] as $custom_field_id => $custom_field) {
                            $find[] = '{custom_field_' . $custom_field_id . '}';
                            $replace[] = isset($custom_field['value']) ? $custom_field['value'] : '';
                        }
                    }

                    if (!$address_format) {
                        $address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                    }

                    $template->data['address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $address_format))));
                    $template->data['address_zone'] = $zone;
                    $template->data['address_country'] = $country;
                }
            }

            $template->data['customer_group'] = $customer_group_info['name'];

            if (defined('HTTP_ADMIN')) {
                $admin_url = HTTP_ADMIN;
            } elseif ($this->config->get('config_ssl')) {
                $admin_url = $this->config->get('config_ssl') . 'admin/';
            } else {
                $admin_url = $this->config->get('config_url') . 'admin/';
            }

            if ($customer_group_info['approval']) {
                $template->data['customer_link'] = $admin_url . 'index.php?route=customer/customer_approval&filter_email=' . $customer_info['email'];

                $template->data['text_register_subject_admin'] = $template->data['text_register_approve_subject_admin'];

                $template->data['text_admin_heading'] = $template->data['text_customer_approve'];

                $template->data['status'] = $this->language->get('text_admin_approve');
            } else {
                $template->data['customer_link'] = $admin_url . 'index.php?route=customer/customer/edit&customer_id=' . $customer_info['customer_id'];

                $template->data['text_register_subject_admin'] = $template->data['text_register_subject_admin'];

                $template->data['text_admin_heading'] = $template->data['text_new_customer'];

                $template->data['status'] = $this->language->get($customer_info['status'] ? 'text_enabled' : 'text_disabled');
            }

            $template->data['text_customer_link'] = $template->data['text_customer_link'];

            if (isset($template->data['button_customer_link']) && $template->data['button_customer_link'] != 'button_customer_link') {
                $template->data['customer_link_text'] =  $template->data['button_customer_link'];
            } else {
                $template->data['customer_link_text'] =  $template->data['customer_link'];
            }
		    // Prepared mail: customer.register_admin
		}
	]]></add>
	</operation>
	<operation>
		<search index="1"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: customer.register_admin
			if ($template && $template->check()) {
			    $template->build();
			    $template->fetch();
			    $template->hook($mail);
            }

			$mail->send();

			$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/register_alert', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/register_alert', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/register_alert', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/information/contact.php" email_template="information.contact">
  <operation>
    <search index="0"><![CDATA[$mail = new Mail(]]></search>
    <add position="before"><![CDATA[			// Prepare mail: information.contact
          $this->load->model('extension/module/emailtemplate');

          $template_load = array(
            'key' => 'information.contact',
            'email' => $this->request->post['email']
          );

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
				//$template->addData($this->request->post);

				$template->data['name'] = html_entity_decode($this->request->post['name'], ENT_QUOTES, 'UTF-8');

				$template->data['email'] = $this->request->post['email'];

				if (!empty($this->request->post['enquiry'])) {
				  $template->data['enquiry'] = html_entity_decode(str_replace("\n", "<br />", $this->request->post['enquiry']), ENT_QUOTES, 'UTF-8');
				}

				if (isset($template->data['text_ip'])) {
                    $template->data['text_ip'] = sprintf($template->data['text_ip'], $this->request->server['REMOTE_ADDR']);
                }

				if (!empty($customer_info)) {
				  $template->data['customer'] = $customer_info;
				}

				if (defined('HTTP_ADMIN')) {
					$admin_url = HTTP_ADMIN;
				} else {
					$admin_url = HTTPS_SERVER . 'admin/';
				}

				if (!empty($customer_info['customer_id'])) {
				  $template->data['admin_customer_url'] = $admin_url . 'index.php?route=customer/customer/edit&customer_id=' . $customer_info['customer_id'];
				}
                // Prepared mail: information.contact
    ]]></add>
  </operation>
  <operation>
    <search index="0"><![CDATA[$mail->send();]]></search>
    <add position="replace"><![CDATA[// Send mail: information.contact
			    if ($template && $template->check()) {
			      $mail->setReplyTo($template->data['email'], $template->data['name']);

			      $template->build();
			      $template->hook($mail);

                  $mail->send();

                  $this->model_extension_module_emailtemplate->sent();
                }
            }]]></add>
  </operation>
</file>

	<file path="catalog/controller/information/contact.php" email_template="information.contact_customer">
	<operation>
		<search index="0"><![CDATA[$this->response->redirect($this->url->link('information/contact/success']]></search>
		<add position="before"><![CDATA[			// Prepare mail: information.contact_customer
			$this->load->model('extension/module/emailtemplate');

			$template_load = array(
			    'key' => 'information.contact_customer',
			    'email' => $this->request->post['email']
            );

			$template = $this->model_extension_module_emailtemplate->load($template_load);

			if ($template) {
				//$template->addData($this->request->post);

				$template->data['name'] = html_entity_decode($this->request->post['name'], ENT_QUOTES, 'UTF-8');

				$template->data['email'] = $this->request->post['email'];

				if (!empty($this->request->post['enquiry'])) {
					$template->data['enquiry'] = html_entity_decode(str_replace("\n", "<br />", $this->request->post['enquiry']), ENT_QUOTES, 'UTF-8');
				}

				if (!empty($customer_info)) {
					$template->data['customer'] = $customer_info;
				}
				// Prepared mail: information.contact_customer

				// Send mail: information.contact_customer
                if ($template && $template->check()) {
                	$template->build();
                	$template->hook($mail);

					$mail->send();

					$this->model_extension_module_emailtemplate->sent();
				}
			}
		]]></add>
	</operation>
</file>

	<file path="catalog/controller/journal3/form.php" error="skip">
    <operation>
        <search index="0"><![CDATA[$params = array(]]></search>
        <add position="after"><![CDATA[					'emailtemplate_key' => 'journal.form.' . $this->module_id,
					'email_data' => $email_data,]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA[$this->load->controller('journal3/mail/send', $params);]]></search>
        <add position="after"><![CDATA[
				// Admin mail
				$admin_template_key = 'journal.form_admin.' . $this->module_id;
				$admin_template = $this->model_extension_module_emailtemplate->load($admin_template_key);

				if ($admin_template) {
					$params['emailtemplate_key'] = $admin_template_key;
					
					$this->load->controller('journal3/mail/send', $params);
				}]]></add>
    </operation>
</file>

<file path="catalog/controller/journal3/mail.php" error="skip">
<operation>
    <search index="0"><![CDATA[$mail->setTo(]]></search>
    <ignoreif><![CDATA[$this->load->model('extension/module/emailtemplate');]]></ignoreif>
    <add position="before"><![CDATA[        if (!empty($data['emailtemplate_key'])) {
            $this->load->model('extension/module/emailtemplate');

            $template = $this->model_extension_module_emailtemplate->load($data['emailtemplate_key']);

            if (!$template) {
                // Remove key .index
                $emailtemplate_key = preg_replace('/.[0-9]*$/', '', $data['emailtemplate_key']);

                if ($emailtemplate_key && $emailtemplate_key != $data['emailtemplate_key']) {
                    $template = $this->model_extension_module_emailtemplate->load($emailtemplate_key);
                }
            }

            if ($template) {
                if (isset($data['email_data'])) {
                    $template->addData($data['email_data']);
                } else {
                    $template->addData($data);
                }
            }
        }
        ]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[$mail->send();]]></search>
    <ignoreif><![CDATA[$this->model_extension_module_emailtemplate->sent();]]></ignoreif>
    <add position="replace"><![CDATA[
        if (!empty($data['emailtemplate_key']) && $template) {
    			$template->hook($mail);
    		}

        $mail->send();

        if (!empty($data['emailtemplate_key']) && $template) {
            $this->model_extension_module_emailtemplate->sent();
        }
        ]]></add>
</operation>
</file>

	<file path="catalog/controller/journal3/newsletter.php" error="skip">
    <operation>
        <search index="0"><![CDATA[$this->load->controller('journal3/mail/send', array(]]></search>
        <add position="after"><![CDATA[					'emailtemplate_key' => 'journal.newsletter.' . $this->module_id,
    'subscribed' => 1,]]></add>
    </operation>
    <operation>
        <search index="1"><![CDATA[$this->load->controller('journal3/mail/send', array(]]></search>
        <add position="after"><![CDATA[					'emailtemplate_key' => 'journal.newsletter_admin.' . $this->module_id,
    'subscribed' => 1,]]></add>
    </operation>
    <operation>
        <search index="2"><![CDATA[$this->load->controller('journal3/mail/send', array(]]></search>
        <add position="after"><![CDATA[					'emailtemplate_key' => 'journal.newsletter.' . $this->module_id,
    'subscribed' => 0,]]></add>
    </operation>
    <operation>
        <search index="3"><![CDATA[$this->load->controller('journal3/mail/send', array(]]></search>
        <add position="after"><![CDATA[					'emailtemplate_key' => 'journal.newsletter_admin.' . $this->module_id,
    'subscribed' => 0,]]></add>
    </operation>
</file>

<file path="catalog/controller/journal3/mail.php" error="skip">
<operation>
    <search index="0"><![CDATA[$mail->setTo(]]></search>
    <ignoreif><![CDATA[$this->load->model('extension/module/emailtemplate');]]></ignoreif>
    <add position="before"><![CDATA[        if (!empty($data['emailtemplate_key'])) {
            $this->load->model('extension/module/emailtemplate');

            $template = $this->model_extension_module_emailtemplate->load($data['emailtemplate_key']);

            if (!$template) {
                // Remove key .index
                $emailtemplate_key = preg_replace('/.[0-9]*$/', '', $data['emailtemplate_key']);

                if ($emailtemplate_key && $emailtemplate_key != $data['emailtemplate_key']) {
                    $template = $this->model_extension_module_emailtemplate->load($emailtemplate_key);
                }
            }

            if ($template) {
                $template->addData($data);
            }
        }
        ]]></add>
</operation>
<operation>
    <search index="0"><![CDATA[$mail->send();]]></search>
    <ignoreif><![CDATA[$this->model_extension_module_emailtemplate->sent();]]></ignoreif>
    <add position="replace"><![CDATA[
        if (!empty($data['emailtemplate_key']) && $template) {
            $template->hook($mail);
        }

        $mail->send();

        if (!empty($data['emailtemplate_key']) && $template) {
            $this->model_extension_module_emailtemplate->sent();
        }
        ]]></add>
</operation>
</file>

	<file path="catalog/controller/mail/order.php" email_template="order.admin">
    <operation>
        <search index="1"><![CDATA[$data['products'][] = array(]]></search>
        <add position="after"><![CDATA[				'product_id'  => $order_product['product_id'],
				'order_product_id'  => $order_product['order_product_id'],]]></add>
    </operation>
    <operation>
        <search index="1"><![CDATA['name'  => $order_option['name'],]]></search>
        <add position="before"><![CDATA[					'order_option_id'  => $order_option['order_option_id'],]]></add>
    </operation>
    <operation>
		<search index="2"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
			// Prepare mail: order.admin
			$this->load->language('product/product'); // required for stock status
			$this->load->language('mail/order_alert');
			$this->load->language('extension/module/emailtemplate/order');

			$this->load->model('tool/image');
            $this->load->model('catalog/product');
            $this->load->model('extension/module/emailtemplate');

			$template_load = array(
				'key' => 'order.admin',
				'customer_id' => $order_info['customer_id'],
				'customer_group_id' => $order_info['customer_group_id'],
				'language_id' => $order_info['language_id'],
				'order_status_id' => $order_status_id,
				'store_id' => $order_info['store_id'],
                'payment_method' => $order_info['payment_code'],
                'shipping_method' => $order_info['shipping_code']
			);

			$template_filter = array();

			if (!empty($order_info['customer_id']) && !isset($total_customer_orders)) {
				$total_customer_orders_query = $this->db->query("SELECT count(1) as total FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$order_info['customer_id'] . "'");

				if ($total_customer_orders_query->row) {
					$total_customer_orders = $total_customer_orders_query->row['total'];

					$template_filter['total_customer_orders'] = $total_customer_orders;
				}
			}

			$template = $this->model_extension_module_emailtemplate->load($template_load, $template_filter);

            if ($template) {
                $template->addData($order_info);

                if (!empty($data)) $template->addData($data);

                $template->data['total_customer_orders'] = isset($total_customer_orders) ? $total_customer_orders : 0;

                $template->data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));

                $template->data['date_modified'] = date($this->language->get('date_format_short'), strtotime($order_info['date_modified']));

                if ($order_info['invoice_no']) {
                    $template->data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
                } else {
                    $template->data['invoice_no'] = '';
                }

                // Address
                foreach(array('payment', 'shipping') as $var) {
                    if ($order_info[$var . '_address_format']) {
                        $format = $order_info[$var . '_address_format'];
                    } else {
                        $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                    }

                    $find = array(
                        '{firstname}',
                        '{lastname}',
                        '{company}',
                        '{address_1}',
                        '{address_2}',
                        '{city}',
                        '{postcode}',
                        '{zone}',
                        '{zone_code}',
                        '{country}'
                    );

                    $replace = array(
                        'firstname' => $order_info[$var . '_firstname'],
                        'lastname'  => $order_info[$var . '_lastname'],
                        'company'   => $order_info[$var . '_company'],
                        'address_1' => $order_info[$var . '_address_1'],
                        'address_2' => $order_info[$var . '_address_2'],
                        'city'      => $order_info[$var . '_city'],
                        'postcode'  => $order_info[$var . '_postcode'],
                        'zone'      => $order_info[$var . '_zone'],
                        'zone_code' => $order_info[$var . '_zone_code'],
                        'country'   => $order_info[$var . '_country']
                    );

                    if (isset($order_info['custom_field'])) {
                        foreach ($order_info['custom_field'] as $custom_field_id => $custom_field) {
                            $find[] = '{custom_field_' . $custom_field_id . '}';
                            $replace[] = isset($custom_field['value']) ? $custom_field['value'] : '';
                        }
                    }

                    if (isset($order_info[$var . '_custom_field'])) {
                        foreach ($order_info[$var . '_custom_field'] as $custom_field_id => $custom_field) {
                            $find[] = '{custom_field_' . $custom_field_id . '}';
                            $replace[] = isset($custom_field['value']) ? $custom_field['value'] : $custom_field;
                        }
                    }

                    $template->data[$var . '_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
                }

                if (!empty($order_info['customer_group_id'])) {
                    $this->load->model('account/customer_group');

                    $customer_group = $this->model_account_customer_group->getCustomerGroup($order_info['customer_group_id']);

                    $template->data['customer_group'] = array(
                        'name' => $customer_group['name'],
                        'description' => $customer_group['description']
                    );
                }

                if (!empty($order_info['affiliate_id']) && file_exists(DIR_APPLICATION . 'model/account/affiliate.php')) {
                    $this->load->model('account/affiliate');

                    $affiliate_info = $this->model_account_affiliate->getAffiliate($order_info['affiliate_id']);

                    if ($affiliate_info) {
                        $template->data['affiliate'] = $affiliate_info;
                    }
                }

                // Custom fields
                if (!empty($order_info['custom_field']) || !empty($order_info['payment_custom_field'])) {
                    $this->load->model('account/custom_field');

                    // Cleanup
					foreach(array('custom_field', 'payment_custom_field', 'shipping_custom_field') as $var) {
						if (isset($template->data[$var])) {
							unset($template->data[$var]);
						}
					}

                    if (!empty($order_info['customer_group_id'])) {
                        $customer_group_id = $order_info['customer_group_id'];
                    } else {
                        $customer_group_id = $this->config->get('config_customer_group_id');
                    }

                    $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                    foreach ($custom_fields as $custom_field) {
                        if (isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_name'] = $custom_field['name'];

                            if ($custom_field['custom_field_value']) {
                                foreach ($custom_field['custom_field_value'] as $custom_field_value) {
                                    if (is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                                        if (in_array($custom_field_value['custom_field_value_id'], $order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value_' . $custom_field_value['custom_field_value_id']] = $custom_field_value['name'];
                                        }
                                    } else {
                                        if ($custom_field_value['custom_field_value_id'] == $order_info['payment_custom_field'][$custom_field['custom_field_id']]) {
                                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $custom_field_value['name'];
                                        }
                                    }
                                }
                            } else {
                                $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $order_info['payment_custom_field'][$custom_field['custom_field_id']];
                            }
                        } elseif (isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_name'] = $custom_field['name'];

                            if ($custom_field['custom_field_value']) {
                                foreach ($custom_field['custom_field_value'] as $custom_field_value) {
                                    if (is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
                                        if (in_array($custom_field_value['custom_field_value_id'], $order_info['custom_field'][$custom_field['custom_field_id']])) {
                                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value_' . $custom_field_value['custom_field_value_id']] = $custom_field_value['name'];
                                        }
                                    } else {
                                        if ($custom_field_value['custom_field_value_id'] == $order_info['custom_field'][$custom_field['custom_field_id']]) {
                                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $custom_field_value['name'];
                                        }
                                    }
                                }
                            } else {
                                $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $order_info['custom_field'][$custom_field['custom_field_id']];
                            }
                        }
                    }
                }

                $order_status_query = $this->db->query("SELECT `name` FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int)$order_status_id . "' AND language_id = '" . (int)$order_info['language_id'] . "' LIMIT 1");

                if ($order_status_query->row) {
                    $order_status = $order_status_query->row['name'];

                    $template->data['order_status'] = $order_status;
                }

                    if ($this->config->get('config_processing_status') && in_array($order_status_id, $this->config->get('config_processing_status'))) {
                        $template->data['order_processing_status'] = true;
                    } elseif ($this->config->get('config_complete_status') && in_array($order_status_id, $this->config->get('config_complete_status'))) {
                        $template->data['order_complete_status'] = true;
                    }

                $template->data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));

                if (defined('HTTP_ADMIN')) {
                    $admin_url = HTTP_ADMIN;
                } elseif (!empty($order_info['store_ssl'])) {
                    $admin_url = $order_info['store_ssl'] . 'admin/';
                } else {
                    $admin_url = $order_info['store_url'] . 'admin/';
                }

                $template->data['admin_order_link'] = $admin_url . 'index.php?route=sale/order/info&order_id=' . $order_info['order_id'];

                if ($this->language->get('button_order_link') && $this->language->get('button_order_link') != 'button_order_link') {
                    $template->data['admin_order_link_text'] =  $this->language->get('button_order_link');
                } else {
                    $template->data['admin_order_link_text'] =  $template->data['admin_order_link'];
                }

                if (!empty($order_info['weight'])) {
                    $template->data['order_weight'] = $this->weight->format($order_info['weight'], $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
                }

                $template->data['order_comment'] = nl2br($order_info['comment']);

                if ($order_info['comment'] != $comment) {
                    $template->data['comment'] = nl2br($order_info['comment']);

                    $template->data['instruction'] = nl2br($comment);
                } else {
                    $template->data['comment'] = nl2br($comment);

                    $template->data['instruction'] = '';
                }

                $template->data['order_total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

                $products_stock = array();

                if (!empty($template->data['config']['order_products']['option_length'])) {
                    $option_length = $template->data['config']['order_products']['option_length'];
                } else {
                    $option_length = 120;
                }

                // Add extra data to products array
                $template->data['products'] = $data['products'];

                foreach ($template->data['products'] as $i => $product) {
                    $order_product = false;
                    foreach ($order_products as $row) {
                        if ($product['order_product_id'] == $row['order_product_id']) {
                            $order_product = $row;
                            break;
                        }
                    }

                    $product_data = $this->model_catalog_product->getProduct($order_product['product_id']);

                    if ($product_data) {
                        if ($product['option']) {
                            $order_options = $this->model_checkout_order->getOrderOptions($order_info['order_id'], $order_product['order_product_id']);

                            foreach ($product['option'] as $ii => $product_option) {
                                $order_option = false;
                                foreach ($order_options as $order_option) {
                                    if ($order_option['order_option_id'] == $product_option['order_option_id']) {
                                        break;
                                    }
                                }

                                if ($order_option && $order_option['type'] != 'file') {
                                    $value = $order_option['value'];
                                    $template->data['products'][$i]['option'][$ii]['value'] = utf8_strlen($value) > $option_length ? utf8_substr($value, 0, $option_length) . '..' : $value;
                                }
                            }

                            $product_data['option_value'] = array();

                            $order_option_query = $this->db->query("SELECT oo.* FROM " . DB_PREFIX . "order_option oo WHERE oo.order_product_id = '" . (int)$product['order_product_id'] . "' AND oo.order_id = '" . (int)$order_info['order_id'] . "'");

                            if ($order_option_query->rows) {
                                foreach ($order_option_query->rows as $order_option) {
                                    $order_option_value_query = $this->db->query("SELECT pov.*, ov.image FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) WHERE pov.product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "'");

                                    if ($order_option_value_query->rows) {
                                        foreach ($order_option_value_query->rows as $order_option_value) {
                                            $product_data['option_value'][] = array(
                                                'order_option_id' => $order_option['order_option_id'],
                                                'product_option_value_id' => $order_option['product_option_value_id'],
                                                'type' => $order_option['type'],
                                                'image' => $order_option_value['image'],
                                                'price' => $order_option_value['price'],
                                                'price_prefix' => $order_option_value['price_prefix'],
                                                'stock_quantity' => $order_option_value['quantity'],
                                                'value' => $order_option['value']
                                            );
                                        }
                                    }
                                }
                            }
                        }

                        $image = '';

                        if (!empty($template->data['config']['order_products']['image'])) {
                            $image = $product_data['image'];

                            if (!empty($product_data['option_value']) && !empty($template->data['config']['order_products']['option_image'])) {
                                foreach($product_data['option_value'] as $product_option_value) {
                                    if ($product_option_value['image']) {
                                        $image = $product_option_value['image'];
                                        break;
                                    }
                                }
                            }

                            if ($image) {
                                $image_width = isset($template->data['config']['order_products']['image_width']) ? $template->data['config']['order_products']['image_width']: 100;
                                $image_height = isset($template->data['config']['order_products']['image_height']) ? $template->data['config']['order_products']['image_height']: 100;

                                if ($image_width && $image_height) {
                                    $image = $this->model_tool_image->resize($image, $image_width, $image_height);
                                    if (substr($image, 0, 4) != 'http') {
                                        $image = $order_info['store_url'] . ltrim($image, '/');
                                    }
                                }
                            }
                        }

                        $url = $this->url->link('product/product', 'product_id='.$order_product['product_id']);

                        if (!empty($template->data['config']['order_products']['admin_stock'])) {
                            if (!isset($products_stock[$order_product['product_id']]['stock_quantity'])) {
                                $products_stock[$order_product['product_id']]['stock_quantity'] = (int)$product_data['quantity'];
                            }

                            if ($product_data['subtract']) {
                                $products_stock[$order_product['product_id']]['stock_quantity'] -= (int)$product['quantity'];
                            }
                        }

                        if (!empty($product_data['option_value']) && $template->data['products'][$i]['option']) {
                            foreach ($product_data['option_value'] as $product_option_value) {
                                if ($product_option_value['stock_quantity']) {
                                    foreach($template->data['products'][$i]['option'] as $ii => $product_option) {
                                        if ($product_option_value['order_option_id'] == $product_option['order_option_id']) {
                                            if ($product_option_value['type'] != 'file') {
                                                $value = $product_option_value['value'];
                                            } else {
                                                $value = utf8_substr($product_option_value['value'], 0, utf8_strrpos($product_option_value['value'], '.'));
                                            }

                                            $template->data['products'][$i]['option'][$ii] = array_merge($template->data['products'][$i]['option'][$ii], array(
                                                'value' => utf8_strlen($value) > $option_length ? utf8_substr($value, 0, $option_length) . '..' : $value,
                                                'price' => (float)$product_option_value['price'] ? $this->currency->format($this->tax->calculate($product_option_value['price'], $product_data['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']) : 0,
                                                'price_value' => (float)$product_option_value['price'],
                                                'price_prefix' => isset($product_option_value['price_prefix']) ? $product_option_value['price_prefix'] : '',
                                                'stock_quantity' => isset($product_option_value['quantity']) ? ((int)$product_option_value['quantity'] - (int)$product['quantity']) : '',
                                                'stock_subtract' => isset($product_option_value['subtract']) ? $product_option_value['subtract'] : ''
                                            ));

                                            break 2;
                                        }
                                    }
                                }
                            }
                        }

                        if ($product_data['quantity'] <= 0) {
                            $stock_status = $product_data['stock_status'];
                        } elseif ($this->config->get('config_stock_display')) {
                            $stock_status = $product_data['quantity'];
                        } else {
                            $stock_status = $this->language->get('text_instock');
                        }

                        $template->data['products'][$i] = array_merge($template->data['products'][$i], array(
                            'product_id' => $product_data['product_id'],
                            'url' => $url,
                            'image' => !empty($image) ? $image : '',
                            'weight' => ($product_data['weight'] > 0) ? $this->weight->format($product_data['weight'], $product_data['weight_class_id']) : 0,
                            'price'    => $this->currency->format($order_product['price'] + ($this->config->get('config_tax') ? $order_product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
                            'manufacturer' => $product_data['manufacturer'],
                            'stock_status' => $stock_status
                        ));

                        if (!empty($template->data['config']['order_products']['model'])) {
                            $template->data['products'][$i]['model'] = $product_data['model'];
                        } elseif (isset($template->data['products'][$i]['model'])) {
                            unset($template->data['products'][$i]['model']);
                        }

                        if (!empty($template->data['config']['order_products']['sku'])) {
                            $template->data['products'][$i]['sku'] = $product_data['sku'];
                        } elseif (isset($template->data['products'][$i]['sku'])) {
                            unset($template->data['products'][$i]['sku']);
                        }

                        if (!empty($template->data['config']['order_products']['description']) && $product_data['description']) {
                            $template->data['products'][$i]['description'] = utf8_substr(strip_tags(html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8')), 0, 200) . '..';
                        }
                    }
                }

                // Products Stock
                if (!empty($template->data['config']['order_products']['admin_stock'])) {
                    foreach ($template->data['products'] as $i => $product) {
                        if (isset($products_stock[$product['product_id']]['stock_quantity'])) {
                            $template->data['products'][$i]['stock_quantity'] = $products_stock[$product['product_id']]['stock_quantity'];
                        }
                    }
                }

                // Vouchers
                $template->data['vouchers'] = array();

                $order_vouchers = $this->model_checkout_order->getOrderVouchers($order_info['order_id']);

                foreach ($order_vouchers as $order_voucher) {
                    $template->data['vouchers'][] = array(
                        'description' => $order_voucher['description'],
                        'amount'      => $this->currency->format($order_voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
                    );
                }

                // Order Totals
                $template->data['totals'] = array();

                $order_totals = $this->model_checkout_order->getOrderTotals($order_info['order_id']);

                foreach ($order_totals as $order_total) {
                    $template->data['totals'][] = array(
                        'title' => $order_total['title'],
                        'text'  => $this->currency->format($order_total['value'], $order_info['currency_code'], $order_info['currency_value']),
                    );
                }

                $template->data['order_subject_products'] = '';

                if (!empty($template->data['products'])) {
                    foreach ($template->data['products'] as $order_product) {
                        if (strpos($template->data['order_subject_products'], $order_product['name']) === false) {
                            $template->data['order_subject_products'] .= ($template->data['order_subject_products'] ? ', ' : '') . strip_tags($order_product['name']);
                        }
                    }
                }

                if (!empty($template->data['vouchers'])) {
                    foreach ($template->data['vouchers'] as $order_voucher) {
                        if (strpos($template->data['order_subject_products'], $order_voucher['description']) === false) {
                            $template->data['order_subject_products'] .= ($template->data['order_subject_products'] ? ', ' : '') . strip_tags($order_voucher['description']);
                        }
                    }
                }

                if ($template->data['order_subject_products']) {
                    $template->data['order_subject_products'] = trim(html_entity_decode($template->data['order_subject_products'], ENT_QUOTES, 'UTF-8'));

                    $length = 32;

                    if (strlen($template->data['order_subject_products']) > $length) {
                        $template->data['order_subject_products'] = substr($template->data['order_subject_products'], 0, strrpos(substr($template->data['order_subject_products'], 0, $length), ' ')) . '...';
                    }
                }
			    // Prepared mail: order.admin
            }
		]]></add>
	</operation>
	<operation>
		<search index="2"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: order.admin
			if ($template && $template->check()) {
			    $template->build();
			    $template->hook($mail);
            }

			$mail->send();

			$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/order_alert', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/order_alert', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/order_alert', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/mail/order.php" email_template="order.customer">
    <operation>
        <search index="0"><![CDATA[$data['products'][] = array(]]></search>
        <add position="after"><![CDATA[				'product_id'  => $order_product['product_id'],
				'order_product_id'  => $order_product['order_product_id'],]]></add>
    </operation>
    <operation>
        <search index="0"><![CDATA['name'  => $order_option['name'],]]></search>
        <add position="before"><![CDATA[					'order_option_id'  => $order_option['order_option_id'],]]></add>
    </operation>
    <operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[
		// Prepare mail: order.customer
		$language->load('product/product'); // required for stock status
		$language->load('extension/module/emailtemplate/order');

		$this->load->model('tool/image');
		$this->load->model('catalog/product');
		$this->load->model('extension/module/emailtemplate');

		$template_load = array(
			'key' => 'order.customer',
			'customer_id' => $order_info['customer_id'],
            'customer_group_id' => $order_info['customer_group_id'],
            'language_id' => $order_info['language_id'],
            'order_status_id' => $order_status_id,
            'store_id' => $order_info['store_id'],
            'payment_method' => $order_info['payment_code'],
            'shipping_method' => $order_info['shipping_code']
		);

		$template_filter = array();

		if (!empty($order_info['customer_id']) && !isset($total_customer_orders)) {
			$total_customer_orders_query = $this->db->query("SELECT count(1) as total FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$order_info['customer_id'] . "'");

			if ($total_customer_orders_query->row) {
				$total_customer_orders = $total_customer_orders_query->row['total'];
				$template_filter['total_customer_orders'] = $total_customer_orders;
			}
		}

		$template = $this->model_extension_module_emailtemplate->load($template_load, $template_filter);

        if ($template) {
            $template->addData($order_info);

            if (!empty($data)) $template->addData($data);

            if (!empty($order_info['customer_group_id'])) {
                $this->load->model('account/customer_group');

                $customer_group = $this->model_account_customer_group->getCustomerGroup($order_info['customer_group_id']);

                $template->data['customer_group'] = array(
                    'name' => $customer_group['name'],
                    'description' => $customer_group['description']
                );
            }

            if (!empty($order_info['affiliate_id']) && file_exists(DIR_APPLICATION . 'model/account/affiliate.php')) {
                $this->load->model('account/affiliate');

                $affiliate_info = $this->model_account_affiliate->getAffiliate($order_info['affiliate_id']);

                if ($affiliate_info) {
                    $template->data['affiliate'] = $affiliate_info;
                }
            }

            // Custom fields
            if (!empty($order_info['custom_field']) || !empty($order_info['payment_custom_field'])) {
                $this->load->model('account/custom_field');

                // Cleanup
                foreach(array('custom_field', 'payment_custom_field', 'shipping_custom_field') as $var) {
                    if (isset($template->data[$var])) {
                        unset($template->data[$var]);
                    }
                }

                if (!empty($order_info['customer_group_id'])) {
                    $customer_group_id = $order_info['customer_group_id'];
                } else {
                    $customer_group_id = $this->config->get('config_customer_group_id');
                }

                $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                foreach ($custom_fields as $custom_field) {
                    if (isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_name'] = $custom_field['name'];

                        if ($custom_field['custom_field_value']) {
                            foreach ($custom_field['custom_field_value'] as $custom_field_value) {
                                if (is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                                    if (in_array($custom_field_value['custom_field_value_id'], $order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value_' . $custom_field_value['custom_field_value_id']] = $custom_field_value['name'];
                                    }
                                } else {
                                    if ($custom_field_value['custom_field_value_id'] == $order_info['payment_custom_field'][$custom_field['custom_field_id']]) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $custom_field_value['name'];
                                    }
                                }
                            }
                        } else {
                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $order_info['payment_custom_field'][$custom_field['custom_field_id']];
                        }
                    } elseif (isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_name'] = $custom_field['name'];

                        if ($custom_field['custom_field_value']) {
                            foreach ($custom_field['custom_field_value'] as $custom_field_value) {
                                if (is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
                                    if (in_array($custom_field_value['custom_field_value_id'], $order_info['custom_field'][$custom_field['custom_field_id']])) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value_' . $custom_field_value['custom_field_value_id']] = $custom_field_value['name'];
                                    }
                                } else {
                                    if ($custom_field_value['custom_field_value_id'] == $order_info['custom_field'][$custom_field['custom_field_id']]) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $custom_field_value['name'];
                                    }
                                }
                            }
                        } else {
                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $order_info['custom_field'][$custom_field['custom_field_id']];
                        }
                    }
                }
            }

            // Address
            foreach(array('payment', 'shipping') as $var) {
                if ($order_info[$var . '_address_format']) {
                    $format = $order_info[$var . '_address_format'];
                } else {
                    $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                }

                $find = array(
                    '{firstname}',
                    '{lastname}',
                    '{company}',
                    '{address_1}',
                    '{address_2}',
                    '{city}',
                    '{postcode}',
                    '{zone}',
                    '{zone_code}',
                    '{country}'
                );

                $replace = array(
                    'firstname' => $order_info[$var . '_firstname'],
                    'lastname'  => $order_info[$var . '_lastname'],
                    'company'   => $order_info[$var . '_company'],
                    'address_1' => $order_info[$var . '_address_1'],
                    'address_2' => $order_info[$var . '_address_2'],
                    'city'      => $order_info[$var . '_city'],
                    'postcode'  => $order_info[$var . '_postcode'],
                    'zone'      => $order_info[$var . '_zone'],
                    'zone_code' => $order_info[$var . '_zone_code'],
                    'country'   => $order_info[$var . '_country']
                );

                if (isset($order_info['custom_field'])) {
                    foreach ($order_info['custom_field'] as $custom_field_id => $custom_field) {
                        $find[] = '{custom_field_' . $custom_field_id . '}';
                        $replace[] = isset($custom_field['value']) ? $custom_field['value'] : '';
                    }
                }

                if (isset($order_info[$var . '_custom_field'])) {
                    foreach ($order_info[$var . '_custom_field'] as $custom_field_id => $custom_field) {
                        $find[] = '{custom_field_' . $custom_field_id . '}';
                        $replace[] = isset($custom_field['value']) ? $custom_field['value'] : $custom_field;
                    }
                }

                $template->data[$var . '_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
            }

            $order_status_query = $this->db->query("SELECT `name` FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int)$order_status_id . "' AND language_id = '" . (int)$order_info['language_id'] . "' LIMIT 1");

            if ($order_status_query->row) {
                $order_status = $order_status_query->row['name'];

                $template->data['order_status'] = $order_status;
            }

            if ($this->config->get('config_processing_status') && in_array($order_status_id, $this->config->get('config_processing_status'))) {
                $template->data['order_processing_status'] = true;
            } elseif ($this->config->get('config_complete_status') && in_array($order_status_id, $this->config->get('config_complete_status'))) {
                $template->data['order_complete_status'] = true;
            }

            $template->data['total_customer_orders'] = isset($total_customer_orders) ? $total_customer_orders : 0;

            $products_stock = array();

            if (!empty($template->data['config']['order_products']['option_length'])) {
                $option_length = $template->data['config']['order_products']['option_length'];
            } else {
                $option_length = 120;
            }

            // Add extra data to products array
            $template->data['products'] = $data['products'];

            foreach ($template->data['products'] as $i => $product) {
                $order_product = false;
                foreach ($order_products as $row) {
                    if ($product['order_product_id'] == $row['order_product_id']) {
                        $order_product = $row;
                        break;
                    }
                }

                $product_data = $this->model_catalog_product->getProduct($order_product['product_id']);

                if ($product_data) {
                    if ($product['option']) {
                        $order_options = $this->model_checkout_order->getOrderOptions($order_info['order_id'], $order_product['order_product_id']);

                        foreach ($product['option'] as $ii => $product_option) {
                            $order_option = false;
                            foreach ($order_options as $order_option) {
                                if ($order_option['order_option_id'] == $product_option['order_option_id']) {
                                    break;
                                }
                            }

                            if ($order_option && $order_option['type'] != 'file') {
                                $value = $order_option['value'];
                                $template->data['products'][$i]['option'][$ii]['value'] = utf8_strlen($value) > $option_length ? utf8_substr($value, 0, $option_length) . '..' : $value;
                            }
                        }

                        $product_data['option_value'] = array();

                        $order_option_query = $this->db->query("SELECT oo.* FROM " . DB_PREFIX . "order_option oo WHERE oo.order_product_id = '" . (int)$product['order_product_id'] . "' AND oo.order_id = '" . (int)$order_info['order_id'] . "'");

                        if ($order_option_query->rows) {
                            foreach ($order_option_query->rows as $order_option) {
                                $order_option_value_query = $this->db->query("SELECT pov.*, ov.image FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) WHERE pov.product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "'");

                                if ($order_option_value_query->rows) {
                                    foreach ($order_option_value_query->rows as $order_option_value) {
                                        $product_data['option_value'][] = array(
                                            'order_option_id' => $order_option['order_option_id'],
                                            'product_option_value_id' => $order_option['product_option_value_id'],
                                            'type' => $order_option['type'],
                                            'image' => $order_option_value['image'],
                                            'price' => $order_option_value['price'],
                                            'price_prefix' => $order_option_value['price_prefix'],
                                            //'stock_quantity' => $order_option_value['quantity'],
                                            'value' => $order_option['value']
                                        );
                                    }
                                }
                            }
                        }
                    }

                    $image = '';

                    if (!empty($template->data['config']['order_products']['image'])) {
                        $image = $product_data['image'];

                        if (!empty($product_data['option_value']) && !empty($template->data['config']['order_products']['option_image'])) {
                            foreach($product_data['option_value'] as $product_option_value) {
                                if ($product_option_value['image']) {
                                    $image = $product_option_value['image'];
                                    break;
                                }
                            }
                        }

                        if ($image) {
                            $image_width = isset($template->data['config']['order_products']['image_width']) ? $template->data['config']['order_products']['image_width']: 100;
                            $image_height = isset($template->data['config']['order_products']['image_height']) ? $template->data['config']['order_products']['image_height']: 100;

                            if ($image_width && $image_height) {
                                $image = $this->model_tool_image->resize($image, $image_width, $image_height);
                                if (substr($image, 0, 4) != 'http') {
                                    $image = $order_info['store_url'] . ltrim($image, '/');
                                }
                            }
                        }
                    }

                    $url = $this->url->link('product/product', 'product_id='.$order_product['product_id']);

                    // Products Stock
                    /*if (!isset($products_stock[$order_product['product_id']]['stock_quantity'])) {
                        $products_stock[$order_product['product_id']]['stock_quantity'] = (int)$product_data['quantity'];
                    }

                    if ($product_data['subtract']) {
                        $products_stock[$order_product['product_id']]['stock_quantity'] -= (int)$product['quantity'];
                    }*/

                    if ($product_data['quantity'] <= 0) {
                        $stock_status = $product_data['stock_status'];
                    } elseif ($this->config->get('config_stock_display')) {
                        $stock_status = $product_data['quantity'];
                    } else {
                        $stock_status = $this->language->get('text_instock');
                    }

                    $template->data['products'][$i] = array_merge($template->data['products'][$i], array(
                        'url' => $url,
                        'image' => !empty($image) ? $image : '',
                        'weight' => ($product_data['weight'] > 0) ? $this->weight->format($product_data['weight'], $product_data['weight_class_id']) : 0,
                        'manufacturer' => $product_data['manufacturer'],
                        'stock_status' => $stock_status
                    ));

                    if (!empty($template->data['config']['order_products']['description']) && $product_data['description']) {
                        $template->data['products'][$i]['description'] = utf8_substr(strip_tags(html_entity_decode($product_data['description'], ENT_QUOTES, 'UTF-8')), 0, 200) . '..';
                    }

                    if (!empty($template->data['config']['order_products']['model'])) {
                        $template->data['products'][$i]['model'] = $product_data['model'];
                    } elseif (isset($template->data['products'][$i]['model'])) {
                        unset($template->data['products'][$i]['model']);
                    }

                    if (!empty($template->data['config']['order_products']['sku'])) {
                        $template->data['products'][$i]['sku'] = $product_data['sku'];
                    } elseif (isset($template->data['products'][$i]['sku'])) {
                        unset($template->data['products'][$i]['sku']);
                    }

                    if (!empty($template->data['config']['order_products']['rating'])) {
                        $template->data['products'][$i]['rating'] = $product_data['rating'];
                        $template->data['products'][$i]['reviews'] = $product_data['reviews'];
                    }
                }
            }

            // Products Stock
            /*foreach ($template->data['products'] as $i => $product) {
                if (isset($products_stock[$product['product_id']]['stock_quantity'])) {
                    $template->data['products'][$i]['stock_quantity'] = $products_stock[$product['product_id']]['stock_quantity'];
                }
            }*/

            $template->data['order_comment'] = nl2br($order_info['comment']);

            if ($order_info['comment'] != $comment) {
                $template->data['comment'] = nl2br($order_info['comment']);

                $template->data['instruction'] = nl2br($comment);
            } else {
                $template->data['comment'] = nl2br($comment);

                $template->data['instruction'] = '';
            }

            $template->data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));

            $template->data['date_modified'] = date($this->language->get('date_format_short'), strtotime($order_info['date_modified']));

            if ($order_info['invoice_no']) {
                $template->data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
            } else {
                $template->data['invoice_no'] = '';
            }

            $template->data['order_total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

            $template->data['order_subject_products'] = '';

            if (!empty($template->data['products'])) {
                foreach ($template->data['products'] as $order_product) {
                    if (strpos($template->data['order_subject_products'], $order_product['name']) === false) {
                        $template->data['order_subject_products'] .= ($template->data['order_subject_products'] ? ', ' : '') . strip_tags($order_product['name']);
                    }
                }
            }

            if (!empty($template->data['vouchers'])) {
                foreach ($template->data['vouchers'] as $order_voucher) {
                    if (strpos($template->data['order_subject_products'], $order_voucher['description']) === false) {
                        $template->data['order_subject_products'] .= ($template->data['order_subject_products'] ? ', ' : '') . strip_tags($order_voucher['description']);
                    }
                }
            }

            if ($template->data['order_subject_products']) {
                $template->data['order_subject_products'] = trim(html_entity_decode($template->data['order_subject_products'], ENT_QUOTES, 'UTF-8'));

                $length = 32;

                if (strlen($template->data['order_subject_products']) > $length) {
                    $template->data['order_subject_products'] = substr($template->data['order_subject_products'], 0, strrpos(substr($template->data['order_subject_products'], 0, $length), ' ')) . '...';
                }
            }

            if ($order_info['customer_id']) {
                $template->data['order_link'] = $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_info['order_id'];

                if ($this->language->get('button_order_link') && $this->language->get('button_order_link') != 'button_order_link') {
                    $template->data['order_link_text'] = $this->language->get('button_order_link');
                } else {
                    $template->data['order_link_text'] = $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_info['order_id'];
                }
            }

            if ($download_status) {
                $template->data['download_link'] = $order_info['store_url'] . 'index.php?route=account/download';

                if ($this->language->get('button_download_link') && $this->language->get('button_download_link') != 'button_download_link') {
                    $template->data['download_link_text'] = $this->language->get('button_download_link');
                } else {
                    $template->data['download_link_text'] = $template->data['download_link'];
                }
            }
		    // Prepared mail: order.customer
		}
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[
		// Send mail: order.customer
		if ($template && $template->check()) {
		    $template->build();
		    $template->hook($mail);
        }

		$mail->send();

		$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/order_add', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/order_add', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/order_add', $data));]]></add>
    </operation>
</file>

	<file path="catalog/controller/mail/order.php" email_template="order.update">
	<operation>
		<search index="1"><![CDATA[$mail = new Mail(]]></search>
		<add position="after"><![CDATA[
		// Prepare mail: order.update
		$this->load->model('extension/module/emailtemplate');

		$language->load('extension/module/emailtemplate/order');

		$template_load = array(
			'key' => 'order.update',
			'customer_id' => $order_info['customer_id'],
            'customer_group_id' => $order_info['customer_group_id'],
            'language_id' => $order_info['language_id'],
            'order_status_id' => $order_status_id,
            'store_id' => $order_info['store_id'],
            'payment_method' => $order_info['payment_code'],
            'shipping_method' => $order_info['shipping_code']
		);

		if (!empty($this->request->post['emailtemplate_id'])) {
			$template_load['emailtemplate_id'] = $this->request->post['emailtemplate_id'];
		}

		$template_filter = array();

		if (!empty($order_info['customer_id']) && !isset($total_customer_orders)) {
			$total_customer_orders_query = $this->db->query("SELECT count(1) as total FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$order_info['customer_id'] . "'");

			if ($total_customer_orders_query->row) {
				$total_customer_orders = $total_customer_orders_query->row['total'];
				$template_filter['total_customer_orders'] = $total_customer_orders;
			}
		}

		$template = $this->model_extension_module_emailtemplate->load($template_load, $template_filter);

        if ($template) {
            $template->addData($order_info);

            if (!empty($data)) $template->addData($data);

            if (!empty($order_info['customer_group_id'])) {
                $this->load->model('account/customer_group');

                $customer_group = $this->model_account_customer_group->getCustomerGroup($order_info['customer_group_id']);

                $template->data['customer_group'] = array(
                    'name' => $customer_group['name'],
                    'description' => $customer_group['description']
                );
            }

            if (!empty($order_info['affiliate_id']) && file_exists(DIR_APPLICATION . 'model/account/affiliate.php')) {
                $this->load->model('account/affiliate');

                $template->data['affiliate'] = $this->model_account_affiliate->getAffiliate($order_info['affiliate_id']);
            }

            $template->data['order_status'] = $data['order_status'];

            $template->data['order_status_id'] = $order_status_id;

            $template->data['total_customer_orders'] = isset($total_customer_orders) ? $total_customer_orders : 0;

            $template->data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));

            $template->data['date_modified'] = date($this->language->get('date_format_short'), strtotime($order_info['date_modified']));

            $template->data['date_relative_hours'] = floor((time() - strtotime($order_info['date_added'])) / 3600);

            if ($order_info['invoice_no']) {
                $template->data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
            } else {
                $template->data['invoice_no'] = '';
            }

            if ($order_info['order_status_id'] != $order_status_id){
                $template->data['prev_order_status_id'] = $order_info['order_status_id'];
            }

            $template->data['order_total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

            $comment = html_entity_decode($comment, ENT_QUOTES, 'UTF-8');

            $template->data['comment'] = (trim(strip_tags($comment)) != '') ? $comment : '';

            if ($order_info['comment']) {
                $template->data['order_comment'] = nl2br($order_info['comment']);
            }

            if ($order_info['comment'] != $comment) {
                $template->data['instruction'] = nl2br($comment);
            } else {
                $template->data['instruction'] = '';
            }

            if ($order_info['customer_id']) {
                $template->data['order_link'] = $order_info['store_url'] . 'index.php?route=account/order/info&order_id=' . $order_info['order_id'];

                if (!empty($template->data['button_order_link'])) {
                    $template->data['order_link_text'] = $template->data['button_order_link'];
                } else {
                    $template->data['order_link_text'] = $template->data['order_link'];
                }
            }

            // Custom fields
            if (!empty($order_info['custom_field']) || !empty($order_info['payment_custom_field'])) {
                $this->load->model('account/custom_field');

				// Cleanup
				foreach(array('custom_field', 'payment_custom_field', 'shipping_custom_field') as $var) {
					if (isset($template->data[$var])) {
						unset($template->data[$var]);
					}
				}

                if (!empty($order_info['customer_group_id'])) {
                    $customer_group_id = $order_info['customer_group_id'];
                } else {
                    $customer_group_id = $this->config->get('config_customer_group_id');
                }

                $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

                foreach ($custom_fields as $custom_field) {
                    if (isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_name'] = $custom_field['name'];

                        if ($custom_field['custom_field_value']) {
                            foreach ($custom_field['custom_field_value'] as $custom_field_value) {
                                if (is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                                    if (in_array($custom_field_value['custom_field_value_id'], $order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value_' . $custom_field_value['custom_field_value_id']] = $custom_field_value['name'];
                                    }
                                } else {
                                    if ($custom_field_value['custom_field_value_id'] == $order_info['payment_custom_field'][$custom_field['custom_field_id']]) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $custom_field_value['name'];
                                    }
                                }
                            }
                        } else {
                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $order_info['payment_custom_field'][$custom_field['custom_field_id']];
                        }
                    } elseif (isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_name'] = $custom_field['name'];

                        if ($custom_field['custom_field_value']) {
                            foreach ($custom_field['custom_field_value'] as $custom_field_value) {
                                if (is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
                                    if (in_array($custom_field_value['custom_field_value_id'], $order_info['custom_field'][$custom_field['custom_field_id']])) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value_' . $custom_field_value['custom_field_value_id']] = $custom_field_value['name'];
                                    }
                                } else {
                                    if ($custom_field_value['custom_field_value_id'] == $order_info['custom_field'][$custom_field['custom_field_id']]) {
                                        $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $custom_field_value['name'];
                                    }
                                }
                            }
                        } else {
                            $template->data['custom_field_' . $custom_field['custom_field_id'] . '_value'] = $order_info['custom_field'][$custom_field['custom_field_id']];
                        }
                    }
                }
            }

			// Address
            foreach(array('payment', 'shipping') as $var) {
                if ($order_info[$var . '_address_format']) {
                    $format = $order_info[$var . '_address_format'];
                } else {
                    $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
                }

                $find = array(
                    '{firstname}',
                    '{lastname}',
                    '{company}',
                    '{address_1}',
                    '{address_2}',
                    '{city}',
                    '{postcode}',
                    '{zone}',
                    '{zone_code}',
                    '{country}'
                );

                $replace = array(
                    'firstname' => $order_info[$var . '_firstname'],
                    'lastname'  => $order_info[$var . '_lastname'],
                    'company'   => $order_info[$var . '_company'],
                    'address_1' => $order_info[$var . '_address_1'],
                    'address_2' => $order_info[$var . '_address_2'],
                    'city'      => $order_info[$var . '_city'],
                    'postcode'  => $order_info[$var . '_postcode'],
                    'zone'      => $order_info[$var . '_zone'],
                    'zone_code' => $order_info[$var . '_zone_code'],
                    'country'   => $order_info[$var . '_country']
                );

                if (isset($order_info['custom_field'])) {
                    foreach ($order_info['custom_field'] as $custom_field_id => $custom_field) {
                        $find[] = '{custom_field_' . $custom_field_id . '}';
                        $replace[] = isset($custom_field['value']) ? $custom_field['value'] : '';
                    }
                }

                if (isset($order_info[$var . '_custom_field'])) {
                    foreach ($order_info[$var . '_custom_field'] as $custom_field_id => $custom_field) {
                        $find[] = '{custom_field_' . $custom_field_id . '}';
                        $replace[] = isset($custom_field['value']) ? $custom_field['value'] : $custom_field;
                    }
                }

                $template->data[$var . '_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
            }

		    // Prepared mail: order.update
        }
		]]></add>
	</operation>
	<operation>
		<search index="1"><![CDATA[$mail->send();]]></search>
        <ignoreif><![CDATA[// Send mail: order.update]]></ignoreif>
		<add position="replace"><![CDATA[// Send mail: order.update
		if ($template && $template->check()) {
		    $template->build();
		    $template->hook($mail);
        }

		$mail->send();

		$this->model_extension_module_emailtemplate->sent();]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[$mail->setHtml($this->load->view('mail/order_edit', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/order_edit', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/order_edit', $data));]]></add>
    </operation>
</file>

<file path="admin/controller/sale/order.php" email_template="order.update">
	<operation>
		<search index="0"><![CDATA[$data['text_ip_add'] = ]]></search>
		<add position="before"><![CDATA[
		$this->load->language('extension/module/emailtemplate/order');

		$data['user_token'] = $this->session->data['user_token'];

		$data['entry_template'] = $this->language->get('entry_template');
		$data['entry_order_summary'] = $this->language->get('entry_order_summary');

		$data['text_select'] = $this->language->get('text_select');

		$data['warning_template_content'] = $this->language->get('warning_template_content');

		$data['language_id'] = $order_info['language_id'];
		$data['store_id'] = $order_info['store_id'];

		$this->load->model('localisation/language');
		$this->load->model('extension/module/emailtemplate');

		$templates = $this->model_extension_module_emailtemplate->getTemplates(array(
			'emailtemplate_key' => 'order.update',
			'sort' => 'default',
			'order' => 'ASC'
		));

		$data['template_options'] = array();

		// Select most appropriate template matching most conditions
			$keys = array(
			'store_id' => $order_info['store_id'],
			'language_id' => $order_info['language_id'],
			'customer_group_id' => $order_info['customer_group_id'],
			'order_status_id' => $order_info['order_status_id'],
			'payment_method' => $order_info['payment_code'],
			'shipping_method' => $order_info['shipping_code'],
		);

		// Give all templates a 'power'
		$i = 0;
		foreach ($templates as $template) {
			$i++;
			$data['template_options'][$i] = array(
				'value' => $template['emailtemplate_id'],
				'label' => $template['emailtemplate_label'] . (!empty($template['emailtemplate_default']) ? ' (' . strip_tags($this->language->get('text_default')) . ')': ''),
				'order_status_id' => $template['order_status_id'],
				'selected' => false,
				'power' => 0,
			);

			foreach ($keys as $_key => $_value) {
				$data['template_options'][$i]['power'] = $data['template_options'][$i]['power'] << 1;

				if (isset($template[$_key]) && $template[$_key] !== '' && $template[$_key] == $_value) {
					$data['template_options'][$i]['power'] += 1;
				}
			}
		}

		// Select template with max 'power'
		if (count($data['template_options']) > 1) {
			$templates_option_power = 0;

			foreach ($data['template_options'] as $i => $templates_option) {
				if ($templates_option['power'] > $templates_option_power) {
					$templates_option_selected = $i;
				}
				unset($data['template_options'][$i]['power']);
			}

			if (isset($templates_option_selected)) {
				$data['template_options'][$templates_option_selected]['selected'] = true;
			}
		}

		$this->document->addScript('view/javascript/summernote/summernote.js');
		$this->document->addScript('view/javascript/summernote/opencart.js');
		$this->document->addStyle('view/javascript/summernote/summernote.css');
]]></add>
	</operation>
	<operation error="skip">
		<search><![CDATA[nl2br($result['comment'])]]></search>
		<add position="replace"><![CDATA[html_entity_decode($result['comment'], ENT_QUOTES, 'UTF-8')]]></add>
	</operation>
    <operation error="skip">
        <search><![CDATA[nl2br($order_info['comment'])]]></search>
        <add position="replace"><![CDATA[html_entity_decode($order_info['comment'], ENT_QUOTES, 'UTF-8')]]></add>
    </operation>
	<operation>
		<search><![CDATA[$data['vouchers'][] = array(]]></search>
		<add position="after"><![CDATA[					'voucher_id'  => $voucher['voucher_id'],]]></add>
	</operation>
</file>

<file path="admin/view/template/sale/order_info.twig" email_template="order.update">
    <operation>
        <search index="0"><![CDATA[id="input-comment" class="form-control]]></search>
        <add position="replace"><![CDATA[data-toggle="summernote" id="input-comment" class="form-control summernote]]></add>
    </operation>
	<operation>
		<search index="0"><![CDATA[id="input-notify"]]></search>
		<add position="after"><![CDATA[                    </div>
                  </div>
                </div>
                <div class="form-group form-group-notify" style="display:none">
                  <label class="col-sm-2 control-label" for="input-templates">{{ entry_template }}</label>
                  <div class="col-sm-10">
                    <select id="input-templates" name="emailtemplate_id" class="form-control">
                      <option value="">{{ text_select }}</option>
                      {% for item in template_options %}
                        <option value="{{ item.value }}" data-order-status="{{ item.order_status_id }}"{{ (item.selected or template_options|length == 1) ? ' selected="selected"' }}>{{ item.label }}</option>
                      {% endfor %}
                    </select>
                  </div>
                </div>

                <div class="form-group form-group-notify" style="display:none">
                  <label class="col-sm-2 control-label" for="input-order-summary">{{ entry_order_summary }}</label>
                  <div class="col-sm-10">
                      <div class="btn-group btn-group-toggle" data-toggle="buttons">
                        <label class="btn btn-default">
                          <input type="radio" name="order_summary" value="1"> {{ text_yes }}
                        </label>
                        <label class="btn btn-default">
                          <input type="radio" name="order_summary" value="0"> {{ text_no }}
                        </label>
                      </div>

                      <div class="form-group-order-summary" style="display:none">
                        <hr />
                        {% for product in products %}
                        <div class="checkbox"><label>
                            <input type="checkbox" name="order_summary_products[]" value="{{ product.product_id }}" checked="checked" />
                            {{ product.name }}
                            {% for option in product.option %}
                            <br />
                            {% if option.type != 'file' %}
                            &nbsp;<small> - {{ option.name }}: {{ option.value }}</small>
                            {% else %}
                            &nbsp;<small> - {{ option.name }}: <a href="{{ option.href }}">{{ option.value }}</a></small>
                            {% endif %}
                            {% endfor %}
                          </label></div>
                        {% endfor %}
                        {% for voucher in vouchers %}
                        <div class="checkbox"><label>
                            <input type="checkbox" name="order_summary_vouchers[]" value="{{ voucher.voucher_id }}" checked="checked" />
                            {{ voucher.description }}
                          </label>
                        </div>
                        {% endfor %}
                      ]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$('#button-history').on('click', function() {]]></search>
		<add position="after"><![CDATA[  if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
  	  if (CKEDITOR.instances["input-comment"]) {
		  CKEDITOR.instances["input-comment"].updateElement();
	  } else {
		  CKEDITOR.instances["comment"].updateElement();
	  }
  }

  if ($("textarea[name='comment']").val().replace(/(<([^>]+)>)/ig,"") == '') {
    $("textarea[name='comment']").val('');
  }]]></add>
	</operation>
	<operation>
		<search><![CDATA['&comment=' +]]></search>
		<add position="replace"><![CDATA[($('input[name=\'order_summary\']:checked').length ? ('&order_summary=' + $('input[name=\'order_summary\']:checked').val()) : '') + ('&order_summary_products=' + $('input[name=\'order_summary_products[]\']:checked').map(function() { return $(this).val(); }).toArray()) + ('&order_summary_vouchers=' + $('input[name=\'order_summary_vouchers[]\']:checked').map(function() { return $(this).val(); }).toArray()) + '&emailtemplate_id=' + encodeURIComponent($('select[name=\'emailtemplate_id\']').val()) + '&comment=' +]]></add>
	</operation>
	<operation>
		<search><![CDATA[$('textarea[name=\'comment\']').val('');]]></search>
		<add position="after"><![CDATA[
			if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
			  if (CKEDITOR.instances["input-comment"]) {
				  CKEDITOR.instances["input-comment"].setData('');
			  } else {
				  CKEDITOR.instances["comment"].setData('');
			  }
	        } else if ($.fn.summernote) {
				$('textarea[name=\'comment\']').summernote('reset');
			}

			$('input[name=notify]').prop('checked', false).parent().removeClass('active');
			$('input[name=notify][value="0"]').parent().addClass('active');

			$('.form-group-notify').hide().each(function(){
              $(this).find('input[type=radio][value!="0"]').prop('checked', false).parent().removeClass('active');
			  $(this).find('input[type=radio][value="0"]').prop('checked', true).change().parent().addClass('active');
			});
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[{{ footer }}]]></search>
		<add position="before"><![CDATA[
<script type="text/javascript"><!--
(function($){
  $(document).ready(function(){
    var $comment = $('textarea[name=comment]');

    function fetchTemplateComment(id, callback) {
    	if (!id) return false;

		if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
			var editorName = CKEDITOR.instances["input-comment"] ? 'input-comment' : 'comment';
			CKEDITOR.instances[editorName].setData('');
			CKEDITOR.instances[editorName].setReadOnly(true);
		} else if ($.fn.summernote) {
			$comment.summernote('code', '');
			$comment.summernote('disable');
		} else {
			$comment.val('');
		}

        $.ajax({
            url: 'index.php?route=extension/module/emailtemplate/fetch_template&output=comment&user_token={{ user_token }}',
            type: 'get',
            data: 'emailtemplate_id=' + id + '&store_id={{ store_id }}' + '&language_id={{ language_id }}' + '&order_id={{ order_id }}' + '&order_status_id=' + $('#input-order-status').val(),
            dataType: 'html',
            success: function(html) {
                if (html) {
                    $comment.val(html);

					if (typeof CKEDITOR !== "undefined" && (CKEDITOR.instances["input-comment"] || CKEDITOR.instances["comment"])) {
						var editorName = CKEDITOR.instances["input-comment"] ? 'input-comment' : 'comment';
						CKEDITOR.instances[editorName].setData(html);
						CKEDITOR.instances[editorName].setReadOnly(false);
					} else if ($.fn.summernote) {
						$comment.summernote('code', html);
						$comment.summernote('enable');
					}

                    if (callback) callback();
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        })
    }

    var $notify_group = $('.form-group-notify');
	var $notify_checkbox = $('#input-notify');
    var $order_status = $('#input-order-status');
    var $template_options = $('#input-templates');

    $notify_checkbox.on('change', function(){
      if ($notify_checkbox.is(':checked')) {
        $notify_group.show();

        if ($order_status.val()) {
          $order_status.trigger('change');
        }
      } else {
        $notify_group.hide();
      }
    });

    $order_status.on('change', function(){
      var $template_option = $template_options.find('option[data-order-status="' + $order_status.val() + '"]:eq(0)');
      // Select default template
      if ($template_option.length == 0) {
        $template_option = $template_options.find(':nth-child(2)');
      }

      var emailtemplate_id = $template_option.val()

      if ($notify_checkbox.is(':checked')) {
        fetchTemplateComment(emailtemplate_id, function () {
          $template_option.prop('selected', true);
        });
      } else {
        $template_options.val('');
      }
    });

    $('input[name=order_summary]').on('change', function(){
      $('.form-group-order-summary').toggle($(this).val() == 1 ? true : false);
    });

    $template_options.on('change', function() {
        var id = $(this).val();
        if (!id) {
          $comment.val('')
        } else {
          if ($comment.val() != '' && $comment.val() != '<p><br></p>' && !confirm("{{ warning_template_content }}")) {
            $(this).val($.data(this, 'current'));
            return false;
          }
          $.data(this, 'current', $(this).val());
          fetchTemplateComment(id);
        }
    });
  });
})(jQuery);
//--></script>]]></add>
	</operation>
</file>

	<file path="catalog/controller/extension/total/voucher.php" email_template="order.voucher">
	<operation>
	    <search index="0"><![CDATA[$data['message'] = ]]></search>
	    <add position="after"><![CDATA[
	    			// Prepare mail: order.voucher
					$this->load->model('extension/module/emailtemplate');

					$template_load = array(
					    'key' => 'order.voucher',
					    'customer_id' => $order_info['customer_id'],
					    'customer_group_id' => $order_info['customer_group_id'],
					    'language_id' => $order_info['language_id'],
					    'store_id' => $order_info['store_id'],
                        'payment_method' => $order_info['payment_code'],
                        'shipping_method' => $order_info['shipping_code']
                    );

					$template = $this->model_extension_module_emailtemplate->load($template_load);

                    if ($template) {
                        $template->addData($voucher);

                        $template_data = $data;
                        unset($template_data['store_name']);
                        unset($template_data['store_url']);
                        $template->addData($template_data);

                        $template->addData($order_info, 'order');

                        $template->data['store_id'] = $order_info['store_id'];

                        $template->data['language_id'] = $order_info['language_id'];

                        $template->data['amount'] = $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']);

                        $template->data['order_total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

                        if ($voucher['image'] && file_exists(DIR_IMAGE . $voucher['image'])) {
                            $template->data['image'] = $template->data['store_url'] . 'image/' . $voucher['image'];

                            list($template->data['image_width'], $template->data['image_height']) = getimagesize(DIR_IMAGE . $voucher['image']);
                        }

                        $template->data['text_heading'] = sprintf($template->data['text_heading'], $template->data['store_name']);
                        $template->data['text_subject'] = sprintf($template->data['text_subject'], $template->data['store_name']);

                        $template->data['voucher_url'] = $template->data['store_url'];

                        if (!empty($template->data['button_voucher_url'])) {
                            $template->data['voucher_url_text'] = $template->data['button_voucher_url'];
                        } else {
                            $template->data['voucher_url_text'] = $template->data['voucher_url'];
                        }
					    // Prepared mail: order.voucher
		]]></add>
	</operation>
	<operation>
	    <search index="0"><![CDATA[$mail->send();]]></search>
	    <add position="replace"><![CDATA[// Send mail: order.voucher
                        if ($template && $template->check()) {
                        	$template->build();
                        	$template->hook($mail);

                        	$mail->send();

                        	$this->model_extension_module_emailtemplate->sent();
						}
                    }]]></add>
	</operation>
    <operation error="skip">
        <search index="0"><![CDATA[$mail->setHtml($this->load->view('mail/voucher', $data));]]></search>
        <ignoreif><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/voucher', $data));]]></ignoreif>
        <add position="replace"><![CDATA[if (empty($template)) $mail->setHtml($this->load->view('mail/voucher', $data));]]></add>
    </operation>
</file>

	<file path="catalog/model/catalog/review.php" email_template="product.review">
	<operation>
		<search index="0"><![CDATA[$mail = new Mail(]]></search>
		<add position="before"><![CDATA[			// Prepare mail: product.review
			$this->load->model('extension/module/emailtemplate');

			$template_load = array('key' => 'product.review');

			$template = $this->model_extension_module_emailtemplate->load($template_load);

            if ($template) {
                $template->addData($data, 'review');

                $template->addData($product_info, 'product');

                if (defined('HTTP_ADMIN')) {
                    $admin_url = HTTP_ADMIN;
                } elseif ($this->config->get('config_ssl')) {
                    $admin_url = $this->config->get('config_ssl') . 'admin/';
                } else {
                    $admin_url = $this->config->get('config_url') . 'admin/';
                }

                $template->data['review_approve'] = $admin_url . 'index.php?route=catalog/review/edit&review_id=' . $review_id;

				if ($this->language->get('button_review_approve') && $this->language->get('button_review_approve') != 'button_review_approve') {
					$template->data['review_approve_text'] =  $this->language->get('button_review_approve');
				} else {
					$template->data['review_approve_text'] =  $template->data['review_approve'];
				}

                $template->data['customer_link'] = $admin_url . 'index.php?route=customer/customer/edit&filter_name=' . urlencode($data['name']);

                if ($this->language->get('button_customer_link') && $this->language->get('button_customer_link') != 'button_customer_link') {
                    $template->data['customer_link_text'] =  $this->language->get('button_customer_link');
                } else {
                    $template->data['customer_link_text'] =  $template->data['customer_link'];
                }

				$template->data['product_link'] = $this->url->link('product/product', 'product_id=' . $product_id);
			    // Prepared mail: product.review
		]]></add>
	</operation>
	<operation>
		<search index="0"><![CDATA[$mail->send();]]></search>
		<add position="replace"><![CDATA[// Send mail: product.review
			    if ($template && $template->check()) {
			    	$template->build();
			    	$template->hook($mail);

					if ($this->customer && $this->customer->isLogged()) {
						$mail->setReplyTo($this->customer->getEmail());
					}

					$mail->send();

					$this->model_extension_module_emailtemplate->sent();
                }
            }]]></add>
	</operation>
</file>

</modification>