<?php
class ControllerCatalogPmcbd extends Controller {
	private $error = array();
	
	private function tbl_pmcbd() {
		$query = $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "pmcbd` (  `pmcbd_id` int(11) NOT NULL AUTO_INCREMENT,  `target_product_id` int(11) NOT NULL,  `combo_setting` text NOT NULL,  `status` tinyint(1) NOT NULL, `limitset` int(5) NOT NULL, `date_added` DATE NOT NULL , `date_modified` DATE NOT NULL , PRIMARY KEY (`pmcbd_id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1"); 
	}

	public function index() {
		$this->tbl_pmcbd();
		
		$this->language->load('catalog/pmcbd');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/pmcbd');

		$this->getList();
	}

	public function add() {
		$this->language->load('catalog/pmcbd');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/pmcbd');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_catalog_pmcbd->addPmcbd($this->request->post);

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

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function edit() {
		$this->language->load('catalog/pmcbd');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/pmcbd');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_catalog_pmcbd->editPmcbd($this->request->get['pmcbd_id'], $this->request->post);

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

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
		$this->language->load('catalog/pmcbd');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/pmcbd');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $pmcbd_id) {
				$this->model_catalog_pmcbd->deletePmcbd($pmcbd_id);
			}

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

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}
 	 
	protected function getList() {
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'date_added';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

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

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

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['add'] = $this->url->link('catalog/pmcbd/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['delete'] = $this->url->link('catalog/pmcbd/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');
 
		$data['pmcbds'] = array();

		$filter_data = array(
			'sort'  => $sort,
			'order' => $order,
			'start' => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit' => $this->config->get('config_limit_admin')
		);

		$pmcbd_total = $this->model_catalog_pmcbd->getTotalPmcbd();

		$results = $this->model_catalog_pmcbd->getPmcbds($filter_data);

		foreach ($results as $result) {
			$data['pmcbds'][] = array(
				'pmcbd_id' => $result['pmcbd_id'],
				'target_product_id' => $result['target_product_id'],
				'target_product_data' => $this->getProductData($result['target_product_id']),
				'combo_setting'        => json_decode($result['combo_setting'], true),
				'status'  => $result['status'],
				'limitset'  => $result['limitset'],
				'date_added'    => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
				'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
				'edit'        => $this->url->link('catalog/pmcbd/edit', 'token=' . $this->session->data['token'] . '&pmcbd_id=' . $result['pmcbd_id'] . $url, 'SSL'),
				'delete'      => $this->url->link('catalog/pmcbd/delete', 'token=' . $this->session->data['token'] . '&pmcbd_id=' . $result['pmcbd_id'] . $url, 'SSL')
			);
		}

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

		$data['text_list'] = $this->language->get('text_list');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');

		$data['column_product'] = $this->language->get('column_product');
		$data['column_numofcombo'] = $this->language->get('column_numofcombo');
		$data['column_status'] = $this->language->get('column_status');
		$data['column_limitset'] = $this->language->get('column_limitset');
		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_date_modified'] = $this->language->get('column_date_modified');
		$data['column_action'] = $this->language->get('column_action');

		$data['button_add'] = $this->language->get('button_add');
		$data['button_edit'] = $this->language->get('button_edit');
		$data['button_delete'] = $this->language->get('button_delete');
 
		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'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_date_added'] = $this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . '&sort=date_added' . $url, 'SSL');
		$data['sort_date_modified'] = $this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . '&sort=date_modified' . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $pmcbd_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($pmcbd_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($pmcbd_total - $this->config->get('config_limit_admin'))) ? $pmcbd_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $pmcbd_total, ceil($pmcbd_total / $this->config->get('config_limit_admin')));

		$data['sort'] = $sort;
		$data['order'] = $order;

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

		if(file_exists(DIR_LOCAL_TEMPLATE .'catalog/pmcbd_list.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'catalog/pmcbd_list', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'catalog/pmcbd_list', $data));
		}

		
	}

	protected function getForm() {
		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_form'] = !isset($this->request->get['pmcbd_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['text_none'] = $this->language->get('text_none');
		$data['text_default'] = $this->language->get('text_default');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');

		$data['entry_target_product'] = $this->language->get('entry_target_product');
		$data['entry_combo_product'] = $this->language->get('entry_combo_product');
		$data['entry_discount'] = $this->language->get('entry_discount');
		$data['entry_discount_type'] = $this->language->get('entry_discount_type');
		$data['entry_tabtitle'] = $this->language->get('entry_tabtitle');
		$data['entry_customer_group'] = $this->language->get('entry_customer_group');
		$data['entry_store'] = $this->language->get('entry_store');
 		$data['entry_status'] = $this->language->get('entry_status');
		$data['entry_limitset'] = $this->language->get('entry_limitset');
 
  		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');

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

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

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

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

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		if (!isset($this->request->get['pmcbd_id'])) {
			$data['action'] = $this->url->link('catalog/pmcbd/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		} else {
			$data['action'] = $this->url->link('catalog/pmcbd/edit', 'token=' . $this->session->data['token'] . '&pmcbd_id=' . $this->request->get['pmcbd_id'] . $url, 'SSL');
		}

		$data['cancel'] = $this->url->link('catalog/pmcbd', 'token=' . $this->session->data['token'] . $url, 'SSL');

		if (isset($this->request->get['pmcbd_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$pmcbd_info = $this->model_catalog_pmcbd->getPmcbd($this->request->get['pmcbd_id']);
		}

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

		$this->load->model('localisation/language');
 		$data['languages'] = $this->model_localisation_language->getLanguages();
		
		$data['customer_group'] = $this->getCustomerGroups();
		
		$this->load->model('setting/store');
		$data['stores'] = $this->model_setting_store->getStores();		
		
  		if (isset($this->request->post['target_product_id'])) {
			$data['target_product_id'] = $this->request->post['target_product_id'];
		} elseif (!empty($pmcbd_info)) {
			$data['target_product_id'] = $pmcbd_info['target_product_id'];
		} else {
			$data['target_product_id'] = 0;
		}
		
 		if (isset($this->request->post['target_product_id'])) {
			$data['target_product_data'] = $this->getProductData($this->request->post['target_product_id']);
		} elseif (!empty($pmcbd_info)) {
			$data['target_product_data'] = $this->getProductData($pmcbd_info['target_product_id']);
		} else {
			$data['target_product_data'] = array();
		}
 		
		if (isset($this->request->post['combo_setting'])) {
			$data['combo_setting'] = $this->request->post['combo_setting'];
		} elseif (!empty($pmcbd_info)) {
			$data['combo_setting'] = json_decode($pmcbd_info['combo_setting'], true);
		} else {
			$data['combo_setting'] = array();
		}
		
		if($data['combo_setting']) {
			$row = 0;
			foreach ($data['combo_setting'] as $pmcbdstng) { 
				if(isset($pmcbdstng['product']) && $pmcbdstng['product']) { 
					$data['combo_setting'][$row]['product']  = $this->getpmcbdpro($pmcbdstng['product']);
				}
				$row++;
			} 
		}
   		   
		if (isset($this->request->post['status'])) {
			$data['status'] = $this->request->post['status'];
		} elseif (!empty($pmcbd_info)) {
			$data['status'] = $pmcbd_info['status'];
		} else {
			$data['status'] = true;
		}
		
		if (isset($this->request->post['limitset'])) {
			$data['limitset'] = $this->request->post['limitset'];
		} elseif (!empty($pmcbd_info)) {
			$data['limitset'] = $pmcbd_info['limitset'];
		} else {
			$data['limitset'] = 3;
		}
 
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		if(file_exists(DIR_LOCAL_TEMPLATE .'catalog/pmcbd_form.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'catalog/pmcbd_form', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'catalog/pmcbd_form', $data));
		}

		
	}

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'catalog/pmcbd')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
 
		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'catalog/pmcbd')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}
 
	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
			$this->load->model('catalog/product');
			$this->load->model('catalog/option');

			if (isset($this->request->get['filter_name'])) {
				$filter_name = $this->request->get['filter_name'];
			} else {
				$filter_name = '';
			}

			if (isset($this->request->get['filter_model'])) {
				$filter_model = $this->request->get['filter_model'];
			} else {
				$filter_model = '';
			}

			if (isset($this->request->get['limit'])) {
				$limit = $this->request->get['limit'];
			} else {
				$limit = 5;
			}

			$filter_data = array(
				'filter_name'  => $filter_name,
				'filter_model' => $filter_model,
				'start'        => 0,
				'limit'        => $limit
			);

			$results = $this->model_catalog_product->getProducts($filter_data);

			foreach ($results as $result) {
				$option_data = array();

				$product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

				foreach ($product_options as $product_option) {
					$option_info = $this->model_catalog_option->getOption($product_option['option_id']);

					if ($option_info) {
						$product_option_value_data = array();

						foreach ($product_option['product_option_value'] as $product_option_value) {
							$option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

							if ($option_value_info) {
								$product_option_value_data[] = array(
									'product_option_value_id' => $product_option_value['product_option_value_id'],
									'option_value_id'         => $product_option_value['option_value_id'],
									'name'                    => $option_value_info['name'],
									'price'                   => (float)$product_option_value['price'] ? $this->currency->format($product_option_value['price'], $this->config->get('config_currency')) : false,
									'price_prefix'            => $product_option_value['price_prefix']
								);
							}
						}

						$option_data[] = array(
							'product_option_id'    => $product_option['product_option_id'],
							'product_option_value' => $product_option_value_data,
							'option_id'            => $product_option['option_id'],
							'name'                 => $option_info['name'],
							'type'                 => $option_info['type'],
							'value'                => $product_option['value'],
							'required'             => $product_option['required']
						);
					}
				}

				$json[] = array(
					'product_id' => $result['product_id'],
					'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
					'model'      => $result['model'],
					'option'     => $option_data,
					'price'      => $result['price']
				);
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
	
	public function getProductData($product_id) {
		
		$product_data = array();

		if ($product_id) {
			$this->load->model('catalog/product');
 
			$result = $this->model_catalog_product->getProduct($product_id);

			$product_data = array(
				'product_id' => $result['product_id'],
				'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
				'model'      => $result['model'],
 			);
		}
		
		return $product_data;
  	}
	
	public function getCustomerGroups($data = array()) {
		$sql = "SELECT * FROM " . DB_PREFIX . "customer_group cg LEFT JOIN " . DB_PREFIX . "customer_group_description cgd ON (cg.customer_group_id = cgd.customer_group_id) WHERE cgd.language_id = '" . (int)$this->config->get('config_language_id') . "'";

		$sort_data = array(
			'cgd.name',
			'cg.sort_order'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY cgd.name";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}  
	
	public function getpmcbdpro($product_arr) {
		// product						
		$this->load->model('catalog/product');
		
		if (!empty($product_arr)) {
			$product_arr = $product_arr;
		} else {
			$product_arr = array();
		} 		
		
		$product_arr_data = array();
		
		if($product_arr && is_array($product_arr)) {
			foreach ($product_arr as $product_id) {
				$product_info = $this->model_catalog_product->getProduct($product_id);
				if ($product_info) {
					$product_arr_data[] = array(
						'product_id' => $product_info['product_id'],
						'name'       => $product_info['name']
					);
				}
			}
		}
		return $product_arr_data ;
	}	
}