<?php
class ControllerCheckoutShippingMethod extends Controller {
	public function index() {
		$this->load->language('checkout/checkout');

		if (isset($this->session->data['shipping_address'])) {
			// Shipping Methods
			$method_data = array();

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

			$results = $this->model_extension_extension->getExtensions('shipping');

			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('extension/shipping/' . $result['code']);
					
					/**
 * order split code starts here
 */
                if ($this->config->get('mpordersplit_status')) {
                    /**
                     * creatng cart backup
                     */
                    $this->load->model('mpordersplit/mpordersplit');
                    $sellerlist = $this->model_mpordersplit_mpordersplit->saveCart();
                    /**
                     * checking if cart only contains admin product
                     */
                    if ( $sellerlist['admincheck'] > 0) {
                        unset($sellerlist['admincheck']);
                        $this->cart->clear();
                        $shipping_skiperrorquote = false;

                        foreach ($sellerlist as $key => $seller) {
                                $this->model_mpordersplit_mpordersplit->sellercartrestore($seller);
                                /**
                                 * [if checking if shipping has any error]
                                 * @param  {[boolean]} $shipping_skiperrorquote [description]
                                 */
                                if ($shipping_skiperrorquote) {
                                    if(isset($quote['quote'][$result['code']]))
                                        unset($this->session->data['ordersplit_shippingmethod'][$quote['quote'][$result['code']]['code']]);
                                    unset($method_data[$result['code']]);
                                    $this->cart->clear();
                                    break;
                                }
                                if(!$this->cart->hasShipping())
                                    continue;
                                $quote = $this->{'model_extension_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);

                                if ($quote && !array_key_exists ($result['code'], $method_data)) {
                                    $method_data[$result['code']] = array(
                                        'title'      => $quote['title'],
                                        'quote'      => $quote['quote'],
                                        'sort_order' => $quote['sort_order'],
                                        'error'      => $quote['error']
                                    );
                                    $wk_tax = $this->tax->calculate($quote['quote'][$result['code']]['cost'],$method_data[$result['code']]['quote'][$result['code']]['tax_class_id'],$this->config->get('config_tax'));
                                } else if($quote) {
                                    $wk_tax += $this->tax->calculate($quote['quote'][$result['code']]['cost'],$method_data[$result['code']]['quote'][$result['code']]['tax_class_id'],$this->config->get('config_tax'));

                                    $method_data[$result['code']]['quote'][$result['code']]['cost'] += $quote['quote'][$result['code']]['cost'];

                                    $method_data[$result['code']]['quote'][$result['code']]['text'] = $this->currency->format($wk_tax, $this->session->data['currency']);
                                }
                                /**
                                 * saving shipping quote for each seller
                                 */
                                if(isset($quote['quote'][$result['code']]))
                                    $this->session->data['ordersplit_shippingmethod'][$quote['quote'][$result['code']]['code']][$seller] = $quote['quote'][$result['code']];
                                if (!empty($quote['error'])) {
                                    $shipping_skiperrorquote = true;
                                }
                                /**
                                 * clearing seller's cart
                                 */
                                $this->cart->clear();
                        } // foreach ends here
                    } else {
                        $quote = $this->{'model_extension_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);

                        if ($quote) {
                            $method_data[$result['code']] = array(
                                'title'      => $quote['title'],
                                'quote'      => $quote['quote'],
                                'sort_order' => $quote['sort_order'],
                                'error'      => $quote['error']
                            );
                        }
                    }
                    $sellerlist = $this->model_mpordersplit_mpordersplit->restoreCart();
                } else {
/**
 * order split code ends here
 */

					$quote = $this->{'model_extension_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);

					if ($quote) {
						$method_data[$result['code']] = array(
							'title'      => $quote['title'],
							'quote'      => $quote['quote'],
							'sort_order' => $quote['sort_order'],
							'error'      => $quote['error']
						);
					}
				/**
* order split code starts here
*/
                }
/**
 * order split code ends here
 */
				}
			}

			$sort_order = array();

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

			array_multisort($sort_order, SORT_ASC, $method_data);

			$this->session->data['shipping_methods'] = $method_data;
		}

		$data['text_shipping_method'] = $this->language->get('text_shipping_method');
		$data['text_comments'] = $this->language->get('text_comments');
		$data['text_loading'] = $this->language->get('text_loading');

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

		if (empty($this->session->data['shipping_methods'])) {
			$data['error_warning'] = sprintf($this->language->get('error_no_shipping'), $this->url->link('information/contact'));
		} else {
			$data['error_warning'] = '';
		}

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

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

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

		if(file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/checkout/shipping_method.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/checkout/shipping_method', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/checkout/shipping_method', $data));
		}

		
	}

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

		$json = array();

		// Validate if shipping is required. If not the customer should not have reached this page.
		if (!$this->cart->hasShipping()) {
			$json['redirect'] = $this->url->link('checkout/checkout', '', true);
		}

		// Validate if shipping address has been set.
		if (!isset($this->session->data['shipping_address'])) {
			$json['redirect'] = $this->url->link('checkout/checkout', '', true);
		}

		// Validate cart has products and has stock.
		if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
			$json['redirect'] = $this->url->link('checkout/cart');
		}

		// Validate minimum quantity requirements.
		$products = $this->cart->getProducts();

		foreach ($products as $product) {
			$product_total = 0;

			foreach ($products as $product_2) {
				if ($product_2['product_id'] == $product['product_id']) {
					$product_total += $product_2['quantity'];
				}
			}

			if ($product['minimum'] > $product_total) {
				$json['redirect'] = $this->url->link('checkout/cart');

				break;
			}
		}

		if (!isset($this->request->post['shipping_method'])) {
			$json['error']['warning'] = $this->language->get('error_shipping');
		} else {
			$shipping = explode('.', $this->request->post['shipping_method']);

			if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
				$json['error']['warning'] = $this->language->get('error_shipping');
			}
		}

		if (!$json) {
			$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];

			$this->session->data['comment'] = strip_tags($this->request->post['comment']);
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}