<?php
require_once DIR_SYSTEM.'library/devmanextensions_poc/Httpful/autoload.php';
require_once DIR_SYSTEM.'library/devmanextensions_poc/PayPal/autoload.php';
use PayPal\Api\OpenIdUserinfo;

class ControllerExtensionModulePerfectOneCheckout extends Controller {

	 public function __construct($registry) {
		parent::__construct($registry);
		$loader = new Loader($registry);

        $loader->language('checkout/checkout');
        $loader->model('extension/module/perfect_one_checkout');
        $loader->model('account/address');

        $this->prefix_extension = version_compare(VERSION, '2.3.0.1', '>=') ? 'extension/' : '';
        $this->model_init = version_compare(VERSION, '2.3.0.1', '>=') ? 'model_extension' : 'model';

        if(version_compare(VERSION, '3.0.0.0', '>='))
        	$this->extension_template = "";
        else
        	$this->extension_template = ".tpl";

        if(version_compare(VERSION, '3.0.0.0', '>='))
        {
        	$loader->model('setting/extension');
        	$this->model_extension_name = 'model_setting_extension';
        }
        elseif(version_compare(VERSION, '2.0.0.0', '>='))
        {
        	$loader->model('extension/extension');
        	$this->model_extension_name = 'model_extension_extension';
        }
        else
        {
        	$loader->model('setting/extension');
        	$this->model_extension_name = 'model_setting_extension';
        }

        $this->language_id = $this->config->get('config_language_id');
        $this->more_oc_2 = version_compare(VERSION, '2.0.0.0', '>=');
        $this->is_oc_3 = version_compare(VERSION, '3.0.0.0', '>=');
        $this->new_login_functions = version_compare(VERSION, '2.0.0.0', '>');

       /* if(!isset($this->session->data['order_id']))
        	$this->session->data['order_id'] = '';*/
    }

	public function ajax_login() {
		$array_return = array('error' => false, 'message' => '', 'data' => array());

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

		// Check how many login attempts have been made.
		if($this->new_login_functions)
		{
			$login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']);

			if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
				$array_return['error'] = true;
				$array_return['message'] = $this->session->data['poc']['lang']['identification_error_attemps'];
			}
		}

