# makecommerce/1.0.2/makecommerce.php

MakeCommerce for WooCommerce, version 1.0.2. 2,093 lines.

- Page: https://pluginprobe.com/plugins/makecommerce/1.0.2/code/makecommerce.php
- Raw: https://pluginprobe.com/plugins/makecommerce/1.0.2/raw/makecommerce.php
- Modified: 2016-07-13T08:05:00+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/makecommerce/1.0.2/code/makecommerce.php#L10-L20`.

```php
<?php
/*
	Plugin Name: MakeCommerce for WooCommerce
	Description: Adds MakeCommerce payment gateway and Itella/Omniva parcel machine shipping methods to Woocommerce checkout
	Version: 1.0.2
	Author: Maksekeskus AS
	Author URI: https://MakeCommerce.net/
	Text Domain: wc_makecommerce_domain
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

	global $mkDbTable;
	$mkDbTable = 'mc_banklinks';

	function mc_install() {
		global $wpdb;
		global $mkDbTable;
		
		$tableName = $wpdb->prefix . $mkDbTable;
			
		$charset = $wpdb->get_charset_collate();
		
		$sql = "CREATE TABLE $tableName (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			type varchar(10) NOT NULL,
			country char(2) NOT NULL,
			name varchar(25) NOT NULL,
			url varchar(250) NOT NULL,
			UNIQUE KEY id (id)
		) $charset;";
		
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
		dbDelta( $sql );
	}

	register_activation_hook( __FILE__, 'mc_install' );

	if (!class_exists('wc_makecommerce_domain')) {
		require_once('includes/Api.php');
	}

	function woocommerce_payment_makecommerce_init() {
		load_plugin_textdomain('wc_makecommerce_domain', false, dirname(plugin_basename(__FILE__)) . '/');
		
		
		class woocommerce_makecommerce extends WC_Payment_Gateway {
			
			const MC_CANCELLED = 'CANCELLED';
			const MC_COMPLETED = 'COMPLETED';
			const MC_DEPOSITED = 'DEPOSITED';
			
			const MC_PART_REFUNDED = 'PART_REFUNDED';
			const MC_REFUNDED = 'REFUNDED';
			
			const module_name = 'MakeCommerce';
			const api_url = 'https://api.maksekeskus.ee/v1/';
			const gateway_url = 'https://payment.maksekeskus.ee/pay/1/signed.html';
			const gateway_url_static = 'https://payment.maksekeskus.ee/checkout/dist/';
			const fo_url = 'https://merchant.maksekeskus.ee/';
			const test_api_url = 'https://api-test.maksekeskus.ee/v1/';
			const test_gateway_url = 'https://payment-test.maksekeskus.ee/pay/1/signed.html';
			const test_gateway_url_static = 'https://payment-test.maksekeskus.ee/checkout/dist/';
			const test_fo_url = 'https://merchant-test.maksekeskus.ee/';
			const billing_descriptor_dba = '';		
			const currencies_allowed = 'EUR';
			const module_homepage_url = 'https://maksekeskus.ee/en/integration-modules/makecommerce-woocommerce-payment-plugin/';
			const testenv_homepage_url = 'http://maksekeskus.ee/en/for-developers/test-environment/';
			
			public $id = 'makecommerce';
			public $version = '1.1';
			
			public $return_url;
			public $return_url_cancel;
			
			public $return_url_cc;
			
			protected $_shop_id;
			protected $_api_key_secret;
			protected $_api_key_public;
			
			protected $_gateway_url_static;
			
			protected $_banklinks = array();
			protected $_banklinks_grouped;
			protected $_cards = array();
			
			protected $_api;
			
			protected $_init;
			
			public function __construct($init = false) {
				
				$this->_init = $init;
				
				$this->return_url = site_url('/?makecommerce_return=1');
				$this->return_url_cancel = site_url('/?makecommerce_return=1');
				
				$this->return_url_cc = site_url('/?makecommerce_return=2');
				
				// Load the form fields.
				$this->init_form_fields();
				
				// Load the settings.
				$this->init_settings();
				
				$this->initBanklinks();
				
				$this->title = $this->settings['ui_widget_title'];
				$this->method_title = 'MakeCommerce';
				$this->description = true;

				$this->_api = mk_get_api();
				if (!$this->_api && $this->_init) {
					add_action( 'admin_notices', array(&$this, 'makecommerce_api_info_missing') );
				}
				
				if(get_option('mk_api_type', false) == 'live') {
					$this->_gateway_url_static = self::gateway_url_static;
				} elseif (get_option('mk_api_type', false) == 'test') {
					$this->_gateway_url_static = self::test_gateway_url_static;
				}
				
				$this->supports = array(
					'products',
					'refunds',
				);
				
				add_filter('query_vars', array(&$this, 'makecommerce_return_trigger'));
				add_action('template_redirect', array(&$this, 'makecommerce_return_trigger_check'));
				
				add_action( 'wp_ajax_makecommerce_pay_token', array(&$this, 'makecommerce_pay_token') );
				add_action( 'wp_ajax_nopriv_makecommerce_pay_token', array(&$this, 'makecommerce_pay_token') );
				
				if($this->_init == false) {
					add_action('woocommerce_update_options_payment_gateways', array(&$this, 'process_admin_options'));
					add_action('woocommerce_update_options_payment_gateways_' . $this->id, array(&$this, 'process_admin_options'));
					
					add_action('woocommerce_receipt_' . $this->id, array(&$this, 'receipt_page'));
					add_action('woocommerce_admin_order_data_after_order_details', array(&$this, 'admin_order_page'), 10, 1);
					
					wp_enqueue_script('jquery');
					wp_enqueue_style('makecommerce', plugins_url('/css/makecommerce.css', __FILE__), array(), $this->version);
				}
				
				if(is_admin()) {
					add_action( 'wp_ajax_mc_banklinks_reload', array(&$this, 'mc_banklinks_reload') );
				}
			}
			
			function makecommerce_api_info_missing() {
				?>
				<div class="notice notice-error is-dismissible">
					<p>
						<?php echo __('You have not entered the Shop ID and keys for the MakeCommerce payment module. The module will not work without them.', 'wc_makecommerce_domain'); ?>
						<a href="<?php echo admin_url('admin.php?page=wc-settings&tab=api&section=mk_api'); ?>"><?php echo __('Click here to enter them', 'wc_makecommerce_domain'); ?></a>
					</p>
				</div>
				<?php
			}
			
			function makecommerce_banklinks_list_empty() {
				?>
				<div class="notice notice-error is-dismissible">
					<p>
						<?php echo __('The payment methods list for MakeCommerce payment module is empty.', 'wc_makecommerce_domain'); ?>
						<a href="<?php echo admin_url('admin.php?page=wc-settings&tab=checkout&section=makecommerce'); ?>"><?php echo __('Go to the settings to update them', 'wc_makecommerce_domain'); ?></a>
					</p>
				</div>
				<?php
			}
			
			function makecommerce_banklinks_list_type_notice() {
				?>
				<div class="notice notice-error is-dismissible">
					<p>
						<?php echo __('You have changed the environment for MakeCommerce payment module. The payment methods list has been loaded for a different environment.', 'wc_makecommerce_domain'); ?>
						<a href="<?php echo admin_url('admin.php?page=wc-settings&tab=checkout&section=makecommerce'); ?>"><?php echo __('Go to the settings to update them', 'wc_makecommerce_domain'); ?></a>
					</p>
				</div>
				<?php
			}
			
			/**
			 * Initialise Gateway Settings Form Fields
			 */
			function init_form_fields() {

				$this->form_fields = array(
					'header' => array(
						'type' => 'mc_header',
					),
					'active' => array(
						'title' => __('Enable/Disable', 'wc_makecommerce_domain'),
						'type' => 'checkbox',
						'label' => __('Enable MakeCommerce payments', 'wc_makecommerce_domain'),
						'default' => 'no'
					),
					'api_title' => array(
						'title' => __('MakeCommerce API', 'wc_makecommerce_domain'),
						'description' => sprintf(__('Go to <a href="%s">API settings</a> to fill in the credentials', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api&section=mk_api')),
						'type' => 'title',
					),
					'ui_title' => array(
						'title' => '<br>'.__('User Interface', 'wc_makecommerce_domain'),
						'type' => 'title',
						'class' => 'ui-identifier',
					),
					'ui_open_by_default' => array(
						'title' => __('Set as default selection', 'wc_makecommerce_domain'),
						'label' => __('MakeCommerce payments widget will be selected by default', 'wc_makecommerce_domain'),
						'type' => 'checkbox',
						'default' => 'yes',
						'class' => 'ui-identifier',
					),
					'ui_mode' => array(
						'title' => __('Display MC payment channels as', 'wc_makecommerce_domain'),
						'type' => 'mc_hidden',
						'default' => 'widget',
						'options' => array(
							'inline' => __('List', 'wc_makecommerce_domain'),
							'widget' => __('Grouped to widget', 'wc_makecommerce_domain'),
						),
						'class' => 'ui-identifier',
					),
					'ui_widget_title' => array(
						'title' => __('MC payments widget title', 'wc_makecommerce_domain'),
						'type' => 'text',
						'desc_tip' => __("Appropriate title may depend on the configuration you have made, i.e. 'pay with bank-link or credit card', 'pay with bank-links' or 'payment methods'", 'wc_makecommerce_domain'),
						'default' => __('Pay with bank-links or credit card', 'wc_makecommerce_domain'),
						'class' => 'ui-identifier',
					),
					'ui_inline_uselogo' => array(
						'title' => __('MC payment channels display style', 'wc_makecommerce_domain'),
						'type' => 'select',
						'default' => 'logo',
						'options' => array(
							'logo' => __('Logo', 'wc_makecommerce_domain'),
							'text_logo' => __('Text & logo', 'wc_makecommerce_domain'),
							'text' => __('Text', 'wc_makecommerce_domain'),
						),
						'class' => 'ui-identifier',
					),
					'ui_widget_logosize' => array(
						'title' => __('Size of payment channel logos', 'wc_makecommerce_domain'),
						'type' => 'select',
						'default' => 'medium',
						'options' => array(
							'small' => __('Small', 'wc_makecommerce_domain'),
							'medium' => __('Medium', 'wc_makecommerce_domain'),
							'large' => __('Large', 'wc_makecommerce_domain')
						),
						'class' => 'ui-identifier',
					),
					'ui_widget_groupcountries' => array(
						'title' => __('Group bank-links by countries', 'wc_makecommerce_domain'),
						'type' => 'mc_hidden',
						'default' => 'no',
						'class' => 'ui-identifier',
					),
					'ui_widget_countryselector' => array(
						'title' => __('Country selector style', 'wc_makecommerce_domain'),
						'type' => 'mc_hidden',
						'default' => 'flag',
						'options' => array(
							'flag' => __('Flag', 'wc_makecommerce_domain'),
							'dropdown' => __('Dropdown', 'wc_makecommerce_domain'),
						),
						'class' => 'ui-identifier',
					),
					'ui_widget_groupcc' => array(
						'title' => __('Group credit card into separate widget', 'wc_makecommerce_domain'),
						'type' => 'mc_hidden',
						'default' => 'no',
						'class' => 'ui-identifier',
					),
					'ui_chorder' => array(
						'title' => __('Define custom order of payment channels', 'wc_makecommerce_domain'),
						'type' => 'text',
						'desc_tip' => __('If you want to change default order, put here comma separated list of channels. i,e, - seb,lhv,swedbank. see more on the module home page (link above)', 'wc_makecommerce_domain'),
						'class' => 'ui-identifier',
					),
					'ui_javascript' => array(
						'type' => 'ui_javascript',
					),
					'cc_title' => array(
						'title' => '<br>'.__('Credit Card Settings', 'wc_makecommerce_domain'),
						'type' => 'title',
					),
					'cc_pass_cust_data' => array(
						'title' => __('Prefill Credit Card form with customer data', 'wc_makecommerce_domain'),
						'type' => 'checkbox',
						'default' => 'yes',
						'desc_tip' => __('It will pass user Name and e-mail address to the Credit Card dialog to make the form filling easier', 'wc_makecommerce_domain'),
					),
					'cc_shop_name' => array(
						'title' => __('Shop name on credit card payment', 'wc_makecommerce_domain'),
						'type' => 'text',
						'desc_tip' => __('This will appear on buyer\'s credit card transaction', 'wc_makecommerce_domain'),
					),
					'cc_cart_reference_string' => array(
						'title' => __('Order reference on credit card payment', 'wc_makecommerce_domain'),
						'type' => 'text',
						'default' => 'Order %s',
						'desc_tip' => __('This will appear on buyer\'s credit card transaction where "%s" is the order number', 'wc_makecommerce_domain'),
					),
					'adv_title' => array(
						'title' => '<br>'.__('Advanced Settings', 'wc_makecommerce_domain'),
						'type' => 'title',
					),
					'reload_links' => array(
						'type' => 'mc_banklinks_reload',
						'title' => __('Update payment methods', 'wc_makecommerce_domain'),
						'description' => __('Update', 'wc_makecommerce_domain'),
						'desc_tip' => __('This will update shop configuration from MakeCommerce servers.', 'wc_makecommerce_domain'),
					),
				);
			}

			public function generate_mc_hidden_html( $key, $data ) {
				$field_key = $this->get_field_key($key);
				ob_start();
				?>
				<tr style="display: none;">
					<td colspan="2">
						<input type="hidden" name="<?php echo $field_key; ?>" value="<?php echo $data['default']; ?>" />
					</td>
				</tr>
				<?php
				return ob_get_clean();
			}
			
			public function generate_mc_banklinks_reload_html( $key, $data ) {
			
				$field    = $this->get_field_key( $key );
				$defaults = array(
					'title'             => '',
					'disabled'          => false,
					'class'             => '',
					'css'               => '',
					'placeholder'       => '',
					'type'              => 'text',
					'desc_tip'          => false,
					'description'       => '',
					'custom_attributes' => array()
				);
			
				$data = wp_parse_args( $data, $defaults );
			
				ob_start();
				?>
				<tr valign="top">
					<th scope="row" class="titledesc">
						<label for="<?php echo esc_attr( $field ); ?>"><?php echo wp_kses_post( $data['title'] ); ?></label>
						<?php echo $this->get_tooltip_html( $data ); ?>
					</th>
					<td class="forminp">
						<fieldset>
							<legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
							<input id="mc_banklinks_reload" class="button <?php echo esc_attr( $data['class'] ); ?>" type="button" name="<?php echo esc_attr( $field ); ?>" id="<?php echo esc_attr( $field ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" value="<?php echo esc_attr( $data['description'] ); ?>" placeholder="<?php echo esc_attr( $data['placeholder'] ); ?>" <?php disabled( $data['disabled'], true ); ?> <?php echo $this->get_custom_attribute_html( $data ); ?> />
							<script type="text/javascript">
							jQuery('input#mc_banklinks_reload').on('click', function() {
									init_mc_loading();
									jQuery.ajax({
										url: '<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php',
										type: 'POST',
										data: 'action=mc_banklinks_reload',
										success: function (output) {
											if(output.data) {
												alert(output.data);
											} else {
												alert('<?php echo __('There was an error with your update. Please try again.', 'wc_makecommerce_domain'); ?>');
											}
										},
										complete: function() { stop_mc_loading(); }
									});
							});
							
							function init_mc_loading() {
								jQuery('input#mc_banklinks_reload').attr('disabled', 'disabled');
							}
							
							function stop_mc_loading() {
								jQuery('input#mc_banklinks_reload').removeAttr('disabled');
							}
							</script>
						</fieldset>
					</td>
				</tr>
				<?php
			
				return ob_get_clean();
			}
			
			public function generate_ui_javascript_html( $key, $data ) {
				?>
				<script type="text/javascript">
				jQuery(document).ready(function($) {
						
						var api_type = $('#woocommerce_<?php echo $this->id; ?>_api_type');
						
						var ui_inline_uselogo_row = $('#woocommerce_<?php echo $this->id; ?>_ui_inline_uselogo').closest('tr');
						var ui_widget_title_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_title').closest('tr');
						var ui_widget_logosize_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_logosize').closest('tr');
						var ui_widget_countryselector_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_countryselector').closest('tr');
						var ui_widget_groupcountries_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcountries').closest('tr');
						var ui_widget_groupcc_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcc').closest('tr');
						var ui_widget_groupcc_title_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcc_title').closest('tr');
						
						var ui_mode = $('#woocommerce_<?php echo $this->id; ?>_ui_mode');
						var ui_widget_groupcountries = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcountries');
						var ui_widget_groupcc = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcc');
						
						parseVisibility();
						function parseVisibility() {
							$('.ui-identifier').closest('tr').show();
							
							if(api_type.val() == 'live') {
								$('.mc-test-link').hide();
								$('.api-test').closest('tr').hide();
							} else {
								$('.mc-test-link').show();
								$('.api-live').closest('tr').hide();
							}
							
							if(ui_mode.val() == 'inline') {
								ui_widget_title_row.hide();
								ui_widget_logosize_row.hide();
								ui_widget_countryselector_row.hide();
								ui_widget_groupcountries_row.hide();
								ui_widget_groupcc_row.hide();
								ui_widget_groupcc_title_row.hide();
							} else {
								ui_inline_uselogo_row.hide();
								
								if(ui_widget_groupcountries.prop('checked')) {
									ui_widget_countryselector_row.hide();
								}
								if(!ui_widget_groupcc.prop('checked')) {
									ui_widget_groupcc_title_row.hide();
								}
							}
						}
						
						api_type.on('change', parseVisibility);
						ui_mode.on('change', parseVisibility);
						ui_widget_groupcountries.on('change', parseVisibility);
						ui_widget_groupcc.on('change', parseVisibility);
						
				});
				</script>
				<?php
			}
			
			public function generate_mc_header_html( $key, $data ) {
				?>
				<div class="makecommerce-info">
					<div class="makecommerce-logo">
						<a target="_blank" href="http://makecommerce.net"><img src="<?php echo plugins_url('/images/makecommerce_logo_en.svg', __FILE__); ?>" class="makecommerce-logo"></a>
					</div>
					<div class="makecommerce-links">
						<div class="makecommerce-link"><a target="_blank" href="https://merchant.maksekeskus.ee">Merchant Portal</a></div>
						<div class="makecommerce-link"><a target="_blank" href="https://makecommerce.net/">makecommerce.net</a></div>
						<div class="makecommerce-link"><a target="_blank" href="http://maksekeskus.ee">maksekeskus.ee</a></div>
					</div>
				</div>
				<?php
			}
			
			public function mc_banklinks_reload($force = false) {
				if ($force || (defined('DOING_AJAX') && DOING_AJAX)) {
					
					global $wpdb;
					global $mkDbTable;
					global $wp_version;
					
					$tableName = $wpdb->prefix . $mkDbTable;
					$wpdb->query('TRUNCATE TABLE '.$tableName);
					
					$request_params = array(
						'environment' => json_encode(array(
							'platform' => 'wordpress '.$wp_version,
							'module' => $this->id.' '.$this->version,
						)),
					);

					if (!$this->_api) {
						return false;
					}
					
					try {
						$methods = $this->_api->getShopConfig($request_params)->paymentMethods;
					} catch (Exception $e) {
						return false;
					}
					if(isset($methods->banklinks)) {
						foreach($methods->banklinks as $method) {
							$wpdb->insert($tableName, array('type' => 'banklink', 'country' => $method->country, 'name' => $method->name, 'url' => $method->url));
						}
						$updated = true;
					}
					
					if(isset($methods->cards)) {
						foreach($methods->cards as $method) {
							$wpdb->insert($tableName, array('type' => 'card', 'name' => $method->name));
						}
						$updated = true;
					}
					if ($updated) {
						update_option( 'mc_banklinks_api_type', get_option('mk_api_type', false) );
					}
					if ($force) {
						$this->initBankLinks();
						return $updated;
					}
					
					if($updated) {
						wp_send_json(array('success' => 1, 'data' => __('Update successfully completed!', 'wc_makecommerce_domain')));
						exit; 
					}
					
					wp_send_json(array('success' => 0, 'data' => __('There was an error with your update. Please try again.', 'wc_makecommerce_domain')));
					exit; 
				}
				die();
			}
			
			protected function _getWooCommerce() {
				global $woocommerce;
				return $woocommerce;
			}
			
			function is_valid_for_use() {
				return true;
			}
			
			public function is_available() {
				if ($this->settings['active'] == "yes") {
					return true;
				}
			}
			
			function payment_fields() {
				
				if($this->settings['ui_mode'] == 'inline') {
					
					?>
					<ul class="makecommerce-picker">
					<?php foreach($this->_banklinks as $method): ?>
						<li class="makecommerce-picker-method">
							<input type="radio" id="makecommerce_method_picker_<?php echo $method->country.'_'.$method->name; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>" value="<?php echo $method->country.'_'.$method->name; ?>"/>
							<label for="makecommerce_method_picker_<?php echo $method->country.'_'.$method->name; ?>">
								<span class="makecommerce-method-title"><?php if(in_array($this->settings['ui_inline_uselogo'], array('text', 'text_logo'))) { echo ucfirst($method->name); if(count($this->_banklinks_grouped) > 1) { echo ' ('.$this->getCountryName($method->country).')'; } } ?></span>
								<?php if(in_array($this->settings['ui_inline_uselogo'], array('logo', 'text_logo'))) : ?>
									<div><img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" /></div>
								<?php endif; ?>
							</label>
						</li>
					<?php endforeach; ?>
					<?php foreach($this->_cards as $method): ?>
						<li class="makecommerce-picker-method">
							<input type="radio" id="makecommerce_method_picker_<?php echo 'card_'.$method->name; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>" value="<?php echo 'card_'.$method->name; ?>"/>
							<label for="makecommerce_method_picker_<?php echo 'card_'.$method->name; ?>">
								<span class="makecommerce-method-title"><?php if(in_array($this->settings['ui_inline_uselogo'], array('text', 'text_logo'))) { echo ucfirst($method->name); } ?></span>
								<?php if(in_array($this->settings['ui_inline_uselogo'], array('logo', 'text_logo'))) : ?>
									<div><img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" /></div>
								<?php endif; ?>
							</label>
						</li>
					<?php endforeach; ?>
					</ul>
					<?php
					
				} else {
					?>
					<select id="<?php echo $this->id; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>">
						<option value=""></option>
					<?php foreach($this->_banklinks as $method): ?>
						<option value="<?php echo $method->country.'_'.$method->name; ?>"><?php echo strtoupper($method->country).' - '.ucfirst($method->name); ?></option>
					<?php endforeach; ?>
					<?php foreach($this->_cards as $method): ?>
						<option value="card_<?php echo $method->name; ?>"><?php echo ucfirst($method->name); ?></option>
					<?php endforeach; ?>
					</select>
					<ul class="makecommerce-picker">
					<?php
					
					if($this->_banklinks) {
						$defaultCountry = $this->getDefaultCountry();
						?>
						<?php if(empty($this->settings['ui_widget_groupcountries']) || $this->settings['ui_widget_groupcountries'] == 'no') : ?>
							<div class="makecommerce_country_picker_countries">
								<?php foreach(array_keys($this->_banklinks_grouped) as $country): ?>
									<input style="display: none;" type="radio" id="makecommerce_country_picker_<?php echo $country; ?>" name="makecommerce_country_picker" value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'checked="checked" '; ?>/><?php if($this->settings['ui_widget_countryselector'] == 'flag') { ?><label for="makecommerce_country_picker_<?php echo $country; ?>" class="makecommerce_country_picker_label" style="background-image: url(<?php echo plugins_url('/images/'.$country.'32.png', __FILE__); ?>);"></label><?php } ?>
								<?php endforeach; ?>
								<?php if($this->settings['ui_widget_countryselector'] == 'dropdown') : ?>
									<select name="makecommerce_country_picker_select">
										<?php foreach(array_keys($this->_banklinks_grouped) as $country): ?>
											<option value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'selected="selected" '; ?>><?php echo $this->getCountryName($country); ?></option>
										<?php endforeach; ?>
										<option value="card" style="display:none;"></option>
									</select>
								<?php endif; ?>
							</div>
						<?php endif; ?>
						<?php foreach($this->_banklinks_grouped as $country => $methods): ?>
							<li class="makecommerce-picker-country">
							<?php if($this->settings['ui_widget_groupcountries'] == 'yes') : ?>
								<input type="radio" id="makecommerce_country_picker_<?php echo $country; ?>" name="makecommerce_country_picker" value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'checked="checked" '; ?>/><label for="makecommerce_country_picker_<?php echo $country; ?>"><img src="<?php echo plugins_url('/images/'.$country.'32.png', __FILE__); ?>" /></label>
							<?php endif; ?>
								<div class="makecommerce_country_picker_methods" id="makecommerce_country_picker_methods_<?php echo $country; ?>">
									<?php foreach($methods as $method): ?>
										<div class="makecommerce-banklink-picker" banklink_id="<?php echo $method->country.'_'.$method->name; ?>">
											<img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
										</div>
									<?php endforeach; ?>
									<?php if($this->_cards && $this->settings['ui_widget_groupcc'] == 'no') : ?>
										<div class="breaker"></div>
										<?php foreach($this->_cards as $method): ?>
											<div class="makecommerce-banklink-picker" banklink_id="card_<?php echo $method->name; ?>">
												<img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
											</div>
										<?php endforeach; ?>
									<?php endif; ?>
								</div>
							</li>
						<?php endforeach; ?>
						<?php if($this->_cards && $this->settings['ui_widget_groupcc'] == 'yes') : ?>
							<li class="makecommerce-picker-country">
								<input type="radio" id="makecommerce_country_picker_card" name="makecommerce_country_picker" value="card"/><label for="makecommerce_country_picker_card"><?php echo $this->settings['ui_widget_groupcc_title']; ?></label>
								<div class="makecommerce_country_picker_methods" id="makecommerce_country_picker_methods_card">
									<?php foreach($this->_cards as $method): ?>
										<div class="makecommerce-banklink-picker" banklink_id="card_<?php echo $method->name; ?>">
											<img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
										</div>
									<?php endforeach; ?>
								</div>
							</li>
						<?php endif; ?>
					<?php
					}
					?>
						</ul>
						<script type="text/javascript">
						var makecommerceId = '<?php echo $this->id; ?>';
						var selectedCountry = jQuery('input[name=makecommerce_country_picker]:checked').val();
						
						var logosize = '<?php echo $this->settings['ui_widget_logosize']; ?>';
						jQuery('div.makecommerce_country_picker_methods').addClass('logosize-'+logosize);
						
					<?php if(count($this->_banklinks_grouped) == 1): ?>
						jQuery('div.makecommerce_country_picker_methods').show();
						jQuery('div.makecommerce_country_picker_countries').hide();
						jQuery('li.makecommerce-picker-country > input, li.makecommerce-picker-country > label').hide();
					<?php else: ?>
						makecommercePick();
						
						jQuery('body').on('change', 'select[name=makecommerce_country_picker_select]', function() {
								selectedCountry = jQuery(this).val();
								jQuery('input[name=makecommerce_country_picker]').removeAttr('checked');
								makecommercePick();
						});
						jQuery('body').on('change', 'input[name=makecommerce_country_picker]', function() {
								selectedCountry = jQuery(this).val();
								jQuery('select[name=makecommerce_country_picker_select]').val(selectedCountry);
								makecommercePick();
						});
						
						function makecommercePick() {
							jQuery('select#'+makecommerceId).val('');
							jQuery('div.makecommerce-banklink-picker').removeClass('selected');
							jQuery('label.makecommerce_country_picker_label').removeClass('selected');
							
							jQuery('div.makecommerce_country_picker_methods').hide();
							jQuery('div#makecommerce_country_picker_methods_' + selectedCountry).show();
							jQuery('label[for=makecommerce_country_picker_' + selectedCountry + ']').addClass('selected');
						}
					<?php endif; ?>
						
						jQuery('div.makecommerce-banklink-picker').on('click', function() {
								var banklink_id = jQuery(this).attr('banklink_id');
								jQuery('select#'+makecommerceId).val(banklink_id);
								
								jQuery('div.makecommerce-banklink-picker').removeClass('selected');
								jQuery(this).addClass('selected');
						});
						</script>
					<?php
				}
				
				if($this->settings['ui_open_by_default'] == 'yes') {
					?>
					<script type="text/javascript">
					jQuery('input#payment_method_<?php echo $this->id; ?>').trigger('click');
					</script>
					<?php
				}
			}
			
			private function getDefaultCountry() {
				if ($this->_getWooCommerce()->customer) {
					$customerCountry = strtolower($this->_getWooCommerce()->customer->get_shipping_country());
					if(array_key_exists($customerCountry, $this->_banklinks_grouped)) {
						return $customerCountry;
					}
				}
				
				$localeToCountry = array(
					'et' => 'ee',
					'lv' => 'lv',
					'lt' => 'lt',
					'fi' => 'fi',
				);
				if(array_key_exists(get_locale(), $localeToCountry)) {
					return $localeToCountry[get_locale()];
				}
				
				return key($this->_banklinks_grouped);
			}
			
			private function initBanklinks() {
				global $wpdb;
				global $mkDbTable;
				$this->_banklinks = array();
				
				$tableName = $wpdb->prefix . $mkDbTable;
				$methods = $wpdb->get_results('SELECT * FROM '.$tableName);
				
				if(count($methods)) {
					if(is_admin() && $this->_init == true && get_option( 'mc_banklinks_api_type' ) != get_option('mk_api_type', false)) {
						//add_action( 'admin_notices', array(&$this, 'makecommerce_banklinks_list_type_notice') );
					}
					$banklinks = array();
					$banklinks_grouped = array();
					$cards = array();
					foreach($methods as $method) {
						if($method->type == 'banklink') {
							$banklinks[] = $banklinks_grouped[$method->country][] = $method;
						} elseif($method->type == 'card') {
							$cards[] = $method;
						}
					}
					
					usort($banklinks, array($this, 'orderBanklinks'));
					foreach($banklinks_grouped as &$country) {
						usort($country, array($this, 'orderBanklinks'));
					}
					
					$this->_banklinks = $banklinks;
					$this->_banklinks_grouped = $banklinks_grouped;
					$this->_cards = $cards;
					remove_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
				} elseif(is_admin() && $this->_init == true) {
					add_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
				}
			}
			
			private function orderBanklinks($a, $b) {
				$order = array_map('trim', explode(",", $this->settings['ui_chorder']));
				
				$posA = array_search($a->name, $order);
				$posB = array_search($b->name, $order);
				
				if($posA === $posB) return 0;
				if($posA === FALSE) return 1;
				if($posB === FALSE) return -1;
				
				return $posA > $posB ? 1 : -1;
			}
			
			protected function getImageUrl($methodName) {
				$imageUrlPath = 'https://static.maksekeskus.ee/img/channel/lnd/';
				
				return $imageUrlPath.$methodName.'.png';
			}
			
			public function validate_fields() {
				$selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;

				if (!$selected) {
					wc_add_notice(__('Please select suitable payment option!', 'wc_makecommerce_domain'), 'error');
				} else {
					$this->_getWooCommerce()->session->makecommerce_preselected_method = $selected;
				}

				return true;
			}
			
			function process_payment($orderId) {

				$order = new WC_Order($orderId);

				$selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
				
				if(!empty($selected)) {
					
					update_post_meta($order->id, '_makecommerce_preselected_method', $selected);
					
					if(substr($selected, 0, 5) == 'card_') {
						
						$request_body = array(
							'transaction' => array(
								'amount' => round($order->order_total, 2),
								'currency' => $order->get_order_currency(),
								'reference' => $order->id,
								'transaction_url' => array(
										'return_url' => array(
											'url' => $this->return_url_cc,
											'method' => 'POST',
										),
										'cancel_url' => array(
											'url' => $this->return_url_cc,
											'method' => 'POST',
										),
										'notification_url' => array(
											'url' => $this->return_url_cc,
											'method' => 'POST',
										),
									),
								),
							'customer' => array(
								'ip' => $_SERVER['REMOTE_ADDR'],
								'country' => strtolower($order->billing_country),
								'locale' => strtolower(substr(get_locale(), 0, 2)),
								),
						);
						$transaction = $this->_api->createTransaction($request_body);
						
						if(isset($transaction->id)) {
							update_post_meta($order->id, '_makecommerce_cc_transaction_id', $transaction->id);
							return array(
								'result' => 'success',
								'redirect' => $this->_getOrderConfirmationUrl($order),
							);
						}
						
						wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
						return array(
							'result' => 'failure',
						);
						
					} else {
					
						$redirectUrl = $this->_getRedirectUrl($selected);
						
						if($redirectUrl) {
							$request_body = array(
								'transaction' => array(
									'amount' => round($order->order_total, 2),
									'currency' => $order->get_order_currency(),
									'reference' => $order->id,
									'transaction_url' => array(
										'return_url' => array(
											'url' => $this->return_url,
											'method' => 'POST',
										),
										'cancel_url' => array(
											'url' => $this->return_url,
											'method' => 'POST',
										),
										'notification_url' => array(
											'url' => $this->return_url,
											'method' => 'POST',
										),
									),
								),
								'customer' => array(
									'ip' => $_SERVER['REMOTE_ADDR'],
									'country' => strtolower($order->billing_country),
									'locale' => strtolower(substr(get_locale(), 0, 2)),
									)
							);
							$transaction = $this->_api->createTransaction($request_body);
							
							if(isset($transaction->id)) {
								return array(
									'result' => 'success',
									'redirect' => $redirectUrl.$transaction->id,
								);
							}
						}
						
						wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
						return array(
							'result' => 'failure',
						);
						
					}
					
				}
				
				wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
				return array(
					'result' => 'failure',
				);
			}
			
			protected function _getRedirectUrl($selected) {
				foreach($this->_banklinks as $method) {
					if($selected == $method->country.'_'.$method->name)
						return $method->url;
				}
				
				return false;
			}
			
			protected function _getOrderConfirmationUrl($order) {
				//$url = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
				$url = site_url('?makecommerce_card_pay=1&order_id='.$order->id);
				return $url;
			}
			
			function receipt_page($orderId) {
				echo '<p>' . __('Thank you for the order, please click on the button to start the payment.', 'wc_makecommerce_domain') . '</p>';
				
				$order = new WC_Order($orderId);
				if(substr(get_post_meta($orderId, '_makecommerce_preselected_method', true), 0, 5) == 'card_' && $order->get_status() == 'pending') {
					echo $this->generateCardForm($order);
				}
			}
			
			function generateCardForm($order) {
				$scriptSrc = htmlspecialchars($this->_gateway_url_static.'checkout.js');
				$transactionId = get_post_meta($order->id, '_makecommerce_cc_transaction_id', true);
				$idReference = $order->id;
				$jsParams = array(
					'key' => $this->_api->getPublishableKey(),
					'transaction' => $transactionId,
					'selector' => '#submit_banklinkmakecommerce_payment_form',
					'amount' => round($order->order_total, 2),
					'locale' => strtolower(substr(get_locale(), 0, 2)),
					'open-on-load' => 'true',
					'client-name' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) ($order->billing_first_name . ' ' . $order->billing_last_name) : ''),
					'email' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) $order->billing_email : ''),
					'name' => $this->settings['cc_shop_name'],
					'description' => (string)sprintf($this->settings['cc_cart_reference_string'], (string) $idReference),
					'completed' => 'makecommerce_cc_complete',
					'currency' => 'EUR',
				);
				?>
				<script type="text/javascript">
				function makecommerce_cc_complete(data) {
					 if(data.paymentToken) {
						 jQuery('div.mc-processing-message').show();
						 
						 var submitform = jQuery('<form action="<?php echo $this->return_url_cc; ?>" method="POST" style="display: none;"><input type="submit"/><input type="hidden" name="transaction" value="<?php echo $transactionId; ?>" /></form>');
						 for(var key in data) {
						 	submitform.append('<input type="hidden" name="'+key+'" value="'+data[key]+'" />'); 
						 }
						 jQuery('body').append(submitform);
						 submitform.submit();
					 }
				}
				</script>
				<form id="cc_form">
					<input type="submit" class="button-alt" id="submit_banklinkmakecommerce_payment_form" value="<?php echo __('Pay', 'wc_makecommerce_domain'); ?>" />
					<a class="button cancel" href="<?php echo esc_url($order->get_cancel_order_url()); ?>"><?php echo __('Cancel order &amp; restore cart', 'wc_makecommerce_domain'); ?></a>
					<script type="text/javascript" src="<?php echo $scriptSrc; ?>" <?php echo $this->_toHtmlAttributes($jsParams); ?>></script>
				</form>
				<div class="mc-processing-message"><img src="<?php echo plugins_url('/images/loading.png', __FILE__); ?>"/> <?php echo __('Please wait, processing payment...', 'wc_makecommerce_domain'); ?></div>
				<?php
			}
			
			protected function _toHtmlAttributes($input) {
				$result = array();
				foreach ($input as $key => $value) {
					$result[] = 'data-' . htmlspecialchars($key) . '=' . '"' . htmlspecialchars($value) . '"';
				}
				return implode(' ', $result);
			}        
			
			function makecommerce_return_trigger($vars) {
				$vars[] = 'makecommerce_return';
				$vars[] = 'makecommerce_card_pay';
				return $vars;
			}
			
			function makecommerce_return_trigger_check() {
				if(intval(get_query_var('makecommerce_return')) == 1) {
					
					$returnUrl = home_url();
					
					$request = stripslashes_deep($_POST);
					if($this->_api->verifySignature($request)) {
						$data = $this->_api->extractRequestData($request);
						$order = new WC_Order($data['reference']);
						
						switch($data['status']) {
							case self::MC_CANCELLED:
								$order->update_status( 'cancelled' );
								wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
								$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
								break;
							case self::MC_COMPLETED:
								if($this->validate_completed_payment($order, $data)) {
									$orderNote = array();
									$orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data['transaction'];
									$orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
		
									$order->add_order_note(implode("\r\n", $orderNote));
									
									$order->payment_complete($data['transaction']);
									$order->update_status( 'processing' );
									
									try {
										@ob_start();
										$this->receipt_page($order->id);
										@ob_end_clean();
										
										$returnUrl = $this->get_return_url($order);
									} catch (Exception $ex) {
										@ob_end_clean();									
									}
								} else {
									$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
								}
								break;
						}
						
						//exit;
					}
					wp_redirect($returnUrl);
					exit;
					
				} elseif(intval(get_query_var('makecommerce_return')) == 2) {
					
					$returnUrl = home_url();
					
					if(isset($_POST['paymentToken']) && isset($_POST['transaction'])) {
						$token = $_POST['paymentToken'];
						$transaction = $_POST['transaction'];
					}
					
					if(isset($_POST['json'])) {
						$data = json_decode(stripslashes($_POST['json']), true);
						$token = $data['token']['id'];
						$transaction = $data['transaction']['id'];
					}
					
					if(!empty($token) && !empty($transaction)) {
						global $wpdb;
						if($order = New WC_Order($wpdb->get_var('SELECT post_id from '.$wpdb->postmeta.' where meta_key = "_makecommerce_cc_transaction_id" AND meta_value = "'.$transaction.'"'))) {
							$request_body = array(
								'token' => $token,
							);
							$data = $this->_api->createPayment(get_post_meta($order->id, '_makecommerce_cc_transaction_id', true), $request_body);
							switch($data->status) {
								case self::MC_CANCELLED:
									$order->update_status( 'cancelled' );
									wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
									$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
									break;
								case self::MC_DEPOSITED:
									if($this->validate_completed_payment($order, $data)) {
										$orderNote = array();
										$orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data->transaction->id;
										$orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
		
										$order->add_order_note(implode("\r\n", $orderNote));
										
										$order->payment_complete($data->transaction->id);
										$order->update_status( 'processing' );
										
										try {
											@ob_start();
											$this->receipt_page($order->id);
											@ob_end_clean();
											
											$returnUrl = $this->get_return_url($order);
										} catch (Exception $ex) {
											@ob_end_clean();									
										}
									} else {
										$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
									}
									break;
							}
						}
					}
					
					wp_redirect($returnUrl);
					exit;
				}
				
				if(intval(get_query_var('makecommerce_card_pay')) == 1) {
					if(isset($_GET['order_id'])) {
						if($order = New WC_Order($_GET['order_id'])) {
							New woocommerce_makecommerce(false);
							get_header();
							?>
							<div id="primary" class="content-area">
								<?php $this->receipt_page($order->id); ?>
							</div>
							<?php
							get_sidebar();
							get_footer();
							
							exit;
						}
					}
				}
			}
			
			private function validate_completed_payment($order, $data) {
				
				if(is_object($data)) {
					$data = json_decode(json_encode($data), true);
				}
				
				if(empty($data['transaction'])) {
					$order->add_order_note(__('Payment error, missing transaction id', 'wc_makecommerce_domain'));
					wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain'), 'error');
					return false;
				}
				if($data['amount'] != round($order->order_total, 2)) {
					$order->add_order_note(sprintf(__('Payment error, incorrect amount captured: %s', 'wc_makecommerce_domain'), $data['amount'].' '.$data['currency']));
					wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect amount captured', 'wc_makecommerce_domain'), 'error');
					return false;
				}
				if($data['currency'] != $order->get_order_currency()) {
					$order->add_order_note(sprintf(__('Payment error, incorrect currency captured: %s', 'wc_makecommerce_domain'), $data['currency']));
					wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect currency captured', 'wc_makecommerce_domain'), 'error');
					return false;
				}
				
				return true;
			}
			
			function admin_order_page($order) {
				//
			}
			
			public function process_refund($order_id, $amount = null, $comment = '') {
				if ($this->_api) {
					try {
						$order = new WC_Order($order_id);
						$transactionId = $order->get_transaction_id();
						
						if($response = $this->_api->createRefund($transactionId, array('amount' => $amount, 'comment' => ($comment ? : 'refund')))) {
							if($status = (string)$response->transaction->status) {
								switch($status) {
									case self::MC_REFUNDED: 
										$order->add_order_note(sprintf(__('Refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
										return true;
										break;
									case self::MC_PART_REFUNDED: 
										$order->add_order_note(sprintf(__('Partial refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
										return true;
										break;
								}
							}
						}
						return false;
						
					} catch (Exception $e) {
						return new WP_Error('makecommerce_refund_error', $e->getMessage());
					}

					return false;
				}
				return false;
			}
			
			protected function getCountryName($slug) {
				switch($slug) {
					case 'ee': return __('Estonia', 'wc_makecommerce_domain'); break;
					case 'lv': return __('Latvia', 'wc_makecommerce_domain'); break;
					case 'lt': return __('Lithuania', 'wc_makecommerce_domain'); break;
					case 'fi': return __('Finland', 'wc_makecommerce_domain'); break;
				}
				return $slug;
			}
			
		}
		
		New woocommerce_makecommerce(true);
		
	}

	function woocommerce_payment_makecommerce_add($methods) {
		$methods[] = 'woocommerce_makecommerce';
		return $methods;
	}

	add_action('plugins_loaded', 'woocommerce_payment_makecommerce_init');
	add_action('woocommerce_payment_gateways', 'woocommerce_payment_makecommerce_add');

	function clear_wc_shipping_rates_cache(){
		$packages = WC()->cart->get_shipping_packages();
		foreach ($packages as $key => $value) {
			$shipping_session = "shipping_for_package_$key";
			unset(WC()->session->$shipping_session);
		}
	}
	add_filter('woocommerce_checkout_update_order_review', 'clear_wc_shipping_rates_cache');

	// Parcel machine specific stuff
	function parcelmachine_add_method() {

		// Delete all the wc_ship transient scum, you aren’t wanted around here, move along.
		// Same as being in shipping debug mode
		global $wpdb;
		$transients = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_wc_ship%'");
		if (count($transients)) {
			foreach ($transients as $tr) {
				$hash = substr($tr, 11);
				delete_transient($hash);
			}
		}
		$transient_value = get_transient('shipping-transient-version');
		WC_Cache_Helper::delete_version_transients( $transient_value );
		if (WC()->session) {
			WC()->session->set('shipping_for_package', '');
		}

		if ( ! class_exists( 'WC_ParcelMachine_Shipping_Method' ) ) {

			class WC_ParcelMachine_Shipping_Method extends WC_Shipping_Method {


				function __construct($instance_id = 0) {
					if (!$this->ext) {
						throw new Exception('Do not call this class directly!');
					}
					$this->id           = 'parcelmachine_' . mb_strtolower($this->ext);
					$this->instance_id  = $instance_id;
					$this->method_title = $this->name_ext . __(' Parcel Machine by MC', 'wc_makecommerce_domain');
					$this->init();
				}

				function init() {
					$this->init_form_fields();
					$this->init_settings();

					$this->enable            = $this->settings['active'];
					$this->title             = $this->settings['method_name'];
					$this->availability      = 'specific';
					$this->countries         = $this->settings['countries'];
					$this->prioritization    = $this->settings['prioritization'];
					$this->free_shipping_min_amount = $this->settings['free_shipping_min_amount'];
					$this->maximum_weight    = (double)$this->settings['maximum_weight'];
					$this->short_office_names = $this->settings['short_office_names'];
					$this->order_country     = 'unknown';
					add_action('woocommerce_update_options_shipping_' . $this->id, array(&$this, 'process_admin_options'));
					add_filter('woocommerce_review_order_after_shipping' , array(&$this, 'add_parcelmachine_checkout_fields'));
					add_action('woocommerce_checkout_process', array(&$this, 'check_parcelmachine_checkout_fields'));
					add_action('woocommerce_checkout_update_order_meta', array(&$this, 'add_parcelmachine_order_meta'));
					add_filter('woocommerce_order_shipping_to_display_shipped_via', array(&$his, 'add_admin_parcelmachine_via_field'));
				}

				function calculate_shipping($package = array()) {

					$price = $this->settings['price_'.strtolower($package['destination']['country'])];
					if ($this->free_shipping_min_amount && $package['contents_cost'] >= $this->free_shipping_min_amount) {
						$price = 0;
					}
					$rate = array(
						'id' 	=> $this->id,
						'label' => $this->title,
						'cost' 	=> $price,
						'calc_tax' => 'per_order',
					);
					$this->add_rate( $rate );
				}

				function calculate_weight($package) {
					$weight = 0;
					foreach ($package['contents'] as $line) {
						$weight += $line['data']->get_weight();
					}
					return $weight;
				}
				function fits_parcel_machine($package) {
					foreach ($package['contents'] as $line) {
						if (get_post_meta($line['product_id'], '_no_parcel_machine', true) === 'yes') {
							return false;
						}
					}
					return true;
				}


				function is_available($package) {
					if (!$this->fits_parcel_machine($package)) {
						return false;
					}
					$package_weight = $this->calculate_weight($package);
					if ($package_weight >= $this->maximum_weight) {
						return false;
					}
					$is_available = $this->enable === 'yes';
					if (!$is_available) {
						return false;
					}
					if (is_array($this->countries) && !in_array($package['destination']['country'], $this->countries)) {
						$is_available = false;
					}
					$this->order_country = $package['destination']['country'];
					return apply_filters('woocommerce_shipping_' . $this->id . '_is_available', $is_available, $package);
				}

				function mk_get_machines() {
					$machines = mk_get_machines($this->ext, $this->order_country);
					if ($this->prioritization === 'yes') {
						usort($machines, function($a, $b) {
							$sortorder = array(
								'tallinn', 'tartu', 'narva', 'pärnu', 'viljandi', 'kohtla-järve', 'rakvere', 'maardu', 'sillamäe', 'kuressaare',
								'helsinki', 'espoo', 'tampere', 'vantaa', 'oulu', 'turku', 'jüväskülä', 'lahti', 'kuopio', 'kouvola',
								'riga', 'daugavpils', 'liepaja', 'jelgava', 'jurmala', 'ventspils', 'rezekne', 'valmiera', 'jekabpils',
								'vilnius', 'kaunas', 'klaipeda', 'siauliai', 'panevezys', 'alytus', 'mariampole', 'mazeikiai', 'jonava', 'utena'
							);
							$acity = mb_strtolower($a['city']);
							$bcity = mb_strtolower($b['city']);
							if (!$acity) { $acity = 'xxxxxxx'; }
							if (!$bcity) { $bcity = 'xxxxxxx'; }
							$aidx = array_search($acity, $sortorder);
							$bidx = array_search($bcity, $sortorder);
							if ($aidx !== false) {
								$acity = str_pad($aidx, 4, "0", STR_PAD_LEFT) . '-' . $acity;
							}
							if ($bidx !== false) {
								$bcity = str_pad($bidx, 4, "0", STR_PAD_LEFT) . '-' . $bcity;
							}
							$acity .= '-' . mb_strtolower($a['name']);
							$bcity .= '-' . mb_strtolower($b['name']);
							return $acity < $bcity ? -1 : 1;
						});
					}
					return $machines;
				}

				function add_parcelmachine_checkout_fields($checkout) {
					$this->order_country = WC()->customer->get_shipping_country();
					echo '<tr style="display: none;" class="parcel_machine_checkout" id="parcel_machine_checkout_parcelmachine_'.mb_strtolower($this->ext).'"><th>' . $this->title . '</th>';
					echo '<td>';
					$options = array();
					$machines = $this->mk_get_machines();
					echo '<p class="form-row" id="'.esc_attr($this->id).'_field">';
					echo '<select class="select" name="'.esc_attr($this->id).'" id="'.esc_attr($this->id).'">';
					$pcity = false;
					foreach ($machines as $machine) {
						$city = strtolower($machine['city']);
						if ($city !== $pcity) {
							if ($pcity) echo '</optgroup>';
							echo '<optgroup label="'.$machine['city'].'">';
						}
						$mname = $machine['name'];
						if ($this->short_office_names !== 'yes') $mname .= ' - ' . $machine['city'] . ', ' . $machine['address'];
						echo '<option value="'.esc_attr($machine['provider'].'||'.$machine['id']).'">'.$mname.'</option>';
						$pcity = $city;
					}
					if ($pcity) echo '</optgroup>';
					echo '</select>';
					echo '</p>';
					echo '</td></tr>';
				}

				function check_parcelmachine_checkout_fields() {
					$shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
					if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
					if ($shipping_method === $this->id && empty($_POST['parcel_machine_itella'])) {
						wc_add_notice(__('<strong>Parcel machine</strong> is a required field.'), 'error');
					}
				}
				function add_parcelmachine_order_meta($order_id) {
					$shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
					if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
					if ($shipping_method === $this->id && !empty($_POST[$this->id])) {
						update_post_meta($order_id, '_parcel_machine', sanitize_text_field($_POST[$this->id]));
					}
				}
				function add_admin_parcelmachine_via_field($order) {
					error_log('Via');
					error_log(print_r($order, 1));
				}
			}
			class WC_ParcelMachine_Shipping_Method_Omniva extends WC_ParcelMachine_Shipping_Method {
				function __construct($instance_id = 0) {
					$this->ext = 'Omniva';
					$this->name_ext = 'Omniva';
					parent::__construct();
				}
				function init_form_fields() {

					$this->form_fields = array(
						'logo'        => array('type' => 'title', 'title' => __get_logo_html()),
						'generic'     => array('type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
						'active'      => array(
							'title'            => __('Enable', 'wc_makecommerce_domain'),
							'type'             => 'checkbox',
							'label'            => __('enabled', 'wc_makecommerce_domain'),
							'default'          => 'no',
							'description'      => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options', 'wc_makecommerce_domain'),
						),
						'price_ee'        => array(
							'title'            => __('Price EE', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '2.99'
						),
						'price_lv'        => array(
							'title'            => __('Price LV', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '7.99'
						),
						'price_lt'        => array(
							'title'            => __('Price LT', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '8.99'
						),
						//'price_fi'        => array(
						//	'title'            => __('Price FI', 'wc_makecommerce_domain'),
						//	'type'             => 'text',
						//	'default'          => '10.99'
						//),
						'free_shipping_min_amount'        => array(
							'title'            => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
							'type'             => 'number',
							'default'          => '0',
							'description'	   => '(0 means no free shipping)'
						),
						'maximum_weight'        => array(
							'title'            => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '15'
						),
						'countries'    => array(
							'title'            => __('Specific Countries', 'wc_makecommerce_domain'),
							'type'             => 'multiselect',
							'class'            => 'wp-enhanced-select',
							'css'              => 'width: 450px;',
							'default'          => array('EE','LV','LT'),
							'options'          => array('EE' => __('Estonia'), 'LV' => __('Latvia'), 'LT' => __('Lithuania')),
						),
						'look_and_feel'       => array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on check-out page', 'wc_makecommerce_domain')),
                        'method_name'        => array(
                            'title'            => __('Shipping Method Title', 'wc_makecommerce_domain'),
                            'type'             => 'text',
                            'default'          => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
                        ),
						'prioritization'      => array(
							'title'            => __('Prioritize', 'wc_makecommerce_domain'),
							'type'             => 'checkbox',
							'label'            => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
							'default'          => 'yes'
						),
						'short_office_names'      => array(
							'title'            => __('Short names', 'wc_makecommerce_domain'),
							'type'             => 'checkbox',
							'label'            => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
							'default'          => 'no'
						),
						'api_access'       => array( 'type' => 'title', 'title' => '<br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into Omniva system and print the out the package labels right here, at the shop orders view. <br> Please set your Omniva web servises account credentials below here. <br>(see more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>.   Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api&section=mk_api'))),
						'service_user'        => array(
							'title'            => __('Omniva web services username', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => ''
						),
						'service_password'        => array(
							'title'            => __('Omniva web services password', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => ''
						),
						'return_address'     => array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for Omniva shipments', 'wc_makecommerce_domain')),
						'shop_name' => array(
							'type' => 'text',
							'title' => __('Shop name', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						'shop_phone' => array(
							'type' => 'text',
							'title' => __('Shop phone', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						'shop_email' => array(
							'type' => 'text',
							'title' => __('Shop email', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						'shop_postal_code' => array(
							'type' => 'text',
							'title' => __('Shop postal code', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
							'description' => __('Put here zip-code of the Parcel Terminal you use for returns, see: <a href="https://www.omniva.ee/era/kaart/asukohad">List of Omniva Terminals</a>', 'wc_makecommerce_domain')
						),
					);
				}

			}
			class WC_ParcelMachine_Shipping_Method_Smartpost extends WC_ParcelMachine_Shipping_Method {
				function __construct() {
					$this->ext = 'SmartPost';
					$this->name_ext = 'SmartPOST';
					parent::__construct();
				}
				function init_form_fields() {
					global $woocommerce;

					$this->form_fields = array(
						'logo'        => array('type' => 'title', 'title' => __get_logo_html()),
						'generic'     => array( 'type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
						'active'      => array(
							'title'            => __('Enable', 'wc_makecommerce_domain'),
							'type'             => 'checkbox',
							'label'            => __('enabled', 'wc_makecommerce_domain'),
							'default'          => 'no',
							'description'      => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options', 'wc_makecommerce_domain'),
						),
						'price_ee'        => array(
							'title'            => __('Price EE', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '2.99'
						),
						'price_fi'        => array(
							'title'            => __('Price FI', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '10.99'
						),
						'free_shipping_min_amount'        => array(
							'title'            => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
							'type'             => 'number',
							'default'          => '0',
							'description'	   => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
						),
						'maximum_weight'        => array(
							'title'            => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => '15'
						),
						'countries'    => array(
							'title'            => __('Specific Countries', 'wc_makecommerce_domain'),
							'type'             => 'multiselect',
							'class'            => 'wp-enhanced-select',
							'css'              => 'width: 450px;',
							'default'          => array('EE','FI'),
							'options'          => array('EE' => __('Estonia'), 'FI' => __('Finland')),
						),
						'look_and_feel'       => array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on checkout page', 'wc_makecommerce_domain')),
                        'method_name'        => array(
                            'title'            => __('Method Title', 'wc_makecommerce_domain'),
                            'type'             => 'text',
                            'default'          => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
                        ),
						'prioritization'      => array(
							'title'            => __('Prioritize', 'wc_makecommerce_domain'),
							'type'             => 'checkbox',
							'label'            => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
							'default'          => 'yes'
						),
						'short_office_names'      => array(
							'title'            => __('Short names', 'wc_makecommerce_domain'),
							'type'             => 'checkbox',
							'label'            => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
							'default'          => 'no'
						),
						'api_access'       => array( 'type' => 'title', 'title' => '<br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into smartpost.ee system and print the out the package labels right here, at the shop orders view. <br> Please set your smartpost.ee account credentials below here. <br>(See more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>.   Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api&section=mk_api'))),
						'service_user'        => array(
							'title'            => __('eteenindus.smartpost.ee username', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => ''
						),
						'service_password'        => array(
							'title'            => __('eteenindus.smartpost.ee password', 'wc_makecommerce_domain'),
							'type'             => 'text',
							'default'          => ''
						),
						'return_address'     => array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for SmartPOST shipments (used on parcel labels)', 'wc_makecommerce_domain')),
						'shop_name' => array(
							'type' => 'text',
							'title' => __('Shop name', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						'shop_phone' => array(
							'type' => 'text',
							'title' => __('Shop phone', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						'shop_email' => array(
							'type' => 'text',
							'title' => __('Shop email', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						/*'shop_postal_code' => array(
							'type' => 'text',
							'title' => __('Shop postal code', 'wc_makecommerce_domain'),
							'class' => 'input-text regular-input',
						),
						*/
					);
				}

			}
		}
	}
	add_action('woocommerce_shipping_init', 'parcelmachine_add_method');

	function add_parcelmachine_shipping_method($methods) {
		$methods[] = 'WC_ParcelMachine_Shipping_Method_Omniva';
		$methods[] = 'WC_ParcelMachine_Shipping_Method_Smartpost';
		return $methods;
	}
	add_filter('woocommerce_shipping_methods', 'add_parcelmachine_shipping_method');

	function mk_parcelmachine_add_assets() {
		wp_enqueue_style('parcelmachine-css', plugin_dir_url(__FILE__).'/css/parcelmachine.css');
		wp_enqueue_script('parcelmachine-js', plugin_dir_url(__FILE__).'/scripts/parcelmachine.js', array('jquery'));
	}
	add_action('wp_enqueue_scripts', 'mk_parcelmachine_add_assets');

	function mk_admin_plugin_settings_link($links) { 
		$settings_link = '<a href="admin.php?page=wc-settings&tab=api&section=mk_api">API '.__('Settings').'</a>'; 
		array_unshift($links, $settings_link); 
		return $links; 
	}
	$plugin = plugin_basename(__FILE__); 
	add_filter("plugin_action_links_$plugin", 'mk_admin_plugin_settings_link' );

	function mk_admin_add_settings($sections) {
		$sections['mk_api'] = __('MakeCommerce API access', 'wc_makecommerce_domain');
		return $sections;
	}

	function mk_admin_all_settings($settings) {
		global $current_section;
		if ($current_section !== 'mk_api') {
			return $settings;
		}
		return array(
			array('type' => 'title', 'desc' => __get_logo_html()),
			array(
				'type' => 'title', 
				'title' => __('MakeCommerce API access credentials', 'wc_makecommerce_domain'), 
				'desc' => sprintf(__('To use MakeCommerce/Maksekeskus services you need to enter API credentials below here <br/> <br/>'.
									'To further configure the Payment methods please go to <a href="%s">MakeCommerce Checkout Options</a><br>'.
									'To use also Ominva or Itella SmartPOST integration please configure these API accesses: <a href="%s">Omniva API access</a> | '.
									'<a href="%s">SmartPOST API access</a><br/>','wc_makecommerce_domain'),
									'admin.php?page=wc-settings&tab=checkout&section=makecommerce',									
									'admin.php?page=wc-settings&tab=-shipping&section=parcelmachine_omniva', 
									'admin.php?page=wc-settings&tab=shipping&section=parcelmachine_smartpost'
							), 							
				'id' => 'mk_api_settings'
			),
			array(
			        'type' => 'select',
			        'title' => __('Current environment', 'wc_makecommerce_domain'),
			        'desc' => __('See more about <a href="https://maksekeskus.ee/en/for-developers/test-environment/">MakeCommerce Test environment</a>', 'wc_makecommerce_domain'),
			        'default' => 'live',
			        'options' => array(
					        'live' => __('Live', 'wc_makecommerce_domain'),
					        'test' => __('Test', 'wc_makecommerce_domain'),
		        			),
				'id' => 'mk_api_type'
			),
		      	array(
			        'id' => 'mk_shop_id',
			        'type' => 'text',
			        'title' => __('Shop ID (live)', 'wc_makecommerce_domain'),
			        'desc' => __('Get it from <a href="https://merchant.maksekeskus.ee/api.html" target="_blank">Merchant Portal</a>','wc_makecommerce_domain'), 
			        'class' => 'input-text regular-input',
		      	),
		      	array(
			        'id' => 'mk_public_key',
			        'type' => 'text',
			        'title' => __('Public key (live)', 'wc_makecommerce_domain'),
			        'class' => 'input-text regular-input',
		      	),
		      	array(
			        'id' => 'mk_private_key',
			        'type' => 'text',
			        'title' => __('Private key (live)', 'wc_makecommerce_domain'),
			        'class' => 'input-text regular-input',
		      	),
		      	array(
			        'id' => 'mk_test_shop_id',
			        'type' => 'text',
			        'title' => __('Shop ID (test)', 'wc_makecommerce_domain'),
			        'class' => 'input-text regular-input',
			        'desc' => __('Get it from <a href="https://merchant-test.maksekeskus.ee/api.html" target="_blank">Merchant Portal Test</a>','wc_makecommerce_domain'), 
		      	),
		      	array(
			        'id' => 'mk_test_public_key',
			        'type' => 'text',
			        'title' => __('Public key (test)', 'wc_makecommerce_domain'),
			        'class' => 'input-text regular-input',
		      	),
		      	array(
			        'id' => 'mk_test_private_key',
			        'type' => 'text',
			        'title' => __('Private key (test)', 'wc_makecommerce_domain'),
			        'class' => 'input-text regular-input',
		      	),
			array('type' => 'sectionend', 'id' => 'mk_api_settings')
		);
	}

	function mk_admin_save_settings() {
		// reload banklinks
		global $current_section;
		if ($current_section !== 'mk_api') {
			return;
		}
		$wcmc = New woocommerce_makecommerce(true);
		$wcmc->mc_banklinks_reload(true);
	}

			function __get_logo_html() {
				return '<div class="makecommerce-info">'.
					'<div class="makecommerce-logo">'.
					'<a target="_blank" href="http://maksekeskus.ee"><img src="'. plugins_url('/images/makecommerce_logo_en.svg', __FILE__) .'" class="makecommerce-logo"></a>'.
					'</div>'.
					'<div class="makecommerce-links">'.
					'<div class="makecommerce-link"><a target="_blank" href="https://merchant.maksekeskus.ee">Merchant Portal</a></div>'.
					'<div class="makecommerce-link"><a target="_blank" href="https://makecommerce.net/">makecommerce.net</a></div>'.
					'<div class="makecommerce-link"><a target="_blank" href="http://maksekeskus.ee">maksekeskus.ee</a></div>'.
					'</div>'.
					'</div>';
			}

	add_action('woocommerce_get_sections_api', 'mk_admin_add_settings');
	add_filter('woocommerce_get_settings_api', 'mk_admin_all_settings', 10, 2);
	add_action('woocommerce_settings_saved', 'mk_admin_save_settings', 30, 0);

    function mk_admin_restrict_manage_posts() {
        global $typenow;
        if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
			$selected_method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
			$methods = WC()->shipping->load_shipping_methods();
			echo '<select name="_shipping_method" id="shipping_type" class="enhanced">';
			echo '<option value="">'.__('-- filter by shipping method', 'wc_makecommerce_domain') . '</option>';
			foreach ($methods as $method) {
				echo '<option value="'.$method->id.'"'.($selected_method === $method->id ? ' selected="selected"' : '').'>'.$method->title.'</option>';
			}
			echo '</select>';
		}
	}
	function mk_admin_shipping_filter($where, &$wp_query) {
		global $pagenow, $wpdb;
		$method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
		if (is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
			$where .= $GLOBALS['wpdb']->prepare( ' AND ID
				IN (
				SELECT items.order_id
				FROM '.$wpdb->prefix.'woocommerce_order_itemmeta meta, '.$wpdb->prefix.'woocommerce_order_items items
				WHERE meta.order_item_id = items.order_item_id
				AND meta.meta_key = "method_id"
				AND meta.meta_value = %s
			) ', $method );
		}
		return $where;
	}
	add_filter('restrict_manage_posts', 'mk_admin_restrict_manage_posts');
	add_filter('posts_where', 'mk_admin_shipping_filter', 10, 2);

	function mk_admin_bulk_actions() {
		global $post_type;
		if ('shop_order' === $post_type) {
?>
            <script type="text/javascript">
            jQuery(function() {
                jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
                jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
                jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
                jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
			});
			</script>
<?php
			if (!empty($_REQUEST['mk_pdf'])) {
?>
			<script type="text/javascript">
			jQuery(function(){
				window.open('<?php echo $_REQUEST['mk_pdf'] ?>', 'pdf');
			});
			</script>
<?php
			}
		}
	}
	function mk_admin_bulk_action_labels() {
		$wp_list_table = _get_list_table('WP_Posts_List_Table');
		$shipping_request = array('credentials' => array(), 'orders' => array());
		$post_ids = array_map('absint', (array)$_REQUEST['post']);
		mk_get_shipment_ids($post_ids);
	}
	function mk_admin_bulk_action_print() {
		$wp_list_table = _get_list_table('WP_Posts_List_Table');
		$shipping_request = array('credentials' => array(), 'orders' => array());
		$post_ids = array_map('absint', (array)$_REQUEST['post']);
		mk_get_labels($post_ids);
	}
	add_action('admin_footer', 'mk_admin_bulk_actions', 11);
	add_action('admin_action_parcel_machine_labels', 'mk_admin_bulk_action_labels');
	add_action('admin_action_parcel_machine_print_labels', 'mk_admin_bulk_action_print');



	function mk_admin_parcelmachine_order_meta($order) {
		$machine_id = get_post_meta($order->id, '_parcel_machine', true);
		if (empty($machine_id)) return;
		list($provider, $machine) = explode('||', $machine_id);
		if (empty($machine)) return;
		$machine = mk_get_machine($provider, (int)$machine);
		if (!$machine) return;
		echo '<p><strong>'.__('Parcel machine').':</strong><br/>' . $machine['name'] . '<br/><small>' . $machine['address'] . '</small></p>';
		$shipment_id = get_post_meta($order->id, '_parcel_machine_shipment_id', true);
		$shipment_id_error = get_post_meta($order->id, '_parcel_machine_error', true);
		if ($shipment_id) {
			echo '<p><strong>'.__('Parcel machine shipment ID').':</strong><br/>' . $shipment_id . '</small></p>';
		}
		if ($shipment_id_error) {
			echo '<p><strong style="color: red;">'.__('Parcel machine shipment generation error').':</strong><br/>' . $shipment_id_error . '</small></p>';
		}
	}

	function mk_admin_render_shop_order_columns( $column ) {
		global $post, $woocommerce, $the_order;
		if (empty($the_order) || $the_order->id != $post->ID) {
			$the_order = wc_get_order($post->ID);
		}
		if ($column === 'shipping_address') {
			$machine = get_post_meta($the_order->id, '_parcel_machine', true);
			$shipment_id = get_post_meta($the_order->id, '_parcel_machine_shipment_id', true);
			$shipment_id_error = get_post_meta($the_order->id, '_parcel_machine_error', true);
			if ($machine) {
				if ($shipment_id) echo __('Package shipment_id:', 'wc_makecommerce_domain') . ' ' . $shipment_id;
				else if ($shipment_id_error) echo '<span style="color: red;">'.__('Package shipment generation error:', 'wc_makecommerce_domain') . '</span><br/>' .$shipment_id_error;
				else echo __('Shipment ID not generated for delivery', 'wc_makecommerce_domain');
			}
		}
	}
	function mk_add_email_customer_details_fields($fields, $sent_to_admin, $order) {
		$machine_id = get_post_meta($order->id, '_parcel_machine', true);
		if (empty($machine_id)) return $fields;
		list($provider, $machine) = explode('||', $machine_id);
		if (empty($machine)) return $fields;
		$machine = mk_get_machine($provider, (int)$machine);
		if (!$machine) return $fields;
		$fields[] = array('label' => __('Parcel machine'), 'value' => $machine['name'].' - '.$machine['address']);
		return $fields;
	}
	function mk_add_order_customer_details_fields($order) {
		$machine_id = get_post_meta($order->id, '_parcel_machine', true);
		if (empty($machine_id)) return;
		list($provider, $machine) = explode('||', $machine_id);
		if (empty($machine)) return;
		$machine = mk_get_machine($provider, (int)$machine);
		if (!$machine) return;
		echo '<tr>';
		echo '<th>'.__('Parcel machine').'</th>';
		echo '<td>'.$machine['name'].'<br/>'.$machine['address'].'</td>';
		echo '</tr>';
	}
	function mk_admin_product_option_fields($fields) {
		echo '<div class="options_group">';
		woocommerce_wp_checkbox( 
			array( 
				'id'            => '_no_parcel_machine', 
				'wrapper_class' => 'show_if_simple', 
				'label'         => __('Does not fit parcel machine', 'wc_makecommerce_domain'), 
				'description'   => __('When this is checked, parcel machine shipping option is not available for a cart with this product', 'wc_makecommerce_domain')
			)
		);
		echo '</div>';
	}
	function mk_admin_product_fields_save($post_id) {
		$no_parcel_machine = isset($_POST['_no_parcel_machine']) ? 'yes' : 'no';
		update_post_meta($post_id, '_no_parcel_machine', $no_parcel_machine);
	}

	add_action('woocommerce_product_options_shipping', 'mk_admin_product_option_fields');
	add_action('woocommerce_process_product_meta', 'mk_admin_product_fields_save');
	add_action('woocommerce_admin_order_data_after_shipping_address', 'mk_admin_parcelmachine_order_meta', 10, 1);
	add_action('manage_shop_order_posts_custom_column', 'mk_admin_render_shop_order_columns', 3);
	add_filter('woocommerce_email_customer_details_fields', 'mk_add_email_customer_details_fields', 10, 3 );
	add_action('woocommerce_order_details_after_customer_details', 'mk_add_order_customer_details_fields');
	add_action('woocommerce_order_status_processing', 'mk_get_shipment_ids');



	function mk_get_shipment_ids($post_ids) {
		if (!is_array($post_ids)) {
			$post_ids = array($post_ids);
		}
		parcelmachine_add_method();
		$shipping_request = array('credentials' => array(), 'orders' => array());
		foreach ($post_ids as $post_id) {
			$parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
			if (!$parcel_machine) { continue; }
			list($provider, $machine_id) = explode('||', $parcel_machine);
			if (!$provider || !$machine_id) { continue; }
			$provider_uc = mb_strtoupper($provider);
			switch ($provider_uc) {
				case "OMNIVA":
					$transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
					break;
				case "SMARTPOST":
					$transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
					break;
				default:
					break 2;
			}
			if (empty($shipping_request['credentials'][$provider_uc])) {
				$api_user = $transport_class->settings['service_user'];
				$api_password = $transport_class->settings['service_password'];
				if (!$api_user || !$api_password) {
					add_action('admin_notices', 'mk_admin_error');
					continue;
				}
				$shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
			}
			$order = wc_get_order($post_id);
			$sender = array(
				'name' => $transport_class->settings['shop_name'],
				'phone' => $transport_class->settings['shop_phone'],
				'email' => $transport_class->settings['shop_email'],
				'postalCode' => $transport_class->settings['shop_postal_code']
			);
			$shipping_request['orders'][] = array(
				'carrier' => $provider_uc,
				'orderId' => $order->id,
				'destination' => array('destinationId' => $machine_id),
				'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
				'sender' => $sender
			);
		}
		$shipping_request['credentials'] = array_values($shipping_request['credentials']);
		if (empty($shipping_request['orders'])) {
			return;
		}
		$MK = mk_get_api();
		if (!$MK) {
			return;
		}
		try {
			$response = $MK->createShipments($shipping_request);
		} catch (Exception $e) {
			echo $e->getMessage();
			exit();
		}
		foreach ($response as $order) {
			if (!empty($order->orderId) && !empty($order->shipmentId)) {
				update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->shipmentId));
			} else if (!empty($order->orderId) && !empty($order->barCode)) {
				update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->barCode));
			} else if (!empty($order->orderId) && !empty($order->errorMessage)) {
				update_post_meta((int)$order->orderId, '_parcel_machine_error', sanitize_text_field($order->errorMessage));
			}
		}
	}

	function mk_get_labels($post_ids) {
		if (!is_array($post_ids)) {
			$post_ids = array($post_ids);
		}
		$sender = array(
			'name' => get_option('mk_shop_name', ''),
			'phone' => get_option('mk_shop_phone', ''),
			'email' => get_option('mk_shop_email', ''),
			'postalCode' => get_option('mk_shop_postal_code', '')
		);
		parcelmachine_add_method();
		$shipping_request = array('credentials' => array(), 'orders' => array(), 'printFormat' => 'A4');
		foreach ($post_ids as $post_id) {
			$parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
			if (!$parcel_machine) { continue; }
			list($provider, $machine_id) = explode('||', $parcel_machine);
			if (!$provider || !$machine_id) { continue; }
			$provider_uc = mb_strtoupper($provider);
			if (empty($shipping_request['credentials'][$provider_uc])) {
				switch ($provider_uc) {
					case "OMNIVA":
						$transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
						break;
					case "SMARTPOST":
						$transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
						break;
					default:
						break 2;
				}
				$api_user = $transport_class->settings['service_user'];
				$api_password = $transport_class->settings['service_password'];
				if (!$api_user || !$api_password) {
					add_action('admin_notices', 'mk_admin_error');
					continue;
				}
				$shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
			}
			$order = wc_get_order($post_id);
			$shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
			if (!$shipment_id) { continue; }
			$shipping_request['orders'][] = array(
				'carrier' => $provider_uc,
				'orderId' => $order->id,
				'destination' => array('destinationId' => $machine_id),
				'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
				'sender' => $sender,
				'shipmentId' => $shipment_id
			);
		}
		$shipping_request['credentials'] = array_values($shipping_request['credentials']);
		if (empty($shipping_request['orders'])) {
			return;
		}
		$MK = mk_get_api();
		if (!$MK) {
			return;
		}
		try {
			$response = $MK->createLabels($shipping_request);
		} catch (Exception $e) {
			echo $e->getMessage();
			exit();
		}
		if (empty($response->labelUrl)) {
			return;
		}
		$sendback = add_query_arg(array('post_type' => 'shop_order', 'mk_pdf' => urlencode($response->labelUrl)), '');
		wp_redirect(esc_url_raw($sendback));
		exit();
	}



	$MKAPI = false;
	function mk_get_api() {
		global $MKAPI;
		if ($MKAPI) {
			//return $MKAPI;
		}
		$mk_api_type = get_option('mk_api_type', false);
		if (!$mk_api_type) {
			return false;
		}
		$key_prefix     = $mk_api_type.'_';
		$mk_shop_id     = get_option('mk_'.$key_prefix.'shop_id', '');
		$mk_public_key  = get_option('mk_'.$key_prefix.'public_key', '');
		$mk_private_key = get_option('mk_'.$key_prefix.'private_key', '');
		if (!$mk_shop_id || !$mk_public_key || !$mk_shop_id) {
			return false;
		}
		$MKAPI = new Maksekeskus($mk_shop_id, $mk_public_key, $mk_private_key, $mk_api_type === 'live' ? false : true);
		return $MKAPI;
	}
	function mk_get_machines($provider, $country = 'EE') {
		$data         = get_option('mk_machines_cache', false);
		$data_expires = get_option('mk_machines_expires', false);
		if (!$data || $data_expires < time()) {
			$MK = mk_get_api();
			$data = $MK->getDestinations(array('type' => 'APT'));
			update_option('mk_machines_cache', $data);
			update_option('mk_machines_expires', time()+3*60*60);
		}

		$machines = array();
		if (!$data || empty($data)) {
			return array();
		}
		foreach ($data as $machine) {
			if ($machine->country === $country && $machine->type === 'APT' && ($provider === '*' || strtolower($provider) === strtolower($machine->provider))) {
				$machines[] = array(
					'provider' => strtolower($machine->provider),
					'id' => $machine->id,
					'name' => $machine->name, 
					'city' => $machine->city,
					'address' => !empty($machine->address) ? $machine->address : '',
				);
			}
		}
		usort($machines, function($a, $b){ 
			if ($a['city'] === $b['city']) {
				return $a['name'] > $b['name'];
			}
			return $a['city'] > $b['city'];
		});
		return $machines;
	}

	function mk_get_machine($provider, $id) {
		$machines = mk_get_machines($provider);
		foreach ($machines as $machine) {
			if ($machine['provider'] === $provider && $machine['id'] === $id) {
				return $machine;
			}
		}
		return false;
	}
	function mk_admin_error() {
		printf( '<div class="%1$s"><p>%2$s</p></div>', 'notice notice-error', __('Please check that you have configured correctly MakeCommerce API accesses', 'wc_makecommerce_domain')); 
	}
}

```
