<?php
class ControllerExtensionShippingcanadapost extends Controller {
	private $error = array();

	public function install() {

		$this->load->model('extension/shipping/canadapost');
		$this->model_extension_shipping_canadapost->createTable();

		$this->load->model('setting/event');

		$code     = "shipping_canadapost_getData";
		$trigger  = "admin/view/sale/order_info";
		$action   = "sale/canadapost_shipping/getData";
		$this->model_setting_event->addEvent($code, $trigger, $action);
	  
	}

	public function uninstall() {

		$this->load->model('extension/shipping/canadapost');
		$this->model_extension_shipping_canadapost->deleteTable();

		$this->load->model('setting/event');
		$this->model_setting_event->deleteEventByCode('shipping_canadapost_getData');
	}
	
	public function index() {
		$data = array();

		$data = array_merge($data, $this->load->language('extension/shipping/canadapost'));

		$this->document->setTitle($data['heading_title']);

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->model_setting_setting->editSetting('shipping_canadapost', $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=shipping', true));
		}

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

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_extension'),
			'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=shipping', true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/shipping/canadapost', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['action'] = $this->url->link('extension/shipping/canadapost', 'user_token=' . $this->session->data['user_token'],true);
		$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=shipping', true);

		$data['user_token'] = $this->session->data['user_token'];
		
    $data['servicesDom'] = array(
    	'DOM.RP'  => $data['text_service'],
    	'DOM.EP'  => $data['text_service1'],
    	'DOM.XP'  => $data['text_service2'],
    	'DOM.XP.CERT'  => $data['text_service3'],
    	'DOM.PC'  => $data['text_service4'],
    	'DOM.DT'  => $data['text_service5'],
    	'DOM.LIB'  => $data['text_service6'],
    );

    $data['servicesUsa'] = array(
      'USA.EP'  => $data['text_service7'],
			'USA.PW.ENV'  => $data['text_service8'],
			'USA.PW.PAK'  => $data['text_service9'],
			'USA.PW.PARCEL'  => $data['text_service11'],
			'USA.XP' => $data['text_service14'],
			'USA.TP' => $data['text_service13'],
    );

    $data['servicesInn'] = array(
      'INT.XP'  => $data['text_INT_XP'],
			'INT.IP.AIR'  => $data['text_INT_IP_AIR'],
			'INT.IP.SURF'  => $data['text_INT_IP_SURF'],
			'INT.SP.AIR'  => $data['text_INT_SP_AIR'],
			'INT.PW.PARCEL'  => $data['text_INT_PW_PARCEL'],
			'INT.SP.SURF'  => $data['text_INT_SP_SURF'],
			'INT.TP'  => $data['text_INT_TP'],
    );

    $data['services'] = array_merge($data['servicesDom'], $data['servicesUsa'],$data['servicesInn']);

    $form_keys = array(
    	'api_key',
    	'api_password',
    	'customer_number',
    	'contract_id',
    	'status',
    	'test',
    	'sort_order',
    	'geo_zone_id',
    	'tax_class_id',
    	'time_estimated',
    	'handling_fee_status',
    	'handling_fee',
    	'fee_amount',
    	'free_shipping_min_amount',
    	'free_shipping_amount_value',
    	'domestic_free_method',
    	'usa_free_method',
    	'inn_free_method',
    	'show_error_to_user',
			'delivery_time_offset',
			'title',
			'address_line1',
			'address_line2',
			'city',
			'postcode',
			'origin_country',
			'origin_zone',
			'custom_error',
			'origin_address',
    );

		foreach ($form_keys as $form_value) {
		    if (isset($this->request->post['shipping_canadapost_'.$form_value])) {
		        $data['shipping_canadapost_'.$form_value] = $this->request->post['shipping_canadapost_'.$form_value];
		    } else {
		        $data['shipping_canadapost_'.$form_value] = $this->config->get('shipping_canadapost_'.$form_value);
		    }
		}

   if (isset($this->request->post['shipping_canadapost_service'])) {
			$data['shipping_canadapost_service'] = $this->request->post['shipping_canadapost_service'];
		} elseif ($this->config->has('shipping_canadapost_service') && !isset($this->error['error_canadapost_service']) ) {
			$data['shipping_canadapost_service'] = $this->config->get('shipping_canadapost_service');
		} else {
			$data['shipping_canadapost_service'] = array();
		}

    if (isset($this->request->post['shipping_canadapost_country'])) {
			$data['shipping_canadapost_country'] = $this->request->post['shipping_canadapost_country'];
		} elseif ($this->config->has('shipping_canadapost_country')  && !isset($this->error['error_canadapost_country'])) {
			$data['shipping_canadapost_country'] = $this->config->get('shipping_canadapost_country');
		} else {
			$data['shipping_canadapost_country'] = array();
		}
    $error_keys = array(
    	'api_key',
    	'api_password',
    	'customer_number',
    	'fee_amount',
    	'service',
    	'country',
			'delivery_time_offset',
			'address_line1',
			'title',
			'city',
			'origin_country',
			'origin_zone',
			'custom_error',
			'address_line2',
    );

    foreach ($error_keys as $form_value) {
	    if (isset($this->error['error_shipping_canadapost_'.$form_value])) {
	        $data['error_shipping_canadapost_'.$form_value] = $this->error['error_shipping_canadapost_'.$form_value];
	    } else {
	    	$data['error_shipping_canadapost_'.$form_value] = '';
	    }
		}

    if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

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

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

		$data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

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

		$data['tax_classes'] = $this->model_localisation_tax_class->getTaxClasses();

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

		$data['Countries'] = $this->model_localisation_country->getCountries();
		
		$this->load->model('localisation/language');

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

	
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('extension/shipping/canadapost', $data));
	}

  /**
  * [this function validate the permisssion for user access and also validate required fields]
  * @return [array] [Error containing all error massages]
  */
	protected function validate() {
		if (!$this->user->hasPermission('modify', 'extension/shipping/canadapost')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
		
		$this->load->model('localisation/language');
		$languages = $this->model_localisation_language->getLanguages();

		foreach($languages as $language) {

			if (isset($this->request->post['shipping_canadapost_title']) && is_array($this->request->post['shipping_canadapost_title']) && !empty($this->request->post['shipping_canadapost_title'])) {
				if (isset($this->request->post['shipping_canadapost_title'][$language['language_id']]) && strlen(trim($this->request->post['shipping_canadapost_title'][$language['language_id']])) > 30 || strlen(trim($this->request->post['shipping_canadapost_title'][$language['language_id']])) < 5 || ctype_space($this->request->post['shipping_canadapost_title'][$language['language_id']])) {
					$this->error['error_shipping_canadapost_title'][$language['language_id']] = $this->language->get('error_shipping_name'); 
				}
			} else {
				$this->error['error_shipping_canadapost_title'][$language['language_id']] = $this->language->get('error_shipping_name'); 
			}

			if (isset($this->request->post['shipping_canadapost_custom_error']) && is_array($this->request->post['shipping_canadapost_custom_error']) && !empty($this->request->post['shipping_canadapost_custom_error'])) {
				if (isset($this->request->post['shipping_canadapost_custom_error'][$language['language_id']]) && strlen(trim($this->request->post['shipping_canadapost_custom_error'][$language['language_id']])) > 50 || strlen(trim($this->request->post['shipping_canadapost_custom_error'][$language['language_id']])) < 5 || ctype_space($this->request->post['shipping_canadapost_custom_error'][$language['language_id']])) {
					$this->error['error_shipping_canadapost_custom_error'][$language['language_id']] = $this->language->get('error_custom_msg'); 
				}
			} else {
				$this->error['error_shipping_canadapost_custom_error'][$language['language_id']] = $this->language->get('error_custom_msg'); 
			}

		}
			

			if(!isset($this->request->post['shipping_canadapost_api_key'])) {
				$this->error['error_shipping_canadapost_api_key'] = $this->language->get('error_canadapost_api_key');
			} elseif (isset($this->request->post['shipping_canadapost_api_key']) && !trim($this->request->post['shipping_canadapost_api_key']) || ctype_space($this->request->post['shipping_canadapost_api_key'])) {
				$this->error['error_shipping_canadapost_api_key'] = $this->language->get('error_canadapost_api_key'); 
			}

			if(!isset($this->request->post['shipping_canadapost_api_password'])) {
				$this->error['error_shipping_canadapost_api_password'] = $this->language->get('error_canadapost_api_password'); 
			} elseif (isset($this->request->post['shipping_canadapost_api_password']) && !trim($this->request->post['shipping_canadapost_api_password']) || ctype_space($this->request->post['shipping_canadapost_api_password'])) {
				$this->error['error_shipping_canadapost_api_password'] = $this->language->get('error_canadapost_api_password'); 
			}
			
			if(!isset($this->request->post['shipping_canadapost_customer_number'])) {
				$this->error['error_shipping_canadapost_customer_number'] = $this->language->get('error_canadapost_customer_number'); 
			} elseif (isset($this->request->post['shipping_canadapost_customer_number']) && !trim($this->request->post['shipping_canadapost_customer_number']) || !is_numeric($this->request->post['shipping_canadapost_customer_number']) || ctype_space($this->request->post['shipping_canadapost_customer_number'])) {
				$this->error['error_shipping_canadapost_customer_number'] = $this->language->get('error_canadapost_customer_number'); 
			}

			if (isset($this->request->post['shipping_canadapost_origin_address']) && $this->request->post['shipping_canadapost_origin_address'] == 'custom') {
				
				if(!isset($this->request->post['shipping_canadapost_address_line1'])) {
					$this->error['error_shipping_canadapost_address_line1'] = $this->language->get('error_address_line1');
				} elseif (isset($this->request->post['shipping_canadapost_address_line1']) && strlen(trim($this->request->post['shipping_canadapost_address_line1'])) < 5 || strlen(trim($this->request->post['shipping_canadapost_address_line1'])) > 50 || ctype_space($this->request->post['shipping_canadapost_address_line1'])) {
					$this->error['error_shipping_canadapost_address_line1'] = $this->language->get('error_address_line1'); 
				}

				if (isset($this->request->post['shipping_canadapost_address_line2']) && trim($this->request->post['shipping_canadapost_address_line2']) != '' && strlen(trim($this->request->post['shipping_canadapost_address_line2'])) < 5 || strlen(trim($this->request->post['shipping_canadapost_address_line2'])) > 50 || ctype_space($this->request->post['shipping_canadapost_address_line2'])) {
					$this->error['error_shipping_canadapost_address_line2'] = $this->language->get('error_address_line2'); 
				}
	
				if(!isset($this->request->post['shipping_canadapost_city'])) {
					$this->error['error_shipping_canadapost_city'] = $this->language->get('error_city'); 
				} elseif (isset($this->request->post['shipping_canadapost_city']) && strlen(trim($this->request->post['shipping_canadapost_city'])) < 2 || strlen(trim($this->request->post['shipping_canadapost_city'])) > 20 || ctype_space($this->request->post['shipping_canadapost_city'])) {
					$this->error['error_shipping_canadapost_city'] = $this->language->get('error_city'); 
				}
	
				if(!isset($this->request->post['shipping_canadapost_origin_country'])) {
					$this->error['error_shipping_canadapost_origin_country'] = $this->language->get('error_country');
				} elseif (isset($this->request->post['shipping_canadapost_origin_country']) && !$this->request->post['shipping_canadapost_origin_country']) {
					$this->error['error_shipping_canadapost_origin_country'] = $this->language->get('error_country'); 
				}
	
				if(!isset($this->request->post['shipping_canadapost_origin_zone'])) {
					$this->error['error_shipping_canadapost_origin_zone'] = $this->language->get('error_origin_zone');
				} elseif (isset($this->request->post['shipping_canadapost_origin_zone']) && !$this->request->post['shipping_canadapost_origin_zone']) {
					$this->error['error_shipping_canadapost_origin_zone'] = $this->language->get('error_origin_zone'); 
				}
	
			}
			
			

	 if(isset($this->request->post['shipping_canadapost_fee_amount']) && $this->request->post['shipping_canadapost_fee_amount']) {
			 if(!is_numeric($this->request->post['shipping_canadapost_fee_amount']))  {
				 $this->error['error_canadapost_fee_amount'] = $this->language->get('error_canadapost_fee_amount _numeric');
		     $this->error['warning'] = $this->language->get('error_empty');
			 } else {
			   $sign = min(1, max(-1, $this->request->post['shipping_canadapost_fee_amount']));
			   if($sign == -1) {
			 	   $this->error['error_shipping_canadapost_fee_amount'] = $this->language->get('error_canadapost_fee_amount _numeric');
		       $this->error['warning'] = $this->language->get('error_empty');
			   }
		   }
		}

    if(isset($this->request->post['shipping_canadapost_delivery_time_offset']) && $this->request->post['shipping_canadapost_delivery_time_offset']) {
			if(!ctype_digit($this->request->post['shipping_canadapost_delivery_time_offset'])) {
				 $this->error['error_canadapost_delivery_time_offset'] = $this->language->get('error_canadapost_delivery_time_offset_digit');
		     $this->error['warning'] = $this->language->get('error_empty');
			}
		}

		if(!isset($this->request->post['shipping_canadapost_service'])) {
			$this->error['error_shipping_canadapost_service'] = $this->language->get('error_canadapost_service');
		  $this->error['warning'] = $this->language->get('error_empty');
		}

		if(!isset($this->request->post['shipping_canadapost_country'])) {
			$this->error['error_shipping_canadapost_country'] = $this->language->get('error_canadapost_country');
		   $this->error['warning'] = $this->language->get('error_empty');
		}

		if (!empty($this->error) && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_empty');
		}
	    return !$this->error;
	}
}