		// Check if customer has been approved.
		$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);

		$account_dissaproved = array_key_exists('approved', $customer_info) && !$customer_info['approved'];
		$account_not_enabled = array_key_exists('status', $customer_info) && !$customer_info['status'];

		if (!empty($customer_info) && ($account_dissaproved || $account_not_enabled)){
			$array_return['error'] = true;
			$array_return['message'] = $this->language->get('error_approved');
		}

		if (!$array_return['error']) {
			if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
				$array_return['error'] = true;
				$array_return['message'] = $this->session->data['poc']['lang']['identification_error_login'];

				if($this->new_login_functions)
					$this->model_account_customer->addLoginAttempt($this->request->post['email']);
			} else {
				if($this->new_login_functions)
					$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
			}
		}

		echo json_encode($array_return); die;
	}

	public function ajax_register()
	{
		$this->language->load('account/register');
		$array_return = array('error' => false, 'message' => '', 'data' => array());

        $logged = $this->customer->isLogged();
        if($logged) {
            echo json_encode($array_return); die;
        }

		$this->request->post['name'] = !empty($this->request->post['name']) ? $this->request->post['name'] : '';
	    $this->request->post['lastname'] = !empty($this->request->post['lastname']) ? $this->request->post['lastname'] : '';
	    $this->request->post['email'] = !empty($this->request->post['email']) ? $this->request->post['email'] : '';
	    $this->request->post['telephone'] = !empty($this->request->post['telephone']) ? $this->request->post['telephone'] : '';
	    $this->request->post['fax'] = !empty($this->request->post['fax']) ? $this->request->post['fax'] : '';
	    $this->request->post['company'] = !empty($this->request->post['company']) ? $this->request->post['company'] : '';
	    $this->request->post['address_1'] = !empty($this->request->post['address_1']) ? $this->request->post['address_1'] : '';
	    $this->request->post['address_2'] = !empty($this->request->post['address_2']) ? $this->request->post['address_2'] : '';
	    $this->request->post['city'] = !empty($this->request->post['city']) ? $this->request->post['city'] : '';
	    $this->request->post['post_code'] = !empty($this->request->post['post_code']) ? $this->request->post['post_code'] : '';
	    $this->request->post['country_id'] = !empty($this->request->post['country_id']) ? $this->request->post['country_id'] : '';
	    $this->request->post['zone_id'] = !empty($this->request->post['zone_id']) ? $this->request->post['zone_id'] : '';
	    $this->request->post['password'] = !empty($this->request->post['password']) ? $this->request->post['password'] : '';
	    $this->request->post['confirm'] = !empty($this->request->post['confirm']) ? $this->request->post['confirm'] : '';
	    $this->request->post['newsletter'] = !empty($this->request->post['newsletter']) ? $this->request->post['newsletter'] : '';
	    $this->request->post['postcode'] = !empty($this->request->post['postcode']) ? $this->request->post['postcode'] : '';

		if(!$this->more_oc_2)
		{
			$this->request->post['company_id'] = !empty($this->request->post['company_id']) ? $this->request->post['company_id'] : '';
			$this->request->post['tax_id'] = !empty($this->request->post['tax_id']) ? $this->request->post['tax_id'] : '';
		}

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

		if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
			$array_return['error'] = true;
			$array_return['message'] = $this->language->get('error_exists');
		}

		$this->load->model('localisation/country');

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

		if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($this->request->post['postcode'])) < 2 || utf8_strlen(trim($this->request->post['postcode'])) > 10)) {
			$array_return['error'] = true;
			$array_return['message'] = $this->language->get('error_postcode');
		}

		if(!$array_return['error'])
		{
			$customer_group_id = array_key_exists('customer_group_id', $this->request->post) && !empty($this->request->post['customer_group_id']) ? $this->request->post['customer_group_id'] : $this->config->get('config_customer_group_id');
            $this->request->post['customer_group_id'] = $customer_group_id;
            $customer_id = $this->model_account_customer->addCustomer($this->request->post);
			if($this->is_oc_3)
			{
				$this->load->model('account/address');

				$address = array(
					'default' => true,
					'firstname' => !empty($this->request->post['firstname']) ? $this->request->post['firstname'] : '',
					'lastname' => !empty($this->request->post['lastname']) ? $this->request->post['lastname'] : '',
					'company' => !empty($this->request->post['company']) ? $this->request->post['company'] : '',
					'address_1' => !empty($this->request->post['address_1']) ? $this->request->post['address_1'] : '',
					'address_2' => !empty($this->request->post['address_2']) ? $this->request->post['address_2'] : '',
					'city' => !empty($this->request->post['city']) ? $this->request->post['city'] : '',
					'postcode' => !empty($this->request->post['postcode']) ? $this->request->post['postcode'] : '',
					'country_id' => !empty($this->request->post['country_id']) ? $this->request->post['country_id'] : '',
					'zone_id' => !empty($this->request->post['zone_id']) ? $this->request->post['zone_id'] : ''
				);

				if(!empty($this->request->post['custom_field']))
					$address['custom_field'] = $this->request->post['custom_field'];

				$this->model_account_address->addAddress($customer_id, $address);
			}


			// Clear any previous login attempts for unregistered accounts.
			if($this->more_oc_2)
				$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);

			$this->session->data['account'] = 'register';

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

			$customer_group_info = $this->model_account_customer_group->getCustomerGroup($customer_group_id);

			if ($customer_group_info && !$customer_group_info['approval']) {
				$this->customer->login($this->request->post['email'], $this->request->post['password']);

				$this->session->data['poc_registered'] = true;
                unset($this->session->data['poc']['register']);
				// Default Payment Address
				$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());

				if (!empty($this->request->post['shipping_address'])) {
					$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());

					if(!$this->more_oc_2)
						$this->session->data['shipping_address_id'] = $this->customer->getAddressId();
				}
			} else {
				$array_return['redirect'] = $this->url->link('account/success');
			}

			if($this->config->get('poc_modals_in_forms')) {
                unset($this->session->data['guest']);
                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);
            }

			// Add to activity log
			if ($this->config->get('config_customer_activity')) {
				$this->load->model('account/activity');

				$activity_data = array(
					'customer_id' => $customer_id,
					'name'        => $this->request->post['firstname'] . ' ' . $this->request->post['lastname']
				);

				$this->model_account_activity->addActivity('register', $activity_data);
			}
		}
		echo json_encode($array_return); die;
	}

	public function ajax_new_address()
	{
		$array_return = array('error' => false, 'message' => '', 'data' => array());

		$data = array(
			'firstname' => !empty($this->request->post['firstname']) ? $this->request->post['firstname'] : '',
			'lastname' => !empty($this->request->post['lastname']) ? $this->request->post['lastname'] : '',
			'company' => !empty($this->request->post['company']) ? $this->request->post['company'] : '',
			'address_1' => !empty($this->request->post['address_1']) ? $this->request->post['address_1'] : '',
			'address_2' => !empty($this->request->post['address_2']) ? $this->request->post['address_2'] : '',
			'postcode' => !empty($this->request->post['postcode']) ? $this->request->post['postcode'] : '',
			'city' => !empty($this->request->post['city']) ? $this->request->post['city'] : '',
			'zone_id' => !empty($this->request->post['zone_id']) ? $this->request->post['zone_id'] : '',
			'country_id' => !empty($this->request->post['country_id']) ? $this->request->post['country_id'] : '',
		);

		if(!$this->more_oc_2)
		{
			$data['company_id'] = !empty($this->request->post['company_id']) ? $this->request->post['company_id'] : '';
			$data['tax_id'] = !empty($this->request->post['tax_id']) ? $this->request->post['tax_id'] : '';
		}

		//Devman Extensions - info@devmanextensions.com - 2017-07-22 14:44:18 - Custom fields
			if(array_key_exists('custom_field', $this->request->post) && !empty($this->request->post['custom_field']['address']))
				$data['custom_field'] = $this->request->post['custom_field']['address'];
		//END

		if(!$this->is_oc_3)
			$address_id = $this->model_account_address->addAddress($data);
		else
			$address_id = $this->model_account_address->addAddress($this->customer->getId(), $data);

		if(empty($address_id))
		{
			$array_return['error'] = true;
			$array_return['message'] = 'Internal error';
		}

		echo json_encode($array_return); die;
	}

	public function ajax_set_terms_accepted()
	{
		$this->session->data['poc']['terms_accepted'] = $this->request->post['checked'] == 'false' ? false : true;
		echo json_encode(array('Terms accepted to: '.$this->request->post['checked'])); die;
	}

	public function ajax_set_guest()
	{
		$this->session->data['poc']['guest'] = true;
        $this->session->data['poc']['register'] = false;
		echo json_encode(array('Guest activated')); die;
	}

    public function ajax_set_register()
    {
        $this->session->data['poc']['register'] = true;
        $this->session->data['poc']['guest'] = false;
        echo json_encode(array('Register activated'));
        die;
    }

	public function ajax_set_address()
	{
		$select_name = $this->request->post['select_name'];
		$address_id = !empty($this->request->post['address_id']) ? $this->request->post['address_id'] : '';
		$address_info = !empty($address_id) ? $this->model_account_address->getAddress($address_id) : array();

		$this->session->data['poc'][$select_name] = $address_id;
		$this->session->data[$select_name] = $address_info;

		if(!$this->more_oc_2)
			$this->session->data[$select_name.'_id'] = $address_id;

		echo json_encode(array('Address '.$select_name.' set')); die;
	}

	public function ajax_set_address_guest($die_json_encode = true)
	{
	    $die_json_encode = is_array($die_json_encode) || $die_json_encode;

		$logged = $this->customer->isLogged();
		$same_address = !empty($this->session->data['poc']['same_address']);

		$address_type = $this->request->post['address_type'];

		unset($this->request->post['address_type']);

		//Devman Extensions - info@devmanextensions.com - 2017-04-29 15:24:41 - If not isset field define these!
			$payment_address_fields = array('firstname', 'lastname','company','address_1','address_2','city','postcode','zone','zone_id','country','country_id','address_format','custom_field','email', 'telephone', 'fax');

			if(!$this->more_oc_2)
			{
				array_push($payment_address_fields, 'company_id');
				array_push($payment_address_fields, 'tax_id');
			}

			$shipping_address_fields = array('firstname', 'lastname','company','address_1','address_2','city','postcode','zone','zone_id','country','country_id','address_format','custom_field','email', 'telephone', 'fax');

			foreach (${$address_type.'_fields'} as $key => $field_name) {
				if(!isset($this->request->post[$field_name]))
					$this->request->post[$field_name] = '';
			}
		//END

		//Devman Extensions - info@devmanextensions.com - 2017-06-03 13:03:24 - Insert manually names of zones and countries

		if(!empty($this->request->post['country_id']))
		{
			$country_id =$this->request->post['country_id'];
			$country = $this->db->query('SELECT * FROM '.DB_PREFIX.'country WHERE country_id = '.$country_id);
			$this->request->post['country'] = !empty($country->row['name']) ? $country->row['name'] : '';
			$this->request->post['iso_code_2'] = !empty($country->row['iso_code_2']) ? $country->row['iso_code_2'] : '';
			$this->request->post['iso_code_3'] = !empty($country->row['iso_code_3']) ? $country->row['iso_code_3'] : '';
		}

		if(!empty($this->request->post['zone_id']))
		{
			$zone_id =$this->request->post['zone_id'];
			$country = $this->db->query('SELECT * FROM '.DB_PREFIX.'zone WHERE zone_id = '.$zone_id);
			$this->request->post['zone'] = !empty($country->row['name']) ? $country->row['name'] : '';
			$this->request->post['zone_code'] = !empty($country->row['code']) ? $country->row['code'] : '';
		}

		if($address_type == 'payment_address' && !$logged)
		{
			$this->session->data['guest'] = $this->request->post;
			if(!$this->more_oc_2)
				$this->session->data['guest']['payment'] = $this->request->post;
			$this->session->data['guest']['customer_group_id'] = $this->config->get('config_customer_group_id');
		}
		elseif($address_type == 'shipping_address' && !$logged && !$this->more_oc_2)
		{
			$this->session->data['guest']['shipping'] = $this->request->post;
		}

		$this->session->data[$address_type] = $this->request->post;

		if($same_address)
		{
			$this->session->data['shipping_address'] = $this->request->post;
			if(!$this->more_oc_2) { $this->session->data['guest']['shipping'] = $this->request->post; }
		}

		//Devman Extensions - info@devmanextensions.com - 2017-07-22 14:55:13 - Custom fields
			if($this->more_oc_2 && !$logged)
			{
				$sent_custom_fields = isset($this->request->post['custom_field']);

				if($sent_custom_fields)
				{
					if($address_type == 'payment_address' || ($address_type == 'payment_address' && $same_address))
					{
						$custom_field_account = !empty($this->request->post['custom_field']['account']) ? $this->request->post['custom_field']['account'] : array();
						if(!empty($custom_field_account))
							$this->session->data['guest']['custom_field'] = $this->request->post['custom_field']['account'];

						$custom_field_address = !empty($this->request->post['custom_field']['address']) ? $this->request->post['custom_field']['address'] : array();
						if(!empty($custom_field_address))
						{
							$this->session->data['payment_address']['custom_field'] = $this->request->post['custom_field']['address'];
							if($same_address)
								$this->session->data['shipping_address']['custom_field'] = $this->request->post['custom_field']['address'];
						}
					}
					elseif($address_type == 'shipping_address')
					{
						$custom_field_address = !empty($this->request->post['custom_field']['address']) ? $this->request->post['custom_field']['address'] : array();
						if(!empty($custom_field_address))
							$this->session->data['shipping_address']['custom_field'] = $this->request->post['custom_field']['address'];
					}
				}
			}
		//END

        if($die_json_encode) {
            echo json_encode(array('Address ' . $address_type . ' set'));
            die;
        }
        return true;
	}

	public function ajax_set_shipping_method()
	{
		$shipping_method = $this->request->post['shipping_method'];
		$shipping = explode('.', $shipping_method);

		if(!array_key_exists('shipping_method', $this->session->data))
		    $this->session->data['shipping_method'] = array();

		$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
		$this->session->data['shipping_method_code'] = $shipping[0];
		$this->session->data['shipping_method_quote_code'] = $shipping[1];


		echo json_encode(array('Shipping method '.$shipping_method.' set')); die;
	}

	public function ajax_get_shipping_methods($params = array())
	{
		$array_return = array('error' => false, 'message' => '', 'data' => array());

		$this->session->data['poc_shipping_method_ajax_view'] = true;

		$data = array();

		//Devman Extensions - info@devmanextensions.com - 2017-09-06 19:29:21 - Call tu default function in checkout to load shipping methods
			if($this->more_oc_2)
				$methods_json = $this->load->controller('checkout/shipping_method', array('return' => true));
			else
				$methods_json = $this->getChild('checkout/shipping_method', array('return' => true));

			if(version_compare(VERSION, '1.5.6.4', '<='))
			{
				$methods_json = array();
				$data = array_key_exists('catalog_controller_checkout_shipping_method_datas', $this->session->data) ? $this->session->data['catalog_controller_checkout_shipping_method_datas'] : '';
				unset($this->session->data['catalog_controller_checkout_shipping_method_datas']);
			}
		//END

		if(!empty($methods_json))
			$data = json_decode($methods_json, true);

		//Devman Extensions - info@devmanextensions.com - 2017-09-06 19:35:51 - Mark shipping method
			$shipping_method_choosed_code = array_key_exists('shipping_method_code', $this->session->data) && !empty($this->session->data['shipping_method_code']) ? $this->session->data['shipping_method_code'] : false;
			$shipping_method_quote_choosed_code = array_key_exists('shipping_method_quote_code', $this->session->data) && !empty($this->session->data['shipping_method_quote_code']) ? $this->session->data['shipping_method_quote_code'] : false;

			$shipping_methods = array_key_exists('shipping_methods', $data) && !empty($data['shipping_methods']) ? $data['shipping_methods'] : false;

			//<editor-fold desc="Check if payment method choosed exist in these new payment methods">
                if(!empty($shipping_method_choosed_code) && !empty($shipping_methods)) {
                    $exist = false;
                    foreach ($shipping_methods as $sm_code => $pm) {
                        if($shipping_method_choosed_code == $sm_code)
                            $exist = true;
                    }

                    if(!$exist) {
                        $first_shipping_method = current($shipping_methods);
                        foreach ($shipping_methods as $sm_code => $sm) {
                            $shipping_method_choosed_code = $sm_code;
                            foreach ($sm['quote'] as $quote_code => $quote) {
                                $shipping_method_quote_choosed_code = $quote_code;
                                break;
                            }
                            break;
                        }
                    }
                }

            //</editor-fold>

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

			if(!empty($shipping_methods))
			{
				$data['method_chossed'] = true;
				$first_shipping_method = false;
				$first_quote = false;
				foreach ($shipping_methods as $sm_code => $sm) {

                    //<editor-fold desc="Load image">
                        $data['images'][$sm_code] = array('image' => '');
                        $image = $this->config->get('poc_shipping_method_image_'.$sm_code);
                        if(!empty($image)) {
                            $data['images'][$sm_code]['image'] = HTTPS_SERVER.'image/'.$image;
                        } else {
                            $image = 'view/theme/perfect_one_checkout/img/shipping/'.$sm_code.'.png';
                            if(is_file(DIR_APPLICATION.$image)) {
                                $data['images'][$sm_code]['image'] = HTTPS_SERVER.'catalog/'.$image;
                            }
                        }
				    //</editor-fold>

                    if(!empty($sm['quote'])) {
                        if (!$first_shipping_method && empty($shipping_method_choosed_code)) {
                            $first_shipping_method = $sm_code;
                            $shipping_method_choosed_code = $sm_code;
                        }

                        if ($shipping_method_choosed_code == $sm_code) {
                            $data['shipping_methods'][$sm_code]['checked'] = true;
                        } else
                            $data['shipping_methods'][$sm_code]['checked'] = false;

                        foreach ($sm['quote'] as $quote_code => $quote) {
                            if (!$first_quote && empty($shipping_method_quote_choosed_code)) {
                                $first_quote = $quote_code;
                                $shipping_method_quote_choosed_code = $quote_code;
                            }

                            if ($quote_code == $shipping_method_quote_choosed_code) {
                                $checked = true;
                            } else
                                $checked = false;

                            $data['shipping_methods'][$sm_code]['quote'][$quote_code]['checked'] = $checked;
                        }
                    }
				}
				//Devman Extensions - info@devmanextensions.com - 2017-09-07 10:34:38 - Set shipping method in session
				    if(!empty($shipping_method_quote_choosed_code)) {
                        $this->session->data['shipping_method'] = array_key_exists($shipping_method_choosed_code, $shipping_methods) && array_key_exists('quote', $shipping_methods[$shipping_method_choosed_code]) && array_key_exists($shipping_method_quote_choosed_code, $shipping_methods[$shipping_method_choosed_code]['quote']) ? $shipping_methods[$shipping_method_choosed_code]['quote'][$shipping_method_quote_choosed_code] : '';
				    }
				//END
			}
		//END

		$poc_icon_html = $this->config->get('poc_design_icons') == 'typicons' ? '<span class="typcn typcn-classIcon"></span>' : '<i class="fa fa-classIcon"></i>';
		$icon_error_class = $this->config->get('poc_design_icons') == 'typicons' ? 'warning' : 'warning';
		$data['poc_icon_error'] = str_replace('classIcon', $icon_error_class, $poc_icon_html);
		$data['error_no_shipping'] = $this->language->get('error_no_shipping');

		if($this->more_oc_2)
		{
			$template_path = version_compare(VERSION, '2.1.0.2', '<=') ? 'default/template/checkout/perfect_one_checkout/shipping_method.tpl' : 'checkout/perfect_one_checkout/shipping_method';
			$html = $this->load->view($template_path, $data);
		}
		else
		{
			foreach ($data as $key => $value) {
				$this->data[$key] = $value;
			}
			$this->template = 'default/template/checkout/perfect_one_checkout/shipping_method'.$this->extension_template;
			$html = $this->render();
		}

		if(!empty($params['return']))
			return $html;

		$array_return['data'] = $html;

		echo json_encode($array_return); die;
	}

	public function ajax_set_payment_method()
	{
		$payment_method = $this->request->post['payment_method'];

		if(!array_key_exists('payment_methods', $this->session->data))
		    $this->session->data['payment_methods'] = array();

		$this->session->data['payment_method'] = $this->session->data['payment_methods'][$payment_method];
		echo json_encode(array('Payment method '.$payment_method.' set')); die;
	}

	public function ajax_get_payment_methods($params = array())
	{
		$array_return = array('error' => false, 'message' => '', 'data' => array());

		$this->session->data['poc_payment_method_ajax_view'] = true;

		$data = array();

		//Devman Extensions - info@devmanextensions.com - 2017-09-06 19:29:21 - Call tu default function in checkout to load payment methods
			if($this->more_oc_2)
				$methods_json = $this->load->controller('checkout/payment_method', array('return' => true));
			else
				$methods_json = $this->getChild('checkout/payment_method');

			if(version_compare(VERSION, '1.5.6.4', '<='))
			{
				$methods_json = array();
				$data = array_key_exists('catalog_controller_checkout_payment_method_datas', $this->session->data) ? $this->session->data['catalog_controller_checkout_payment_method_datas'] : '';
				unset($this->session->data['catalog_controller_checkout_payment_method_datas']);
			}
		//END

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

		if(!empty($methods_json))
			$data = json_decode($methods_json, true);

		//Devman Extensions - info@devmanextensions.com - 2017-09-06 19:35:51 - Mark payment method
			$payment_method_choosed_code = array_key_exists('payment_method', $this->session->data) && !empty($this->session->data['payment_method']) ? $this->session->data['payment_method']['code'] : false;
			$payment_methods = array_key_exists('payment_methods', $data) && !empty($data['payment_methods']) ? $data['payment_methods'] : false;
            //<editor-fold desc="Check if payment method choosed exist in these new payment methods">
                if(!empty($payment_method_choosed_code) && !empty($payment_methods)) {
                    $exist = false;
                    foreach ($payment_methods as $pm_code => $pm) {
                        if($payment_method_choosed_code == $pm_code)
                            $exist = true;
                    }

                    if(!$exist) {
                        $first_payment_method = current($payment_methods);
                        $payment_method_choosed_code = $first_payment_method['code'];
                    }
                }
            //</editor-fold>
			if(!empty($payment_methods))
			{
				$data['method_chossed'] = true;
				$first_payment_method = false;
				foreach ($payment_methods as $pm_code => $pm) {

				    //<editor-fold desc="Load image">
                        $data['images'][$pm_code] = array('image' => '');
                        $image = $this->config->get('poc_payment_method_image_'.$pm_code);
                        if(!empty($image)) {
                            $data['images'][$pm_code]['image'] = HTTPS_SERVER.'image/'.$image;
                        } else {
                            $image = 'view/theme/perfect_one_checkout/img/payment/'.$pm_code.'.png';
                            if(is_file(DIR_APPLICATION.$image)) {
                                $data['images'][$pm_code]['image'] = HTTPS_SERVER.'catalog/'.$image;
                            }
                        }
				    //</editor-fold>

					if(!$first_payment_method && empty($payment_method_choosed_code))
						$payment_method_choosed_code = $pm_code;

					if($pm_code == $payment_method_choosed_code)
					{
						$checked = true;
					}
					else
						$checked = false;

					$data['payment_methods'][$pm_code]['checked'] = $checked;
				}

				//Devman Extensions - info@devmanextensions.com - 2017-09-07 10:34:38 - Set payment method in session
					$this->session->data['payment_method'] = $payment_methods[$payment_method_choosed_code];
				//END
			}
		//END

		//Devman Extensions - info@devmanextensions.com - 2017-09-07 10:54:03 - Some error?
			if(array_key_exists('error_warning', $data))
				$data['error_no_payment'] = $data['error_warning'];
		//END
		$poc_icon_html = $this->config->get('poc_design_icons') == 'typicons' ? '<span class="typcn typcn-classIcon"></span>' : '<i class="fa fa-classIcon"></i>';
		$icon_error_class = $this->config->get('poc_design_icons') == 'typicons' ? 'warning' : 'warning';
		$data['poc_icon_error'] = str_replace('classIcon', $icon_error_class, $poc_icon_html);

		if($this->more_oc_2)
		{
			$template_path = version_compare(VERSION, '2.1.0.2', '<=') ? 'default/template/checkout/perfect_one_checkout/payment_method.tpl' : 'checkout/perfect_one_checkout/payment_method';
			$html = $this->load->view($template_path, $data);
		}
		else
		{
			foreach ($data as $key => $value) {
				$this->data[$key] = $value;
			}
			$this->template = 'default/template/checkout/perfect_one_checkout/payment_method'.$this->extension_template;
			$html = $this->render();
		}

		if(!empty($params['return']))
			return $html;

		$array_return['data'] = $html;

		echo json_encode($array_return); die;
	}

	public function ajax_get_payment_info($params = array())
	{
		$array_return = array('error' => false, 'message' => '', 'data' => array());

		$code = !empty($this->request->post['payment_method_code']) ? $this->request->post['payment_method_code'] : (!empty($this->session->data['payment_method']['code']) ? $this->session->data['payment_method']['code'] : '');
		$payment_method = !empty($this->session->data['payment_methods'][$code]) ? $this->session->data['payment_methods'][$code] : '';

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

		if(!empty($payment_method))
		{
			if(array_key_exists('code', $payment_method) && !empty($payment_method['code']))
			{
				$code = explode('.', $payment_method['code']);
				$code = $code[0];
			}
			if($this->more_oc_2)
				$html_payment_info = $this->load->controller($this->prefix_extension.'payment/' . $code);
			else
				$html_payment_info = $this->getChild($this->prefix_extension.'payment/' . $code);

			$array_return['data'] = $html_payment_info;
		}

		if(!empty($params['return']))
			return !empty($html_payment_info) ? $html_payment_info : '';

		echo json_encode($array_return); die;
	}

	public function ajax_same_address()
	{
		$this->session->data['poc']['same_address'] = $this->request->post['checked'] == 'true' ? true : false;
		echo json_encode(array('Same address: '.$this->request->post['checked'])); die;
	}

	public function ajax_same_address_update_address()
	{
		unset($this->session->data['address_type']);

		$add_empty_fields = array('company', 'address_2', 'zone', 'country', 'address_format');

		foreach ($add_empty_fields as $key => $field) {
			if(!array_key_exists($field, $this->request->post))
				$this->request->post[$field] = '';
		}

		$this->session->data['shipping_address'] = $this->request->post;

		echo json_encode(array('Shipping address updated to '.json_encode($this->request->post))); die;
	}

	public function ajax_get_addresses() {
		$this->load->language('checkout/checkout');

		$data['text_address_existing'] = $this->language->get('text_address_existing');
		$data['text_address_new'] = $this->language->get('text_address_new');
		$data['text_select'] = $this->language->get('text_select');
		$data['text_none'] = $this->language->get('text_none');
		$data['text_loading'] = $this->language->get('text_loading');

		$data['entry_firstname'] = $this->language->get('entry_firstname');
		$data['entry_lastname'] = $this->language->get('entry_lastname');
		$data['entry_company'] = $this->language->get('entry_company');
		$data['entry_address_1'] = $this->language->get('entry_address_1');
		$data['entry_address_2'] = $this->language->get('entry_address_2');
		$data['entry_postcode'] = $this->language->get('entry_postcode');
		$data['entry_city'] = $this->language->get('entry_city');
		$data['entry_country'] = $this->language->get('entry_country');
		$data['entry_zone'] = $this->language->get('entry_zone');

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

		if (isset($this->session->data['payment_address']['address_id'])) {
			$data['address_id'] = $this->session->data['payment_address']['address_id'];
		} else {
			$data['address_id'] = $this->customer->getAddressId();
		}

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

		$data['addresses'] = $this->model_account_address->getAddresses();

		if (isset($this->session->data['payment_address']['country_id'])) {
			$data['country_id'] = $this->session->data['payment_address']['country_id'];
		} else {
			$data['country_id'] = $this->config->get('config_country_id');
		}

		if (isset($this->session->data['payment_address']['zone_id'])) {
			$data['zone_id'] = $this->session->data['payment_address']['zone_id'];
		} else {
			$data['zone_id'] = '';
		}

		$this->load->model('localisation/country');

		$data['countries'] = $this->model_localisation_country->getCountries();

		// Custom Fields
		$this->load->model('account/custom_field');

		$data['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

		if (isset($this->session->data['payment_address']['custom_field'])) {
			$data['payment_address_custom_field'] = $this->session->data['payment_address']['custom_field'];
		} else {
			$data['payment_address_custom_field'] = array();
		}

		$template_path = version_compare(VERSION, '2.1.0.2', '<=') ? 'default/template/checkout/payment_address.tpl' : 'checkout/payment_address';
		$this->response->setOutput($this->load->view($template_path, $data));
	}

	public function ajax_set_order_comment()
	{
		$this->session->data['comment'] = $this->request->post['comment'];
		$this->model_extension_module_perfect_one_checkout->add_edit_order();
		echo json_encode(array('Order comment saved in session')); die;
	}

	public function ajax_update_cart()
	{
		$post_data = $this->request->post;

		//Update quantities
			if(!empty($post_data['quantity']))
			{
				foreach ($post_data['quantity'] as $key => $value) {
					$this->cart->update($key, $value);
				}
			}
		//END

		$array_return = array('html' => '', 'heading' => '', 'redirect' => $this->url->link('checkout/cart'));
		if($this->cart->countProducts() != 0)
		{
			/*if(version_compare(VERSION, '2.0.0.0', '<'))
				$this->session->data['poc_cart_view'] = 'default/template/checkout/perfect_one_checkout/cart_info'.$this->extension_template;
			elseif(version_compare(VERSION, '2.0.0.0', '>=') && version_compare(VERSION, '2.2.0.0', '<'))
				$this->session->data['poc_cart_view'] = $this->config->get('config_template') . '/template/checkout/perfect_one_checkout/cart_info.tpl';
			else
				$this->session->data['poc_cart_view'] = 'checkout/perfect_one_checkout/cart_info'.$this->extension_template;*/

			if(version_compare(VERSION, '2.1.0.2', '<='))
                $this->session->data['poc_cart_view'] = 'default/template/checkout/perfect_one_checkout/cart_info.tpl';
            else
                $this->session->data['poc_cart_view'] = 'checkout/perfect_one_checkout/cart_info';

			if($this->more_oc_2)
				$html_payment_info = $this->load->controller('common/cart');
			else
				$html_payment_info = $this->getChild('module/cart');

			$array_return['html'] = $html_payment_info;

			if(!$this->more_oc_2)
			{
				$total_data = array();
				$total = 0;
				$taxes = $this->cart->getTaxes();

				// Display prices
				if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
					$sort_order = array();

					$results = $this->model_setting_extension->getExtensions('total');

					foreach ($results as $key => $value) {
						$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
					}

					array_multisort($sort_order, SORT_ASC, $results);

					foreach ($results as $result) {
						if ($this->config->get($result['code'] . '_status')) {
							$this->load->model('total/' . $result['code']);

							$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
						}

						$sort_order = array();

						foreach ($total_data as $key => $value) {
							$sort_order[$key] = $value['sort_order'];
						}

						array_multisort($sort_order, SORT_ASC, $total_data);
					}
				}


				$array_return['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));
			}
			else
			{
				$array_return['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($this->cart->getTotal(), $this->session->data['currency']));
			}

			$array_return['heading'] = $this->session->data['poc']['lang']['cart_title'].($this->config->get('config_cart_weight') ? ' ('.$this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point')).')' : '');
		}

		$this->model_extension_module_perfect_one_checkout->add_edit_order();
		echo json_encode($array_return); die;
	}

	function _oc15x_coupon()
	{
		$array_return = array('error' => false);

		$errors_coupon = $this->_oc15x_validateCoupon();

		if (isset($this->request->post['coupon']) && !$errors_coupon)
			$this->session->data['coupon'] = $this->request->post['coupon'];
		else
			$array_return['error'] = $errors_coupon;

		echo json_encode($array_return); die;
	}

	function _oc15x_voucher()
	{
		$errors_voucher = $this->_oc15x_validateVoucher();

		if (isset($this->request->post['voucher']) && !$errors_voucher)
			$this->session->data['voucher'] = $this->request->post['voucher'];
		else
			$array_return['error'] = $errors_voucher;

		echo json_encode($array_return); die;
	}

	function _oc15x_reward()
	{
		$array_return = array('error' => false);

		$errors_reward = $this->_oc15x_validateReward();

		if (isset($this->request->post['reward']) && !$errors_reward)
			$this->session->data['reward'] = $this->request->post['reward'];
		else
			$array_return['error'] = $errors_reward;

		echo json_encode($array_return); die;
	}

	protected function _oc15x_validateCoupon() {
		$this->language->load('checkout/cart');
		$this->load->model('checkout/coupon');

		$coupon_info = $this->model_checkout_coupon->getCoupon($this->request->post['coupon']);

		if (!$coupon_info)
			return $this->language->get('error_coupon');

		return false;
	}

	protected function _oc15x_validateVoucher() {
		$this->language->load('checkout/cart');
		$this->load->model('checkout/voucher');

		$voucher_info = $this->model_checkout_voucher->getVoucher($this->request->post['voucher']);

		if (!$voucher_info)
			return  $this->language->get('error_voucher');

		return false;
	}

	protected function _oc15x_validateReward()
	{
		$this->language->load('checkout/cart');
		$points = $this->customer->getRewardPoints();

		$points_total = 0;

		foreach ($this->cart->getProducts() as $product) {
			if ($product['points']) {
				$points_total += $product['points'];
			}
		}

		if (empty($this->request->post['reward'])) {
			return $this->language->get('error_reward');
		}

		if ($this->request->post['reward'] > $points) {
			return sprintf($this->language->get('error_points'), $this->request->post['reward']);
		}

		if ($this->request->post['reward'] > $points_total) {
			return sprintf($this->language->get('error_maximum'), $points_total);
		}

		return false;
	}

	public function sign_in_facebook_call_back() {
        $fb = new Facebook\Facebook(array(
            'app_id' => $this->config->get('poc_sign_in_facebook_app_id'),
            'app_secret' => $this->config->get('poc_sign_in_facebook_app_secret'),
            'default_graph_version' => 'v2.11',
        ));

        $helper = $fb->getRedirectLoginHelper();

        try {
            $accessToken = $helper->getAccessToken(HTTPS_SERVER."index.php?route=extension/module/perfect_one_checkout/sign_in_facebook_call_back");
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        if (isset($accessToken)) {
            $accessToken_code = $accessToken->getValue();
            try {
                $response = $fb->get('/me?fields=id,first_name,last_name,email,hometown,locale,location', $accessToken_code);
            } catch(Facebook\Exceptions\FacebookResponseException $e) {
                echo 'Graph returned an error: ' . $e->getMessage();
                exit;
            } catch(Facebook\Exceptions\FacebookSDKException $e) {
                echo 'Facebook SDK returned an error: ' . $e->getMessage();
                exit;
            }
            $user = $response->getGraphUser();

            if(!empty($user)) {
                $this->request->post['firstname'] = isset($user['first_name']) ? $user['first_name'] : '';
                $this->request->post['lastname'] = isset($user['last_name']) ? $user['last_name'] : '';
                $this->request->post['email'] = isset($user['email']) ? $user['email'] : '';
                $this->request->post['city'] = isset($user['hometown']) && isset($user['hometown']['name']) ? $user['hometown']['name'] : '';

                if(isset($user['location']) && isset($user['location']['id'])) {
                    $response = $fb->get('/' . $user['location']['id'] . '?fields=location', $accessToken_code);
                    $location = $response->getGraphNode();
                    if(!empty($location) && isset($location['location']))
                    {
                        $this->request->post['city'] = isset($location['location']['city']) ? $location['location']['city'] : $this->request->post['city'];
                        $this->request->post['postcode'] = isset($location['location']['zip']) ? $location['location']['zip'] : '';
                        $country_name = isset($location['location']['country']) ? $location['location']['country'] : '';
                        if(!empty($country_name)) {
                            $country_id = $this->model_extension_module_perfect_one_checkout->_get_country_id($country_name);
                            $this->request->post['country_id'] = $country_id;
                            if(!empty($country_id))
                                $this->request->post['zone_id'] = $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $location['location']['city']);
                        }
                    }
                }

                $this->request->post['address_type'] = 'payment_address';
                $this->ajax_set_address_guest(false);
                $this->request->post['address_type'] = 'shipping_address';
                $this->ajax_set_address_guest(false);

                $success_sign_in_message = $this->session->data['poc']['lang']['sign_in_success_title'];
                $custom_code = "<script>$(document).on('ready', function(){";
                    $custom_code .= "_insert_alert_manual($('div.perfect_one_checkout_main_container'), \"".$success_sign_in_message."\", 'success', 'inside', true);";
                    $custom_code .= !empty($this->request->post['firstname']) ? '_put_autocompleted_class($(\'input[name="firstname"]\'));' : '';
                    $custom_code .= !empty($this->request->post['lastname']) ? '_put_autocompleted_class($(\'input[name="lastname"]\'));' : '';
                    $custom_code .= !empty($this->request->post['email']) ? '_put_autocompleted_class($(\'input[name="email"]\'));' : '';
                    $custom_code .= !empty($this->request->post['city']) ? '_put_autocompleted_class($(\'input[name="city"]\'));' : '';
                    $custom_code .= !empty($this->request->post['postcode']) ? '_put_autocompleted_class($(\'input[name="postcode"]\'));' : '';
                    $custom_code .= !empty($this->request->post['country_id']) ? '_put_autocompleted_class($(\'select[name="country_id"]\'));' : '';
                    $custom_code .= !empty($this->request->post['zone_id']) ? '_put_autocompleted_class($(\'select[name="zone_id"]\'));' : '';
                $custom_code .= "})</script>";

                $this->session->data['poc_custom_code'] = $custom_code;
            }
        }

        $this->response->redirect($this->url->link('checkout/checkout'));
    }

    public function sign_in_linkedin_call_back() {
        $redirect_url = urlencode(HTTPS_SERVER.'index.php?route=extension/module/perfect_one_checkout/sign_in_linkedin_call_back');
        $client_id = $this->config->get('poc_sign_in_linkedin_client_id');
        $secret_id = $this->config->get('poc_sign_in_linkedin_secret_id');

        $code = array_key_exists('code', $_GET) ? $_GET['code'] : '';
        $url = 'https://www.linkedin.com/uas/oauth2/accessToken';
        $param = 'grant_type=authorization_code&code='.$code.'&redirect_uri='.$redirect_url.'&client_id='.$client_id.'&client_secret='.$secret_id;
        $return = (json_decode($this->_post_curl($url,$param),true));

        if(array_key_exists('error', $return))
        {
            $custom_code = "<script>$(document).on('ready', function(){";
                $custom_code .= "_insert_alert_manual($('div.perfect_one_checkout_main_cntainer'), \"".$return['error_description']."\", 'danger', 'inside', true);";
            $custom_code .= "})</script>";
            $this->session->data['poc_custom_code'] = $custom_code;
        }
        else
        {
            $url = 'https://api.linkedin.com/v1/people/~:(id,firstName,lastName,location,email-address)?format=json&oauth2_access_token='.$return['access_token'];
            $user = json_decode($this->_post_curl($url), true);
            $this->request->post['firstname'] = isset($user['firstName']) ? $user['firstName'] : '';
            $this->request->post['lastname'] = isset($user['lastName']) ? $user['lastName'] : '';
            $this->request->post['email'] = isset($user['emailAddress']) ? $user['emailAddress'] : '';
            if(isset($user['location']['country']['code']))
            {
                $country_id = $this->model_extension_module_perfect_one_checkout->_get_country_id('',$user['location']['country']['code']);
                $this->request->post['country_id'] = $country_id;

                if(!empty($country_id) && !empty($user['location']['name']))
                {
                    $split_zone = explode(' Area', $user['location']['name']);
                    $zone_name = $split_zone[0];
                    $this->request->post['city'] = $zone_name;
                    $this->request->post['zone_id'] = $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $zone_name);
                }
            }

            $this->request->post['address_type'] = 'payment_address';
            $this->ajax_set_address_guest(false);
            $this->request->post['address_type'] = 'shipping_address';
            $this->ajax_set_address_guest(false);

            $success_sign_in_message = $this->session->data['poc']['lang']['sign_in_success_title'];
            $custom_code = "<script>$(document).on('ready', function(){";
                $custom_code .= "_insert_alert_manual($('div.perfect_one_checkout_main_container'), \"".$success_sign_in_message."\", 'success', 'inside', true);";
                $custom_code .= !empty($this->request->post['firstname']) ? '_put_autocompleted_class($(\'input[name="firstname"]\'));' : '';
                $custom_code .= !empty($this->request->post['lastname']) ? '_put_autocompleted_class($(\'input[name="lastname"]\'));' : '';
                $custom_code .= !empty($this->request->post['email']) ? '_put_autocompleted_class($(\'input[name="email"]\'));' : '';
                $custom_code .= !empty($this->request->post['city']) ? '_put_autocompleted_class($(\'input[name="city"]\'));' : '';
                $custom_code .= !empty($this->request->post['country_id']) ? '_put_autocompleted_class($(\'select[name="country_id"]\'));' : '';
                $custom_code .= !empty($this->request->post['zone_id']) ? '_put_autocompleted_class($(\'select[name="zone_id"]\'));' : '';
            $custom_code .= "})</script>";

            $this->session->data['poc_custom_code'] = $custom_code;
        }
        $this->response->redirect($this->url->link('checkout/checkout'));
    }

    public function sing_in_paypal_call_back() {
	    if(array_key_exists('code', $_GET)) {
            $url_callback = HTTPS_SERVER . 'index.php?route=extension/module/perfect_one_checkout/sing_in_paypal_call_back';
            $requestData = '?grant_type=authorization_code&code=' . $_GET['code'] . '&return_url=' . $url_callback;
            $clientId = $this->config->get('poc_sign_in_paypal_app_id');
            $clientSecret = $this->config->get('poc_sign_in_paypal_secret_id');

            //<editor-fold desc="Get access token">
                $response = \Httpful\Request::get('https://api.paypal.com/v1/identity/openidconnect/tokenservice' . $requestData)
                    ->authenticateWith($clientId, $clientSecret)
                    ->send();

                $jsonResponse = json_decode($response->raw_body, true);

                if (isset($jsonResponse['error'])) {
                    die($jsonResponse['error']);
                }
                $access_token = $jsonResponse['access_token'];
            //</editor-fold>

            //<editor-fold desc="Connect to API">
                $apiContext = new \PayPal\Rest\ApiContext(
                    new \PayPal\Auth\OAuthTokenCredential(
                        $clientId,
                        $clientSecret
                    )
                );
                $apiContext->setConfig(
                    array(
                        'mode' => 'live',
                    )
                );
            //</editor-fold>

            //<editor-fold desc="Get user data">
                try {
                    $params = array('access_token' => $access_token);
                    $userInfo = OpenIdUserinfo::getUserinfo($params, $apiContext);
                } catch (Exception $ex) {
                    echo json_encode($ex);
                    die;
                }
                $this->request->post['firstname'] = $userInfo->getGivenName();
                $this->request->post['lastname'] = $userInfo->getFamilyName();
                $this->request->post['email'] = $userInfo->getEmail();
                $this->request->post['telephone'] = $userInfo->getPhoneNumber();

                $address = $userInfo->getAddress();
                $address = !empty($address) ? json_decode($address, true) : '';

                if(!empty($address)) {
                    $country_id = $this->model_extension_module_perfect_one_checkout->_get_country_id('',$address['country']);
                    $zone_name = $address['region'];

                    $this->request->post['country_id'] = $country_id;
                    $this->request->post['city'] = ucfirst(strtolower($address['locality']));
                    $this->request->post['postcode'] = $address['postal_code'];
                    $this->request->post['address_1'] = $address['street_address'];
                    if(!empty($country_id)) {
                        $this->request->post['zone_id'] = $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $zone_name);
                    }
                }
            //</editor-fold>


            //<editor-fold desc="Set addresses">
                $this->request->post['address_type'] = 'payment_address';
                $this->ajax_set_address_guest(false);
                $this->request->post['address_type'] = 'shipping_address';
                $this->ajax_set_address_guest(false);

                $success_sign_in_message = $this->session->data['poc']['lang']['sign_in_success_title'];
                $custom_code = "<script>$(document).on('ready', function(){";
                    $custom_code .= "_insert_alert_manual($('div.perfect_one_checkout_main_container'), \"".$success_sign_in_message."\", 'success', 'inside', true);";
                    $custom_code .= !empty($this->request->post['firstname']) ? '_put_autocompleted_class($(\'input[name="firstname"]\'));' : '';
                    $custom_code .= !empty($this->request->post['lastname']) ? '_put_autocompleted_class($(\'input[name="lastname"]\'));' : '';
                    $custom_code .= !empty($this->request->post['telephone']) ? '_put_autocompleted_class($(\'input[name="telephone"]\'));' : '';
                    $custom_code .= !empty($this->request->post['email']) ? '_put_autocompleted_class($(\'input[name="email"]\'));' : '';
                    $custom_code .= !empty($this->request->post['city']) ? '_put_autocompleted_class($(\'input[name="city"]\'));' : '';
                    $custom_code .= !empty($this->request->post['address_1']) ? '_put_autocompleted_class($(\'input[name="address_1"]\'));' : '';
                    $custom_code .= !empty($this->request->post['postcode']) ? '_put_autocompleted_class($(\'input[name="postcode"]\'));' : '';
                    $custom_code .= !empty($this->request->post['country_id']) ? '_put_autocompleted_class($(\'select[name="country_id"]\'));' : '';
                    $custom_code .= !empty($this->request->post['zone_id']) ? '_put_autocompleted_class($(\'select[name="zone_id"]\'));' : '';
                $custom_code .= "})</script>";

                $this->session->data['poc_custom_code'] = $custom_code;
            //</editor-fold>

        } else {
	        die('NO "CODE" GET PARAM FOUND');
        }

        $link_to_checkout = $this->url->link('checkout/checkout');

	    die("<!DOCTYPE html><html><head><title></title><script>top.window.opener.location = '".$link_to_checkout."';window.close();</script></head><body></body></html>");
    }

    function _post_curl($url,$param="") {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        if($param!="")
        curl_setopt($ch,CURLOPT_POSTFIELDS,$param);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    public function get_country_id_and_zone_id() {
        $array_return = array('country_id' => '', 'zone_id' => '');
        $iso_code = array_key_exists('country_iso_code', $this->request->post) ? $this->request->post['country_iso_code'] : '';
        $zone_code_1 = array_key_exists('zone_code_1', $this->request->post) ? $this->request->post['zone_code_1'] : '';
        $zone_name_1 = array_key_exists('zone_name_1', $this->request->post) ? $this->request->post['zone_name_1'] : '';
        $zone_code_2 = array_key_exists('zone_code_2', $this->request->post) ? $this->request->post['zone_code_2'] : '';
        $zone_name_2 = array_key_exists('zone_name_2', $this->request->post) ? $this->request->post['zone_name_2'] : '';

        if(!empty($iso_code))
        {
            $country_id = $this->model_extension_module_perfect_one_checkout->_get_country_id('', $iso_code);
            if(!empty($country_id) && (!empty($zone_code_1) || !empty($zone_code_2) || !empty($zone_name_1) || !empty($zone_name_2))) {
                $zone_id = !empty($zone_name_1) ? $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $zone_name_1) : '';
                $zone_id = empty($zone_id) && !empty($zone_name_2) ? $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $zone_name_2) : $zone_id;
                $zone_id = empty($zone_id) && !empty($zone_code_1) ? $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $zone_code_1, true) : $zone_id;
                $zone_id = empty($zone_id) && !empty($zone_code_2) ? $this->model_extension_module_perfect_one_checkout->_get_zone_id($country_id, $zone_code_2, true) : $zone_id;

                $array_return['zone_id'] = $zone_id;
            }
            $array_return['country_id'] = $country_id;
        }

	    echo json_encode($array_return); die;
    }

    public function ajax_remove_cart_discount() {
	     $type = $this->request->post['type'];
	     unset($this->session->data[$type]);
	     echo json_encode(array('status' => $type.' removed')); die;
    }
}
?>