<?php
require_once DIR_SYSTEM . 'library/devmanextensions_poc/Facebook/autoload.php';

class ModelExtensionModulePerfectOneCheckout extends Model {
    public function __construct($registry) {
        parent::__construct($registry);

        $loader = new Loader($registry);
        $loader->language('checkout/checkout');
        $this->prefix_extension = version_compare(VERSION, '2.3.0.1', '>=') ? 'extension/' : '';
        $this->model_init = version_compare(VERSION, '2.3.0.1', '>=') ? 'model_extension' : 'model';
        $loader->model('account/customer');
        $prefix_code_total = '';
        if(version_compare(VERSION, '3.0.0.0', '>='))
        {
            $loader->model('setting/extension');
            $this->model_extension_name = 'model_setting_extension';
            $prefix_code_total = 'total_';
        }
        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';
        }

        if(version_compare(VERSION, '2.3', '>=')) {
            $this->model_prefix = 'extension/';
            $this->model_name = 'model_extension_';
        }
        else {
            $this->model_prefix = '';
            $this->model_name = 'model_';
        }

        $this->language_id = $this->config->get('config_language_id');

        $this->more_oc_2 = version_compare(VERSION, '2.0.0.0', '>=');

        if(version_compare(VERSION, '2.0.0.0', '>='))
        {
            $loader->model('account/custom_field');
            $customer_group_id = $this->customer->isLogged() ? $this->customer->getGroupId() : $this->config->get('config_customer_group_id');
            $this->custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
        }

        $this->prefix_code_total = $prefix_code_total;
        $this->input_to_modal = $this->config->get('poc_modals_in_forms');
        $this->module_clear = 12/$this->_get_form_span();
    }
    public function generate_form($form, $type_customer, $key_session_address)
    {
        $logged = $this->customer->isLogged();

        if(!$logged && !empty($this->session->data['poc']['same_address']) && in_array($key_session_address, array('shipping_address', 'register')))
            $key_session_address = 'guest';

        $html_form = '';
        $count_input = 1;

        foreach ($form as $input_name => $input) {
            //Devman Extensions - info@devmanextensions.com - 2017-07-15 18:08:10 - Custom fields, if is a custom field, load his configuration and add to form
            $is_custom_field = version_compare(VERSION, '2.0.0.0', '>=') && strpos($input_name, 'custom_field') !== false;
            if($is_custom_field)
            {
                $custom_field_id = (int)str_replace('custom_field_', '', $input_name);
                $field_info = $this->get_custom_field_info($custom_field_id);
                if(!empty($field_info))
                {
                    $is_account = $field_info['location'] == 'account';
                    $is_address = $field_info['location'] == 'address';

                    $is_guest = $type_customer == 'guest' || $type_customer == 'register';

                    $status_location =
                        ($is_guest && ($is_address || $is_account) && $key_session_address == 'payment_address')
                        ||
                        ($is_guest && $is_address && ($key_session_address == 'shipping_address' ||$key_session_address == 'guest'))
                        ||
                        (!$is_guest && $is_address && $key_session_address == 'payment_address');

                    if($status_location)
                    {
                        $options = array();

                        $placeholder = $field_info['name'];

                        $is_input_with_options = in_array($field_info['type'], array('select', 'radio', 'checkbox'));

                        if($field_info['type'] == 'select' && !empty($field_info['custom_field_value']))
                            $placeholder = $this->language->get('text_select');

                        if($is_input_with_options)
                            foreach ($field_info['custom_field_value'] as $key => $val)
                                $options[$val['custom_field_value_id']] = $val['name'];

                        $input_value = !empty($this->session->data[$key_session_address]['custom_field'][$custom_field_id]) ? $this->session->data[$key_session_address]['custom_field'][$custom_field_id] : $field_info['value'];

                        if($is_guest && $field_info['location'] == 'account')
                            $input_value = !empty($this->session->data['guest']['custom_field'][$custom_field_id]) ? $this->session->data['guest']['custom_field'][$custom_field_id] : $field_info['value'];

                        $input_final = array(
                            'type' => $field_info['type'],
                            'name' => 'custom_field['.$field_info['location'].']['.$field_info['custom_field_id'].']',
                            'value' => $input_value,
                            'label' => array(
                                $this->language_id => $field_info['name']
                            ),
                            'placeholder' => array(
                                $this->language_id => $placeholder
                            ),
                            'validation_rule' => !empty($field_info['required']) ? 'not_empty' : '',
                            'error_message' => !empty($input['error_message']) ? $input['error_message'] : array(),
                            'status_guest' => true,
                            'rule_guest' => !empty($field_info['required']) ? 'not_empty' : '',
                            'status_register' => true,
                            'rule_register' => !empty($field_info['required']) ? 'not_empty' : '',
                            'status_logged' => true,
                            'rule_logged' => !empty($field_info['required']) ? 'not_empty' : '',
                            'var_options' => '',
                            'options' => $options,
                            'onchange' => '',
                            'default_value' => !empty($field_info['value']) ? $field_info['value'] : '',
                            'type_customer' => $type_customer,
                            'custom_field' => true
                        );

                        $html_form .= $this->generate_input($input_final, $key_session_address);

                        if($count_input%$this->module_clear == 0)
                            $html_form .= '<div style="clear:both;"></div>';

                        $count_input++;
                    }
                }
            }
            //END

            if(!$is_custom_field && !empty($input['status_'.$type_customer]))
            {
                $input['name'] = $input_name;

                $input['value'] = !empty($this->session->data[$key_session_address][$input_name]) ? $this->session->data[$key_session_address][$input_name] : '';

                if($input['name'] == 'country_id' && empty($input['value']))
                    $input['value'] = $this->default_country_id;

                if($input['name'] == 'customer_group_id' && empty($input['value']))
                    $input['value'] = $this->default_customer_group_id;

                if(empty($input['rule_'.$type_customer]))
                    $input['validation_rule'] = '';

                if(!empty($input['type']) && $input['type'] == 'checkbox' && !empty($input['checked_'.$type_customer]))
                    $input['default_value'] = true;

                $input['type_customer'] = $type_customer;

                $input['value'] = $logged ? '' : $input['value'];
                $html_form .= $this->generate_input($input, $key_session_address);

                if($count_input%$this->module_clear == 0)
                    $html_form .= '<div style="clear:both;"></div>';

                $count_input++;
            }
        }

        return $html_form;
    }
    public function add_edit_order() {

        $customer_id = $this->customer->isLogged() ? $this->customer->getId() : false;
        $session = $this->session->data;
        $guest = array_key_exists('guest', $session);
        $payment_address = array_key_exists('payment_address', $session) && !empty($session['payment_address']);
        $shipping_address = array_key_exists('shipping_address', $session) && !empty($session['shipping_address']);

        $payment_method_title = array_key_exists('payment_method', $session) && is_array($session['payment_method']) && array_key_exists('title', $session['payment_method']) ? $session['payment_method']['title'] : '';
        $payment_method_code = array_key_exists('payment_method', $session) && is_array($session['payment_method']) && array_key_exists('code', $session['payment_method']) ? $session['payment_method']['code'] : '';
        $shipping_method_title = array_key_exists('shipping_method', $session) && is_array($session['shipping_method']) && array_key_exists('title', $session['shipping_method']) ? $session['shipping_method']['title'] : '';
        $shipping_method_code = array_key_exists('shipping_method', $session) && is_array($session['shipping_method']) && array_key_exists('code', $session['shipping_method']) ? $session['shipping_method']['code'] : '';

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

        $payment_address_format = '';
        $country_id_payment = $payment_address && array_key_exists('country_id', $session['payment_address']) ? $session['payment_address']['country_id'] : '';
        if(!empty($country_id_payment)) {
            $result = $this->db->query('SELECT address_format FROM ' . DB_PREFIX . 'country WHERE country_id = '.$country_id_payment);
            if($result->num_rows == 1)
                $payment_address_format = $result->row['address_format'];
        }

        $shipping_address_format = '';
        $country_id_shipping = $shipping_address && array_key_exists('country_id', $session['shipping_address']) ? $session['shipping_address']['country_id'] : '';
        if(!empty($country_id_shipping)) {
            $result = $this->db->query('SELECT address_format FROM ' . DB_PREFIX . 'country WHERE country_id = '.$country_id_shipping);
            if($result->num_rows == 1)
                $shipping_address_format = $result->row['address_format'];
        }

        $order_data = array(
            'invoice_prefix' => $this->config->get('config_invoice_prefix'),
            'store_id' => $this->config->get('config_store_id'),
            'store_name' => $this->config->get('config_name'),
            'store_url' => $this->config->get('config_store_id') ? $this->config->get('config_url') : (array_key_exists('HTTPS', $this->request->server) ? HTTPS_SERVER : HTTP_SERVER),
            'customer_id' => $customer_id ? $customer_id : 0,
            'customer_group_id' => $customer_id ? $customer_info['customer_group_id'] : ($guest && array_key_exists('customer_group_id', $session) ? $session['guest']['customer_group_id'] : $this->config->get('config_customer_group_id')),
            'firstname' => $customer_id ? $customer_info['firstname'] : ($guest && array_key_exists('firstname', $session['guest']) ? $session['guest']['firstname'] : ''),
            'lastname' => $customer_id ? $customer_info['lastname'] : ($guest && array_key_exists('lastname', $session['guest']) ? $session['guest']['lastname'] : ''),
            'email' => $customer_id ? $customer_info['email'] : ($guest && array_key_exists('email', $session['guest']) ? $session['guest']['email'] : ''),
            'telephone' => $customer_id ? $customer_info['telephone'] : ($guest && array_key_exists('telephone', $session['guest']) ? $session['guest']['telephone'] : ''),
            'fax' => $customer_id ? $customer_info['fax'] : ($guest && array_key_exists('fax', $session['guest']) ? $session['guest']['fax'] : ''),
            'custom_field' => $customer_id ? json_decode($customer_info['custom_field'], true) : ($guest && array_key_exists('custom_field', $session['guest']) ? $session['guest']['custom_field'] : ''),

            'payment_firstname' => $payment_address && array_key_exists('firstname', $session['payment_address']) ? $session['payment_address']['firstname'] : '',
            'payment_lastname' => $payment_address && array_key_exists('lastname', $session['payment_address']) ? $session['payment_address']['lastname'] : '',
            'payment_company' => $payment_address && array_key_exists('company', $session['payment_address']) ? $session['payment_address']['company'] : '',
            'payment_company_id' => $payment_address && array_key_exists('payment_company_id', $session['payment_address']) ? $session['payment_address']['payment_company_id'] : '',
            'payment_tax_id' => $payment_address && array_key_exists('payment_tax_id', $session['payment_address']) ? $session['payment_address']['payment_tax_id'] : '',
            'payment_address_1' => $payment_address && array_key_exists('address_1', $session['payment_address']) ? $session['payment_address']['address_1'] : '',
            'payment_address_2' => $payment_address && array_key_exists('address_2', $session['payment_address']) ? $session['payment_address']['address_2'] : '',
            'payment_city' => $payment_address && array_key_exists('city', $session['payment_address']) ? $session['payment_address']['city'] : '',
            'payment_postcode' => $payment_address && array_key_exists('postcode', $session['payment_address']) ? $session['payment_address']['postcode'] : '',
            'payment_country' => $payment_address && array_key_exists('country', $session['payment_address']) ? $session['payment_address']['country'] : '',
            'payment_country_id' => $payment_address && array_key_exists('country_id', $session['payment_address']) ? $session['payment_address']['country_id'] : '',
            'payment_zone' => $payment_address && array_key_exists('zone', $session['payment_address']) ? $session['payment_address']['zone'] : '',
            'payment_zone_id' => $payment_address && array_key_exists('zone_id', $session['payment_address']) ? $session['payment_address']['zone_id'] : '',
            'payment_address_format' => $payment_address_format,
            'payment_custom_field' => $payment_address && array_key_exists('custom_field', $session['payment_address']) ? $session['payment_address']['custom_field'] : array(),
            'payment_method' => $payment_method_title,
            'payment_code' => $payment_method_code,

            'shipping_firstname' => $shipping_address && array_key_exists('firstname', $session['shipping_address']) ? $session['shipping_address']['firstname'] : '',
            'shipping_lastname' => $shipping_address && array_key_exists('lastname', $session['shipping_address']) ? $session['shipping_address']['lastname'] : '',
            'shipping_company' => $shipping_address && array_key_exists('company', $session['shipping_address']) ? $session['shipping_address']['company'] : '',
            'shipping_address_1' => $shipping_address && array_key_exists('address_1', $session['shipping_address']) ? $session['shipping_address']['address_1'] : '',
            'shipping_address_2' => $shipping_address && array_key_exists('address_2', $session['shipping_address']) ? $session['shipping_address']['address_2'] : '',
            'shipping_city' => $shipping_address && array_key_exists('city', $session['shipping_address']) ? $session['shipping_address']['city'] : '',
            'shipping_postcode' => $shipping_address && array_key_exists('postcode', $session['shipping_address']) ? $session['shipping_address']['postcode'] : '',
            'shipping_country' => $shipping_address && array_key_exists('country', $session['shipping_address']) ? $session['shipping_address']['country'] : '',
            'shipping_country_id' => $shipping_address && array_key_exists('country_id', $session['shipping_address']) ? $session['shipping_address']['country_id'] : '',
            'shipping_zone' => $shipping_address && array_key_exists('zone', $session['shipping_address']) ? $session['shipping_address']['zone'] : '',
            'shipping_zone_id' => $shipping_address && array_key_exists('zone_id', $session['shipping_address']) ? $session['shipping_address']['zone_id'] : '',
            'shipping_address_format' => $shipping_address_format,
            'shipping_custom_field' => $shipping_address && array_key_exists('custom_field', $session['shipping_address']) ? $session['shipping_address']['custom_field'] : array(),
            'shipping_method' => $shipping_method_title,
            'shipping_code' => $shipping_method_code,

            'comment' => array_key_exists('comment', $session) ? $session['comment'] : '',
            'affiliate_id' => 0,
            'commission' => 0,
            'marketing_id' => 0,
            'tracking' => '',
            'language_id' => $this->config->get('config_language_id'),
            'currency_id' => $this->currency->getId($this->session->data['currency']),
            'currency_code' => $this->session->data['currency'],
            'currency_value' => $this->currency->getValue($this->session->data['currency']),
            'ip' => $this->request->server['REMOTE_ADDR'],
            'forwarded_ip' => !empty($this->request->server['HTTP_X_FORWARDED_FOR']) ? $this->request->server['HTTP_X_FORWARDED_FOR'] : (!empty($this->request->server['HTTP_CLIENT_IP']) ? $this->request->server['HTTP_CLIENT_IP'] : ''),
            'user_agent' => isset($this->request->server['HTTP_USER_AGENT']) ? $this->request->server['HTTP_USER_AGENT'] : '',
            'accept_language' => isset($this->request->server['HTTP_ACCEPT_LANGUAGE']) ? $this->request->server['HTTP_ACCEPT_LANGUAGE'] : ''
        );

        //<editor-fold desc="Get order totals">
            if(version_compare(VERSION, '2.3.0.2', '>=')) {
                $totals = array();
                $taxes = $this->cart->getTaxes();
                $total = 0;

                $total_data = array(
                    'totals' => &$totals,
                    'taxes'  => &$taxes,
                    'total'  => &$total
                );
            } else {
                $order_data['totals'] = array();
                $total = 0;
                $taxes = $this->cart->getTaxes();
            }

            $sort_order = array();

            $results = $this->{$this->model_extension_name}->getExtensions('total');

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

            array_multisort($sort_order, SORT_ASC, $results);

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

                    if(version_compare(VERSION, '2.2', '<'))
                        $this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
                    else
                        $this->{$this->model_name.'total_' . $result['code']}->getTotal($total_data);
                }
            }

            $sort_order = array();

            $final_totals = version_compare(VERSION, '2.2', '<') ? $total_data : $totals;

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

            array_multisort($sort_order, SORT_ASC, $final_totals);

            $order_data['totals'] = $final_totals;
        //</editor-fold>

        $order_data['total'] = version_compare(VERSION, '2.2', '<') ? $total : $total_data['total'];

        $order_data['products'] = array();

        foreach ($this->cart->getProducts() as $product) {
            $option_data = array();

            foreach ($product['option'] as $option) {
                $option_data[] = array(
                    'product_option_id'       => $option['product_option_id'],
                    'product_option_value_id' => $option['product_option_value_id'],
                    'option_id'               => $option['option_id'],
                    'option_value_id'         => $option['option_value_id'],
                    'name'                    => $option['name'],
                    'value'                   => array_key_exists('value', $option) ? $option['value'] : (array_key_exists('option_value', $option) ? $option['option_value'] : ''),
                    'type'                    => $option['type']
                );
            }

            $order_data['products'][] = array(
                'product_id' => $product['product_id'],
                'name'       => $product['name'],
                'model'      => $product['model'],
                'option'     => $option_data,
                'download'   => $product['download'],
                'quantity'   => $product['quantity'],
                'subtract'   => $product['subtract'],
                'price'      => $product['price'],
                'total'      => $product['total'],
                'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
                'reward'     => $product['reward']
            );
        }

        // Gift Voucher
        $order_data['vouchers'] = array();

        if (!empty($this->session->data['vouchers'])) {
            foreach ($this->session->data['vouchers'] as $voucher) {
                $order_data['vouchers'][] = array(
                    'description'      => $voucher['description'],
                    'code'             => token(10),
                    'to_name'          => $voucher['to_name'],
                    'to_email'         => $voucher['to_email'],
                    'from_name'        => $voucher['from_name'],
                    'from_email'       => $voucher['from_email'],
                    'voucher_theme_id' => $voucher['voucher_theme_id'],
                    'message'          => $voucher['message'],
                    'amount'           => $voucher['amount']
                );
            }
        }

        $this->load->model('checkout/order');

        if(!array_key_exists('order_id', $this->session->data) || empty($this->session->data['order_id']))
            $this->session->data['order_id'] = $this->model_checkout_order->addOrder($order_data);
        else {
            $this->model_checkout_order->editOrder($this->session->data['order_id'], $order_data, true);
        }
    }

    public function get_customer_groups(){
        $this->load->model('account/customer_group');
        $cg = $this->model_account_customer_group->getCustomerGroups();
        $cg_formatted = $this->format_to_select($cg, 'customer_group');
        return $cg_formatted;
    }
    public function generate_input($input, $key_session_address = '')
    {
        $html_input = '';

        $label = !empty($input['label'][$this->language_id]) ? $input['label'][$this->language_id] : '';
        $placeholder = !empty($input['placeholder'][$this->language_id]) ? $input['placeholder'][$this->language_id] : '';
        $error_message = !empty($input['error_message'][$this->language_id]) ? $input['error_message'][$this->language_id] : '';
        $validation_rule = !empty($input['validation_rule']) ? ' data-validationrule="'.$input['validation_rule'].'"' : '';
        $input_name = !empty($input['name']) ? $input['name'] : '';
        $type = !empty($input['type']) ? $input['type'] : 'text';
        $var_options = !empty($input['var_options']) ? $input['var_options'] : '';
        $onchange = !empty($input['onchange']) ? ' onchange="'.$input['onchange'].'"' : '';
        $default_value = !empty($input['default_value']) ? $input['default_value'] : '';
        $value = !empty($input['value']) ? $input['value'] : '';
        $options = !empty($input['options']) ? $input['options'] : array();
        $custom_field = !empty($input['custom_field']);
        $time_types = array('date','time','datetime');

        $is_checkbox = !$custom_field && $type == 'checkbox';
        $is_custom_checkbox = $custom_field && $type == 'checkbox';

        $col_span = $is_checkbox ? 12 : $this->_get_form_span();

        if($is_checkbox && !empty($input['name']) && $input['name'] == 'agree_privacy_policy' && $this->config->get('config_account_id'))
        {
            $this->load->model('catalog/information');

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

            if(!empty($information_info))
            {
                $label_text = $input['label'][$this->language_id];

                $from_modal_id = $input['type_customer'] == 'register' ? 'modal_register' : 'modal_billing_address';

                $label_text = str_replace('[link]', '<a href="javascript:{}" onclick="$(\'div.remodal.privacy_policy\').removeAttr(\'data-frommodal\');'.($this->config->get('poc_modals_in_forms') ? '$(\'div.remodal.privacy_policy\').data(\'frommodal\', \''.$from_modal_id.'\');' : '').'" data-remodal-target="modal_privacy_policy">', $label_text);
                $label_text = str_replace('[/link]', '</a>', $label_text);

                $label = $label_text;
            }
        }

        $html_input .= '<div class="poc_col-md-'.$col_span.'">';
        $html_input .= '<div class="poc_form-group'.(!empty($validation_rule) ? ' poc_required':'').($custom_field ? ' custom_field' : '').'">';
        if($is_checkbox) $html_input .= '<div class="checkbox">';
        if(!empty($label))
            $html_input .= '<label class="poc_control-label" for="'.$input_name.'">{here_checkbox}'.$label.'</label>';

        if($type == 'text')
        {
            $extra_class = in_array($input_name, array('address_1')) ? $key_session_address.'_'.$input_name : '';
            $id = in_array($input_name, array('address_1')) ? $this->_generate_random_string(5) : '';
            $html_input .= '<input '.(!empty($id) ? ' id="'.$id.'"' : '').' class="poc_form-control'.(!empty($extra_class) ? ' '.$extra_class : '').'" placeholder="'.$placeholder.'" name="'.$input_name.'" value="'.$value.'" type="text"'.$validation_rule.'>';
        }
        elseif($type == 'password')
        {
            $html_input .= '<input class="poc_form-control" placeholder="'.$placeholder.'" name="'.$input_name.'" value="'.$value.'" type="password"'.$validation_rule.'>';
        }
        elseif($type == 'select')
        {
            $html_input .= '<select class="poc_form-control" placeholder="'.$placeholder.'" name="'.$input_name.'"'.$onchange.$validation_rule.'>';
            $html_input .= '<option value="">'.$placeholder.'</option>';

            if(!empty($var_options))
            {
                foreach ($this->{$var_options} as $id => $name) {
                    $html_input .= '<option'.(in_array($id, array($default_value, $value)) ? ' selected="selected"':'').' value="'.$id.'">'.$name.'</option>';
                }
            }

            if(!empty($options))
            {
                foreach ($options as $id => $name) {
                    $html_input .= '<option'.(in_array($id, array($default_value, $value)) ? ' selected="selected"':'').' value="'.$id.'">'.$name.'</option>';
                }
            }
            $html_input .= '</select>';
        }
        elseif($type == 'radio' || $is_custom_checkbox)
        {
            if(empty($options) && !empty($var_options))
                $options = $this->{$var_options};

            $html_input .= '<div style="clear:both;"></div>';
            if(!empty($options))
            {
                $first_inserted = true;

                foreach ($options as $id => $name)
                {
                    if(is_array($value))
                        $checked = in_array($id, $value);
                    else
                        $checked = in_array($id, array($default_value, $value));

                    $html_input .= '<label class="'.$type.'-inline"><input type="'.$type.'" name="'.$input_name.($is_custom_checkbox ? '[]' : '').'"'.($checked ? ' checked':'').' value="'.$id.'"'.($first_inserted ? $validation_rule : '').'>'.$name.'</label>';

                    $first_inserted = false;
                }
            }
            $html_input = str_replace('{here_checkbox}', '', $html_input);
        }
        elseif($is_checkbox)
        {
            $checkbox = '<input value="1" name="'.$input_name.'" '.(!empty($default_value) || !empty($value) ? 'checked="checked" ':'').'type="checkbox"'.$validation_rule.'>';
            $html_input = str_replace('{here_checkbox}', $checkbox, $html_input);
        }
        elseif($type == 'textarea')
        {
            $html_input .= '<textarea class="poc_form-control" placeholder="'.$placeholder.'" name="'.$input_name.'" value="'.$value.'"'.$validation_rule.'></textarea>';
        }
        elseif(in_array($type, $time_types))
        {
            if($type == 'date')
            {
                $date_format = 'YYYY-MM-DD';
                $div_class = 'date';
            }
            elseif($type == 'datetime')
            {
                $date_format = 'YYYY-MM-DD HH:mm';
                $div_class = 'datetime';
            }
            elseif($type == 'time')
            {
                $date_format = 'HH:mm';
                $div_class = 'time';
            }
            $html_input .= '<div style="clear:both;"></div><div class="input-group '.$div_class.'">';
            $html_input .= '<input class="poc_form-control" placeholder="'.$placeholder.'" name="'.$input_name.'" value="'.$value.'" type="text"'.$validation_rule.' data-date-format="'.$date_format.'">';
            $html_input .= '<span class="input-group-btn"><button class="poc_btn poc_btn-default" type="button"><i class="fa fa-calendar"></i></button></span>';
            $html_input .= '</div>';
        }

        if($type != "checkbox")
            $html_input = str_replace('{here_checkbox}', '', $html_input);

        if(!empty($error_message))
            $html_input .= '<div style="clear:both;"></div><span class="error_message">'.$error_message.'</span>';
        if($is_checkbox) $html_input .= '</div>';
        $html_input .= '</div>';
        $html_input .= '</div>';

        return $html_input;
    }

    public function format_to_select($datas, $name)
    {
        $final_datas = array();
        foreach ($datas as $key => $co) {
            $final_datas[$co[$name.'_id']] = $co['name'];
        }
        return $final_datas;
    }

    public function format_addresses($addresses)
    {
        $final_addresses = array();
        foreach ($addresses as $key => $address) {
            $final_addresses[$address['address_id']] = $address['firstname'].' '.$address['lastname'].' - '.$address['address_1'].', '.$address['postcode'].', '.$address['city'].', '.$address['zone'];
        }
        return $final_addresses;
    }

    public function get_layout_vars()
    {
        $config_name = 'poc_layout'.($this->customer->isLogged() ? '_logged' : '');
        $can_disable = array('identification', 'cart');
        $layout = $this->config->get($config_name);
        $columns = $this->config->get($config_name.'_columns');
        $colspan_1 = $this->config->get($config_name.'_columns_size_1');
        $colspan_2 = $this->config->get($config_name.'_columns_size_2');
        $colspan_3 = $this->config->get($config_name.'_columns_size_3');

        $script_vars = '<script type="text/javascript">';
        $script_vars .= 'var layout_columns = '.$columns.';';
        $script_vars .= 'var layout_colspans = [1,2,3];';
        $script_vars .= 'layout_colspans[1] = '.$colspan_1.';';
        $script_vars .= 'layout_colspans[2] = '.$colspan_2.';';
        $script_vars .= 'layout_colspans[3] = '.$colspan_3.';';

        $script_vars .= 'var panels = [';
        foreach ($layout as $key => $val) {
            $script_vars .= '"'.$key.'",';
        }
        $script_vars = rtrim($script_vars,",");
        $script_vars .= '];';

        foreach ($layout as $key => $val) {
            $script_vars .= 'panels["'.$key.'"] = [];';
            $script_vars .= 'panels["'.$key.'"]["status"] = '.(empty($val['status']) && in_array($key, $can_disable)  ? 0 : 1).';';
            $script_vars .= 'panels["'.$key.'"]["colspan"] = '.$val['cols'].';';
            $script_vars .= 'panels["'.$key.'"]["col"] = '.$val['col_position'].';';
        }
        $script_vars .= '</script>';

        return $script_vars;
    }

    public function get_styles()
    {
        $css_code = '';
        $css_code .= 'div.perfect_one_checkout_main_container .panel_poc>.panel_poc-heading{background:#'.$this->config->get('poc_style_panel_heading_background').';color:#'.$this->config->get('poc_style_panel_heading_font_color').';}';
        $css_code .= 'div.perfect_one_checkout_main_container .panel_poc{border-color:#'.$this->config->get('poc_style_panel_heading_border_color').';}';

        $css_code .= 'div.perfect_one_checkout_main_container div.panel_container.error div.panel div.panel_poc-heading{background:#'.$this->config->get('poc_style_panel_heading_background_error').';color:#'.$this->config->get('poc_style_panel_heading_font_color_error').';}';
        $css_code .= 'div.perfect_one_checkout_main_container div.panel_container.error div.panel{border-color:#'.$this->config->get('poc_style_panel_heading_border_color_error').';}';

        $btn_default = 'div.perfect_one_checkout_main_container button.btn.btn-default{background: #fbfbfb;background: -moz-linear-gradient(top, #fbfbfb 0%, #e6e7e7 100%);background: -webkit-linear-gradient(top, #fbfbfb 0%,#e6e7e7 100%);background: linear-gradient(to bottom, #fbfbfb 0%,#e6e7e7 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#fbfbfb\', endColorstr=\'#e6e7e7\',GradientType=0 );}';
        $btn_default = str_replace('fbfbfb', $this->config->get('poc_style_buttons_default_background_top'), $btn_default);
        $btn_default = str_replace('e6e7e7', $this->config->get('poc_style_buttons_default_background_bottom'), $btn_default);
        $css_code .= $btn_default;

        $css_code .= 'div.perfect_one_checkout_main_container button.btn.btn-default{color:'.'#'.$this->config->get('poc_style_buttons_default_font_color').';border-color:'.'#'.$this->config->get('poc_style_buttons_default_border_color').'}';
        $css_code .= 'div.perfect_one_checkout_main_container button.btn.btn-default:hover{color:'.'#'.$this->config->get('poc_style_buttons_default_font_color_hover').';border-color:'.'#'.$this->config->get('poc_style_buttons_default_border_color').'}';

        $btn_confirm_order = 'div.panel_confirm a.confirm_order_button,
                                div.panel_confirm a.confirm_register_button,
                                div.panel_confirm div.payment_info #button-confirm,
                                div.panel_confirm div.payment_info input[type="submit"]';
        if($this->config->get('poc_style_panel_confirm_buttons_selectors'))
            $btn_confirm_order .= ','.$this->config->get('poc_style_panel_confirm_buttons_selectors');
                                $btn_confirm_order .= '{
                                    display: block;
                                    width: 100%;
                                    font-weight: bold;
                                    font-size: 16px;
                                    color: #fff;
                                    border-color: #1f90bb;
                                    text-shadow: none;
                                    background: #23a0d0;
                                    background: -moz-linear-gradient(top, #23a0d0 0%, #1f90bb 100%);
                                    background: -webkit-linear-gradient(top, #23a0d0 0%,#1f90bb 100%);
                                    background: linear-gradient(to bottom, #23a0d0 0%,#1f90bb 100%);
                                    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#23a0d0\', endColorstr=\'#1f90bb\',GradientType=0 );
                                }';
        $btn_confirm_order = str_replace('23a0d0', $this->config->get('poc_style_buttons_confirm_order_background_top'), $btn_confirm_order);
        $btn_confirm_order = str_replace('1f90bb', $this->config->get('poc_style_buttons_confirm_order_background_bottom'), $btn_confirm_order);
        $css_code .= $btn_confirm_order;

        $css_code .= 'div.perfect_one_checkout_main_container a.poc_btn.confirm_order_button{color:'.'#'.$this->config->get('poc_style_buttons_confirm_order_font_color').';border-color:'.'#'.$this->config->get('poc_style_buttons_confirm_order_border_color').'}';
        $css_code .= 'div.perfect_one_checkout_main_container a.poc_btn.confirm_order_button:hover{color:'.'#'.$this->config->get('poc_style_buttons_confirm_order_font_color_hover').';border-color:'.'#'.$this->config->get('poc_style_buttons_confirm_order_border_color').'}';

        $btn_active = 'div.perfect_one_checkout_main_container div.panel_identification div.panel_poc div.panel_poc-body div.btn-group button.btn[disabled]{background: #23a0d0;background: -moz-linear-gradient(top, #23a0d0 0%, #1f90bb 100%);background: -webkit-linear-gradient(top, #23a0d0 0%,#1f90bb 100%);background: linear-gradient(to bottom, #23a0d0 0%,#1f90bb 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#23a0d0\', endColorstr=\'#1f90bb\',GradientType=0 );}';
        $btn_active = str_replace('23a0d0', $this->config->get('poc_style_buttons_active_background_top'), $btn_active);
        $btn_active = str_replace('1f90bb', $this->config->get('poc_style_buttons_active_background_bottom'), $btn_active);
        $css_code .= $btn_active;

        $css_code .= 'div.perfect_one_checkout_main_container div.panel_identification div.panel_poc div.panel_poc-body div.poc_btn-group button.btn[disabled]{color:'.'#'.$this->config->get('poc_style_buttons_active_font_color').';border-color:'.'#'.$this->config->get('poc_style_buttons_active_border_color').'}';
        $css_code .= 'div.perfect_one_checkout_main_container div.panel_identification div.panel_poc div.panel_poc-body div.poc_btn-group button.btn[disabled]:hover{color:'.'#'.$this->config->get('poc_style_buttons_active_font_color_hover').';border-color:'.'#'.$this->config->get('poc_style_buttons_active_border_color').'}';

        $css_code .= 'div.poc_steps div.step,div.poc_steps div.step::after{background-color:#'.$this->config->get('style_steps_default_background_color').';border-color:#'.$this->config->get('style_steps_default_border_color').';color:#'.$this->config->get('style_steps_default_font_color').';}div.poc_steps div.step span.number{color:#'.$this->config->get('style_steps_default_number_color').';}';

        $css_code .= 'div.poc_steps div.step span.number{color:#'.$this->config->get('poc_style_steps_default_number_color').';}';

        $css_code .= 'div.poc_steps div.step.error,div.poc_steps div.step.error::after{background-color:#'.$this->config->get('poc_style_steps_error_background_color').';border-color:#'.$this->config->get('poc_style_steps_error_border_color').';color:#'.$this->config->get('poc_style_steps_error_font_color').';}div.poc_steps div.step.error::after{background-color:#'.$this->config->get('poc_style_steps_error_background_color').';}';
        $css_code .= 'div.poc_steps div.step.error span.number{color:#'.$this->config->get('poc_style_steps_error_number_color').';}';

        $css_code .= 'div.poc_steps div.step.completed,div.poc_steps div.step.completed::after{background-color:#'.$this->config->get('poc_style_steps_completed_background_color').';border-color:#'.$this->config->get('poc_style_steps_completed_border_color').';color:#'.$this->config->get('poc_style_steps_completed_font_color').';}div.poc_steps div.step.completed::after{background-color:#'.$this->config->get('poc_style_steps_completed_background_color').';}';
        $css_code .= 'div.poc_steps div.step.completed span.number{color:#'.$this->config->get('poc_style_steps_completed_number_color').';}';

        $css_code .= 'div.poc_steps{box-shadow:0px 0px 0px 3px #'.$this->config->get('poc_style_steps_outborder_color').';}';

        $css_code .= 'div.panel_cart div.discount_zone div.discount_container div.icons span,div.panel_cart div.discount_zone div.discount_container div.icons i{color: #'.$this->config->get('poc_style_discount_zone_icon_color').';}';
        $css_code .= 'div.panel_cart div.discount_zone div.discount_container{background: #'.$this->config->get('poc_style_discount_zone_background').';}';

        $css_code .= 'div.perfect_one_checkout_main_container div.panel_confirm .panel_poc{box-shadow: 0px 0px 0px 4px #'.$this->config->get('poc_style_panel_confirm_outborder_color').'}';

        $css_code .= is_numeric($this->config->get('poc_design_container_max_width')) ? 'div.poc_container{ max-width: '.$this->config->get('poc_design_container_max_width').'px !important;}' : '';
        $css_code .= $this->config->get('poc_design_container_remove_padding') ? 'div.poc_container{ padding-left: 0px !important; padding-right: 0px !important; }' : '';

        return $css_code;
    }

    public function get_custom_field_info($custom_field_id)
    {
        foreach ($this->custom_fields as $key => $custom_field) {
            if($custom_field['custom_field_id'] == $custom_field_id)
                return $custom_field;
        }
        return false;
    }

    public function sign_in_facebook_get_link()
    {
        $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();

        $permissions = array('email', 'user_hometown', 'user_location');

        $loginUrl = $helper->getLoginUrl(HTTPS_SERVER.'index.php?route=extension/module/perfect_one_checkout/sign_in_facebook_call_back', $permissions);

        return htmlspecialchars($loginUrl);
    }

    public function sign_in_paypal_get_code() {
        $code = '
            <script src=\'https://www.paypalobjects.com/js/external/api.js\'></script>
            <script>
                paypal.use( [\'login\'], function (login) {
                    login.render ({
                        "appid":"'.$this->config->get('poc_sign_in_paypal_app_id').'",
                        "scopes":"profile email address phone https://uri.paypal.com/services/paypalattributes",
                        "containerid":"poc_sign_in_paypal",
                        "locale":"'.$this->config->get('poc_sign_in_paypal_locale').'",
                        "theme":"neutral",
                        "returnurl":"'.HTTPS_SERVER.'index.php?route=extension/module/perfect_one_checkout/sing_in_paypal_call_back"
                    });
                });
            </script> 
        ';

        return $code;
    }

    public function sign_in_linkedin_get_link()
    {
        $client_id = $this->config->get('poc_sign_in_linkedin_client_id');
        $callback_url = urlencode(HTTPS_SERVER.'index.php?route=extension/module/perfect_one_checkout/sign_in_linkedin_call_back');
        $state = $this->_generate_random_string(21);
        $this->session->data['oauth2state'] = $state;
        $link = 'https://www.linkedin.com/oauth/v2/authorization?response_type=code&state='.$state.'&client_id='.$client_id.'&redirect_uri='.$callback_url.'&scope=r_basicprofile%20r_emailaddress';
        return $link;
    }

    function _generate_random_string($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    function _get_form_span() {
        $modals_enabled = $this->config->get('poc_modals_in_forms');

        if($modals_enabled || $this->customer->isLogged())
            return 4;

        $layout_config = $this->config->get('poc_layout');
        $panel_span = $layout_config['addresses']['cols'];
        $panel_col_number = $layout_config['addresses']['col_position'];
        $col_span = $this->config->get('poc_layout_columns_size_'.$panel_col_number);
        $span = in_array($col_span, array(8, 12)) && $panel_span == 12 ? 3 : 6;

        return $span;
    }

    public function _get_country_id($country_name, $iso_code_2 = '') {
        $iso_code_2 = !empty($iso_code_2) ? strtoupper($iso_code_2) : '';

        $countries = array
        (
            'Afghanistan' => 'AF',
            'Aland Islands' => 'AX',
            'Albania' => 'AL',
            'Algeria' => 'DZ',
            'American Samoa' => 'AS',
            'Andorra' => 'AD',
            'Angola' => 'AO',
            'Anguilla' => 'AI',
            'Antarctica' => 'AQ',
            'Antigua And Barbuda' => 'AG',
            'Argentina' => 'AR',
            'Armenia' => 'AM',
            'Aruba' => 'AW',
            'Australia' => 'AU',
            'Austria' => 'AT',
            'Azerbaijan' => 'AZ',
            'Bahamas' => 'BS',
            'Bahrain' => 'BH',
            'Bangladesh' => 'BD',
            'Barbados' => 'BB',
            'Belarus' => 'BY',
            'Belgium' => 'BE',
            'Belize' => 'BZ',
            'Benin' => 'BJ',
            'Bermuda' => 'BM',
            'Bhutan' => 'BT',
            'Bolivia' => 'BO',
            'Bosnia And Herzegovina' => 'BA',
            'Botswana' => 'BW',
            'Bouvet Island' => 'BV',
            'Brazil' => 'BR',
            'British Indian Ocean Territory' => 'IO',
            'Brunei Darussalam' => 'BN',
            'Bulgaria' => 'BG',
            'Burkina Faso' => 'BF',
            'Burundi' => 'BI',
            'Cambodia' => 'KH',
            'Cameroon' => 'CM',
            'Canada' => 'CA',
            'Cape Verde' => 'CV',
            'Cayman Islands' => 'KY',
            'Central African Republic' => 'CF',
            'Chad' => 'TD',
            'Chile' => 'CL',
            'China' => 'CN',
            'Christmas Island' => 'CX',
            'Cocos (Keeling) Islands' => 'CC',
            'Colombia' => 'CO',
            'Comoros' => 'KM',
            'Congo' => 'CG',
            'Congo, Democratic Republic' => 'CD',
            'Cook Islands' => 'CK',
            'Costa Rica' => 'CR',
            'Cote D\'Ivoire' => 'CI',
            'Croatia' => 'HR',
            'Cuba' => 'CU',
            'Cyprus' => 'CY',
            'Czech Republic' => 'CZ',
            'Denmark' => 'DK',
            'Djibouti' => 'DJ',
            'Dominica' => 'DM',
            'Dominican Republic' => 'DO',
            'Ecuador' => 'EC',
            'Egypt' => 'EG',
            'El Salvador' => 'SV',
            'Equatorial Guinea' => 'GQ',
            'Eritrea' => 'ER',
            'Estonia' => 'EE',
            'Ethiopia' => 'ET',
            'Falkland Islands (Malvinas)' => 'FK',
            'Faroe Islands' => 'FO',
            'Fiji' => 'FJ',
            'Finland' => 'FI',
            'France' => 'FR',
            'French Guiana' => 'GF',
            'French Polynesia' => 'PF',
            'French Southern Territories' => 'TF',
            'Gabon' => 'GA',
            'Gambia' => 'GM',
            'Georgia' => 'GE',
            'Germany' => 'DE',
            'Ghana' => 'GH',
            'Gibraltar' => 'GI',
            'Greece' => 'GR',
            'Greenland' => 'GL',
            'Grenada' => 'GD',
            'Guadeloupe' => 'GP',
            'Guam' => 'GU',
            'Guatemala' => 'GT',
            'Guernsey' => 'GG',
            'Guinea' => 'GN',
            'Guinea-Bissau' => 'GW',
            'Guyana' => 'GY',
            'Haiti' => 'HT',
            'Heard Island & Mcdonald Islands' => 'HM',
            'Holy See (Vatican City State)' => 'VA',
            'Honduras' => 'HN',
            'Hong Kong' => 'HK',
            'Hungary' => 'HU',
            'Iceland' => 'IS',
            'India' => 'IN',
            'Indonesia' => 'ID',
            'Iran, Islamic Republic Of' => 'IR',
            'Iraq' => 'IQ',
            'Ireland' => 'IE',
            'Isle Of Man' => 'IM',
            'Israel' => 'IL',
            'Italy' => 'IT',
            'Jamaica' => 'JM',
            'Japan' => 'JP',
            'Jersey' => 'JE',
            'Jordan' => 'JO',
            'Kazakhstan' => 'KZ',
            'Kenya' => 'KE',
            'Kiribati' => 'KI',
            'Korea' => 'KR',
            'Kuwait' => 'KW',
            'Kyrgyzstan' => 'KG',
            'Lao People\'s Democratic Republic' => 'LA',
            'Latvia' => 'LV',
            'Lebanon' => 'LB',
            'Lesotho' => 'LS',
            'Liberia' => 'LR',
            'Libyan Arab Jamahiriya' => 'LY',
            'Liechtenstein' => 'LI',
            'Lithuania' => 'LT',
            'Luxembourg' => 'LU',
            'Macao' => 'MO',
            'Macedonia' => 'MK',
            'Madagascar' => 'MG',
            'Malawi' => 'MW',
            'Malaysia' => 'MY',
            'Maldives' => 'MV',
            'Mali' => 'ML',
            'Malta' => 'MT',
            'Marshall Islands' => 'MH',
            'Martinique' => 'MQ',
            'Mauritania' => 'MR',
            'Mauritius' => 'MU',
            'Mayotte' => 'YT',
            'Mexico' => 'MX',
            'Micronesia, Federated States Of' => 'FM',
            'Moldova' => 'MD',
            'Monaco' => 'MC',
            'Mongolia' => 'MN',
            'Montenegro' => 'ME',
            'Montserrat' => 'MS',
            'Morocco' => 'MA',
            'Mozambique' => 'MZ',
            'Myanmar' => 'MM',
            'Namibia' => 'NA',
            'Nauru' => 'NR',
            'Nepal' => 'NP',
            'Netherlands' => 'NL',
            'Netherlands Antilles' => 'AN',
            'New Caledonia' => 'NC',
            'New Zealand' => 'NZ',
            'Nicaragua' => 'NI',
            'Niger' => 'NE',
            'Nigeria' => 'NG',
            'Niue' => 'NU',
            'Norfolk Island' => 'NF',
            'Northern Mariana Islands' => 'MP',
            'Norway' => 'NO',
            'Oman' => 'OM',
            'Pakistan' => 'PK',
            'Palau' => 'PW',
            'Palestinian Territory, Occupied' => 'PS',
            'Panama' => 'PA',
            'Papua New Guinea' => 'PG',
            'Paraguay' => 'PY',
            'Peru' => 'PE',
            'Philippines' => 'PH',
            'Pitcairn' => 'PN',
            'Poland' => 'PL',
            'Portugal' => 'PT',
            'Puerto Rico' => 'PR',
            'Qatar' => 'QA',
            'Reunion' => 'RE',
            'Romania' => 'RO',
            'Russian Federation' => 'RU',
            'Rwanda' => 'RW',
            'Saint Barthelemy' => 'BL',
            'Saint Helena' => 'SH',
            'Saint Kitts And Nevis' => 'KN',
            'Saint Lucia' => 'LC',
            'Saint Martin' => 'MF',
            'Saint Pierre And Miquelon' => 'PM',
            'Saint Vincent And Grenadines' => 'VC',
            'Samoa' => 'WS',
            'San Marino' => 'SM',
            'Sao Tome And Principe' => 'ST',
            'Saudi Arabia' => 'SA',
            'Senegal' => 'SN',
            'Serbia' => 'RS',
            'Seychelles' => 'SC',
            'Sierra Leone' => 'SL',
            'Singapore' => 'SG',
            'Slovakia' => 'SK',
            'Slovenia' => 'SI',
            'Solomon Islands' => 'SB',
            'Somalia' => 'SO',
            'South Africa' => 'ZA',
            'South Georgia And Sandwich Isl.' => 'GS',
            'Spain' => 'ES',
            'Sri Lanka' => 'LK',
            'Sudan' => 'SD',
            'Suriname' => 'SR',
            'Svalbard And Jan Mayen' => 'SJ',
            'Swaziland' => 'SZ',
            'Sweden' => 'SE',
            'Switzerland' => 'CH',
            'Syrian Arab Republic' => 'SY',
            'Taiwan' => 'TW',
            'Tajikistan' => 'TJ',
            'Tanzania' => 'TZ',
            'Thailand' => 'TH',
            'Timor-Leste' => 'TL',
            'Togo' => 'TG',
            'Tokelau' => 'TK',
            'Tonga' => 'TO',
            'Trinidad And Tobago' => 'TT',
            'Tunisia' => 'TN',
            'Turkey' => 'TR',
            'Turkmenistan' => 'TM',
            'Turks And Caicos Islands' => 'TC',
            'Tuvalu' => 'TV',
            'Uganda' => 'UG',
            'Ukraine' => 'UA',
            'United Arab Emirates' => 'AE',
            'United Kingdom' => 'GB',
            'United States' => 'US',
            'United States Outlying Islands' => 'UM',
            'Uruguay' => 'UY',
            'Uzbekistan' => 'UZ',
            'Vanuatu' => 'VU',
            'Venezuela' => 'VE',
            'Viet Nam' => 'VN',
            'Virgin Islands, British' => 'VG',
            'Virgin Islands, U.S.' => 'VI',
            'Wallis And Futuna' => 'WF',
            'Western Sahara' => 'EH',
            'Yemen' => 'YE',
            'Zambia' => 'ZM',
            'Zimbabwe' => 'ZW'
        );

        if(array_key_exists($country_name, $countries) || !empty($iso_code_2))
        {
            $iso_code_2 = !empty($iso_code_2) ? $iso_code_2 : $countries[$country_name];
            $country = $this->db->query('SELECT * FROM '.DB_PREFIX.'country WHERE iso_code_2 = "'.$iso_code_2.'"');

            if($country->num_rows > 0 && array_key_exists('country_id', $country->row))
                return $country->row['country_id'];

        }
        return '';
    }

    public function _get_first_zone_id($country_id) {
        $zone = $this->db->query("SELECT zone_id FROM ".DB_PREFIX."zone WHERE country_id = ".$country_id." LIMIT 1");

        return $zone->num_rows ? $zone->row['zone_id'] : '';
    }

    public function _get_zone_id($country_id, $zone_name, $byCode = false){
    	if($byCode) {
    		$filter = '`code` LIKE "%'.$zone_name.'%"';
    	} else {
    		$filter = '`name` LIKE "%'.$zone_name.'%"';
    	}

        $zone = $this->db->query('SELECT * FROM '.DB_PREFIX.'zone WHERE country_id = '.$country_id.' AND '.$filter);
        if($zone->num_rows > 0 && array_key_exists('zone_id', $zone->row))
            return $zone->row['zone_id'];
        return '';
    }
}
?>