<?php
class ControllerExtensionModuleBulkProductEditingPro extends Controller
{
	private $type = 'module';
	private $name = 'bulk_product_editing_pro';

	public function index()
	{

		$data['type'] = $this->type;
		$data['name'] = $this->name;
		$data['token'] = $this->session->data['token'];
		$data['exit'] = $this->url->link('extension/extension&type=' . $this->type . '&token=' . $data['token'], 'SSL');

		$data = array_merge($data, $this->loadLanguage('catalog/product'));
		$data = array_merge($data, $this->loadLanguage($this->type . '/' . $this->name));


		$data['breadcrumbs'] = array();
		$data['breadcrumbs'][] = array(
			'text'		=> $data['text_home'],
			'href'		=> $this->url->link('common/dashboard', 'token=' . $data['token'], 'SSL'),
		);
		$data['breadcrumbs'][] = array(
			'text'		=> $data['tab_module'],
			'href'		=> $data['exit'],
		);
		$data['breadcrumbs'][] = array(
			'text'		=> $data['heading_title'],
			'href'		=> $this->url->link('extension/' . $this->type . '/' . $this->name, 'token=' . $data['token'], 'SSL'),
		);

		$data['action'] = $this->url->link('extension/' . $this->type . '/' . $this->name, 'token=' . $data['token'], 'SSL');
		$data['cancel'] = $data['exit'];
		$data['success'] = '';

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


		$this->load->model('tool/image');

		$this->load->model('setting/store');
		$data['stores'] = $this->model_setting_store->getStores();

		$data['store_array'] = array('all' => $data['text_all_stores'], 0 => $this->config->get('config_name'));
		foreach ($data['stores'] as $store) {
			$data['store_array'][$store['store_id']] = $store['name'];
		}

		$this->load->model('localisation/currency');
		$data['currencies'] = $this->model_localisation_currency->getCurrencies();

		$this->load->model('localisation/tax_class');
		$data['tax_classes'] = $this->model_localisation_tax_class->getTaxClasses();

		$this->load->model('localisation/stock_status');
		$data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses();

		$this->load->model('localisation/weight_class');
		$data['weight_classes'] = $this->model_localisation_weight_class->getWeightClasses();

		$this->load->model('localisation/length_class');
		$data['length_classes'] = $this->model_localisation_length_class->getLengthClasses();

		$this->load->model('catalog/recurring');
		$data['recurrings'] = $this->model_catalog_recurring->getRecurrings();

		$this->load->model('customer/customer_group');
		$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();

		$this->load->model('design/layout');
		$data['layouts'] = $this->model_design_layout->getLayouts();

		$this->load->model('localisation/language');
		$data['languages'] = $this->model_localisation_language->getLanguages();

		$this->load->model('catalog/category');
		$data['categories'] = $this->model_catalog_category->getCategories(array('sort' => 'name'));

		$this->load->model('catalog/manufacturer');
		$data['manufacturers'] = $this->model_catalog_manufacturer->getManufacturers();

		$data['language_code'] = $this->language->get('code');
		$data['text_filemanager'] = ucfirst(strtolower($this->language->get('button_add') . ' ' . $this->language->get('tab_image')));
		$data['error_warning'] = '';
		$data['error_name'] = array();
		$data['error_meta_title'] = array();
		$data['error_model'] = '';
		$data['error_date_available'] = '';
		$data['error_keyword'] = '';

		$data['product_description'] = array();
		$data['image'] = '';
		$data['no_image'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		$data['model'] = '';
		$data['barcode'] = '';
		$data['location'] = '';
		$data['product_store'] = array();
		$data['keyword'] = '';
		$data['shipping'] = '';
		$data['price'] = '';
		$data['product_recurrings'] = array();
		$data['tax_class_id'] = '';
		$data['currency_id'] = '';
		$data['date_available'] = '';
		$data['quantity'] = '';
		$data['minimum'] = '';
		$data['subtract'] = '';
		$data['sort_order'] = '';
		$data['stock_status_id'] = '';
		$data['status'] = '';
		$data['weight'] = '';
		$data['weight_class_id'] = '';
		$data['length'] = '';
		$data['width'] = '';
		$data['height'] = '';
		$data['length_class_id'] = '';
		$data['manufacturer_id'] = '';
		$data['manufacturer'] = '';
		$data['product_category'] = array();
		$data['product_categories'] = array();
		$data['product_filters'] = array();
		$data['product_attributes'] = array();
		$data['product_options'] = array();
		$data['option_values'] = array();
		$data['product_profiles'] = array();
		$data['product_discounts'] = array();
		$data['product_specials'] = array();
		$data['product_images'] = array();
		$data['downloads'] = array();
		$data['product_downloads'] = array();
		$data['product_related'] = array();
		$data['product_relateds'] = array();
		$data['points'] = '';
		$data['product_reward'] = array();
		$data['product_layout'] = array();

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

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

		$template_file = DIR_TEMPLATE . 'extension/' . $this->type . '/' . $this->name . '.tpl';

		if (is_file($template_file)) {
			echo $this->load->view(DIR_TEMPLATE . 'catalog/product_form', $data);
			extract($data);
			ob_start();
			require(modification($template_file));
			$output = ob_get_clean();
			echo $output;
		} else {
			echo 'Error loading template file';
		}
	}

	private function hasPermission($permission)
	{
		return ($this->user->hasPermission($permission, $this->type . '/' . $this->name) || $this->user->hasPermission($permission, 'extension/' . $this->type . '/' . $this->name));
	}

	private function loadLanguage($path)
	{
		$_ = array();
		$language = array();
		$admin_language = $this->config->get('config_admin_language');
		foreach (array('english', 'en-gb', $admin_language) as $directory) {
			$file = DIR_LANGUAGE . $directory . '/' . $directory . '.php';
			if (file_exists($file)) require($file);
			$file = DIR_LANGUAGE . $directory . '/default.php';
			if (file_exists($file)) require($file);
			$file = DIR_LANGUAGE . $directory . '/' . $path . '.php';
			if (file_exists($file)) require($file);
			$file = DIR_LANGUAGE . $directory . '/extension/' . $path . '.php';
			if (file_exists($file)) require($file);
			$language = array_merge($language, $_);
		}
		return $language;
	}

	private function getCategoriesByParentId($category_id)
	{
		$category_data = array($category_id);
		$category_query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "category WHERE parent_id = " . (int)$category_id);
		foreach ($category_query->rows as $category) {
			$children = $this->getCategoriesByParentId($category['category_id']);
			if ($children) $category_data = array_merge($children, $category_data);
		}
		return $category_data;
	}

	public function typeahead()
	{

		$search = (strpos($this->request->get['q'], '[')) ? substr($this->request->get['q'], 0, strpos($this->request->get['q'], ' [')) : $this->request->get['q'];

		if ($this->request->get['type'] == 'all') {
			$tables = array('category_description', 'manufacturer', 'product_description');
		} else {
			$tables = array($this->request->get['type'] == 'manufacturer' ? $this->request->get['type'] : $this->request->get['type'] . '_description');
		}

		$results = array();
		foreach ($tables as $table) {
			if ($table == 'product_description') {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE pd.name LIKE '%" . $this->db->escape($search) . "%' OR p.model LIKE '%" . $this->db->escape($search) . "%' GROUP BY p.product_id ORDER BY pd.name ASC LIMIT 0,100");
			} else {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . $table . " WHERE name LIKE '%" . $this->db->escape($search) . "%' ORDER BY name ASC LIMIT 0,100");
			}
			$results = array_merge($results, $query->rows);
		}

		if (empty($results)) {
			$variations = array();
			for ($i = 0; $i < strlen($search); $i++) {
				$variations[] = $this->db->escape(substr_replace($search, '_', $i, 1));
				$variations[] = $this->db->escape(substr_replace($search, '', $i, 1));
				if ($i != strlen($search) - 1) {
					$transpose = $search;
					$transpose[$i] = $search[$i + 1];
					$transpose[$i + 1] = $search[$i];
					$variations[] = $this->db->escape($transpose);
				}
			}
			foreach ($tables as $table) {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . $table . " WHERE name LIKE '%" . implode("%' OR name LIKE '%", $variations) . "%' ORDER BY name ASC LIMIT 0,100");
				$results = array_merge($results, $query->rows);
			}
		}

		$items = array();
		foreach ($results as $result) {
			if (key($result) == 'category_id') {
				$category_id = reset($result);
				$parent_exists = true;
				while ($parent_exists) {
					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category_description WHERE category_id = (SELECT parent_id FROM " . DB_PREFIX . "category WHERE category_id = " . (int)$category_id . " AND parent_id != " . (int)$category_id . ")");
					if (!empty($query->row['name'])) {
						$category_id = $query->row['category_id'];
						$result['name'] = $query->row['name'] . ' > ' . $result['name'];
					} else {
						$parent_exists = false;
					}
				}
			}
			$items[] = html_entity_decode(str_replace(array("\n", "\r"), ' ', $result['name']), ENT_NOQUOTES, 'UTF-8') . ' [' . key($result) . ':' . reset($result) . ']';
		}

		natcasesort($items);
		echo '["' . implode('","', str_replace(array('"', '_id'), array('&quot;', ''), $items)) . '"]';
	}

	public function getProducts()
	{

		$data = $this->loadLanguage($this->type . '/' . $this->name);

		if (!$this->hasPermission('modify')) {
			echo '!' . $data['standard_error'];
			return;
		}
		if (empty($this->request->post['typeahead'])) {
			echo '!' . $data['text_error'];
			return;
		}



		$product_ids = array();

		foreach (explode(';;', $this->request->post['typeahead']) as $member) {
			$parts = explode(':', str_replace(']', '', $member));
			if (strpos($member, 'category:')) {
				$category_sql = "SELECT product_id FROM ps_product_to_category WHERE category_id = " . (int)$parts[1];
				if (!empty($this->request->post['include_subcategories'])) {
					$categories = $this->getCategoriesByParentId($parts[1]);
					foreach ($categories as $category_id) {
						$category_sql .= " OR category_id = " . (int)$category_id;
					}
				}
				$product_id_query = $this->db->query($category_sql);
				foreach ($product_id_query->rows as $p) {
					$product_ids[] = $p['product_id'];
				}
			} elseif (strpos($member, 'manufacturer:')) {
				$product_id_query = $this->db->query("SELECT product_id FROM ps_product WHERE manufacturer_id = " . (int)$parts[1]);
				foreach ($product_id_query->rows as $p) {
					$product_ids[] = $p['product_id'];
				}
			} elseif (strpos($member, 'product:')) {
				$product_ids[] = $parts[1];
			}
		}



		echo implode(',', array_unique($product_ids));
	}

	public function editProduct()
	{
			
		$data = $this->loadLanguage($this->type . '/' . $this->name);

		if (!$this->hasPermission('modify')) {
			echo $data['standard_error'];
			return;
		}
		if (empty($this->request->post['typeahead'])) {
			echo $data['text_error'];
			return;
		}

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

		foreach (explode(',', $this->request->get['product_ids']) as $product_id) {

			if ($this->request->post['store_id'] != 'all') {
				$store_query = $this->db->query("SELECT * FROM ps_product_to_store WHERE product_id = " . (int)$product_id . " AND store_id = " . (int)$this->request->post['store_id']);
				if (!$store_query->num_rows) continue;
			}

			$new_data = $this->request->post;
			$product_data = $this->model_catalog_product->getProduct($product_id);

			$product_data['product_description'] = $this->model_catalog_product->getProductDescriptions($product_id);

			if (empty($this->request->post['remove_attributes'])) {
				$product_data['product_attribute'] = $this->model_catalog_product->getProductAttributes($product_id);
			}
			if (empty($this->request->post['remove_discounts'])) {
				$product_data['product_discount'] = $this->model_catalog_product->getProductDiscounts($product_id);
			}
			if (empty($this->request->post['remove_filters'])) {
				$product_data['product_filter'] = $this->model_catalog_product->getProductFilters($product_id);
			}
			if (empty($this->request->post['remove_images'])) {
				$product_data['product_image'] = $this->model_catalog_product->getProductImages($product_id);
			}
			if (empty($this->request->post['remove_options'])) {
				$product_data['product_option'] = $this->model_catalog_product->getProductOptions($product_id);
			}
			if (empty($this->request->post['remove_related_products'])) {
				$product_data['product_related'] = $this->model_catalog_product->getProductRelated($product_id);
			}

			$product_data['product_reward'] = $this->model_catalog_product->getProductRewards($product_id);

			if (empty($this->request->post['remove_specials'])) {
				$product_data['product_special'] = $this->model_catalog_product->getProductSpecials($product_id);
			}
			if (empty($this->request->post['remove_categories'])) {
				$product_data['product_category'] = $this->model_catalog_product->getProductCategories($product_id);
			}
			if (empty($this->request->post['remove_downloads'])) {
				$product_data['product_download'] = $this->model_catalog_product->getProductDownloads($product_id);
			}

			$product_data['product_layout'] = $this->model_catalog_product->getProductLayouts($product_id);

			if (empty($this->request->post['remove_stores'])) {
				$product_data['product_store'] = $this->model_catalog_product->getProductStores($product_id);
			}
			if (empty($this->request->post['remove_recurring_profiles'])) {
				$product_data['product_recurrings'] = $this->model_catalog_product->getRecurrings($product_id);
			}

			foreach ($product_data as $key => $value) {
				if (!isset($new_data[$key]) || (empty($new_data[$key]) && $new_data[$key] != '0') || $new_data[$key] == -1) {
					$new_data[$key] = $value;
				} elseif (in_array($key, array('price', 'quantity', 'minimum', 'length', 'width', 'height', 'weight', 'points'))) {
					if (strpos($new_data[$key], '+') !== false) {
						$new_data[$key] = $value + (float)str_replace('+', '', $new_data[$key]);
					} elseif (strpos($new_data[$key], '-') !== false) {
						$new_data[$key] = $value - (float)str_replace('-', '', $new_data[$key]);
					} elseif (strpos($new_data[$key], '%') !== false) {
						$new_data[$key] = $value * (float)$new_data[$key] / 100;
						if ($this->request->post['round_percentages'] != '') {
							$new_data[$key] = round($new_data[$key], (int)$this->request->post['round_percentages']);
						}
					}
				} elseif ($key == 'product_description' || $key == 'product_reward' || $key == 'product_seo_url') {
					foreach ($value as $index => $list) {
						foreach ($list as $k => $v) {
							if (isset($new_data[$key][$index][$k]) && strip_tags(html_entity_decode($new_data[$key][$index][$k], ENT_QUOTES, 'UTF-8')) == '') {
								$new_data[$key][$index][$k] = $v;
							}
						}
					}
				} elseif ($key == 'product_layout') {
					foreach ($new_data[$key] as $k => $v) {
						if ((version_compare(VERSION, '2.0', '<') && $v['layout_id'] != -1) || (version_compare(VERSION, '2.0', '>=') && $v != -1)) continue;
						if (isset($product_data[$key][$k])) {
							$new_data[$key][$k] = $product_data[$key][$k];
						} else {
							unset($new_data[$key][$k]);
						}
					}
				} elseif ($key == 'product_option') {
					$option_ids = array();
					foreach ($new_data[$key] as $k => $v) {
						$option_ids[$k] = $v['option_id'];
					}
					foreach ($value as $k => $v) {
						if (in_array($v['option_id'], $option_ids)) {
							$option_ids_key = array_search($v['option_id'], $option_ids);
							if (isset($new_data[$key][$option_ids_key]['product_option_value'])) {
								$pov_ids = array();
								foreach ($new_data[$key][$option_ids_key]['product_option_value'] as $pov) {
									$pov_ids[] = $pov['option_value_id'];
								}
								foreach ($v['product_option_value'] as $old_pov) {
									if (!in_array($old_pov['option_value_id'], $pov_ids)) {
										$new_data[$key][$option_ids_key]['product_option_value'][] = $old_pov;
									}
								}
							}
						} else {
							$new_data[$key][] = $v;
						}
					}
				} elseif ($key == 'product_id') {
					// do nothing
				} elseif (strpos($key, 'product_') !== false) {
					$new_data[$key] = array_merge_recursive($product_data[$key], $new_data[$key]);
					$new_data[$key] = array_intersect_key($new_data[$key], array_unique(array_map('serialize', $new_data[$key])));
				}
			}

			foreach ($new_data as $key => $value) {
				if ($key == 'product_discount' || $key == 'product_special') {
					foreach ($value as $index => $list) {
						if (strpos($list['price'], '+') !== false) {
							$new_data[$key][$index]['price'] = $new_data['price'] + (float)str_replace('+', '', $list['price']);
						} elseif (strpos($list['price'], '-') !== false) {
							$new_data[$key][$index]['price'] = $new_data['price'] - (float)str_replace('-', '', $list['price']);
						} elseif (strpos($list['price'], '%') !== false) {
							$new_data[$key][$index]['price'] = $new_data['price'] * (float)$list['price'] / 100;
							if ($this->request->post['round_percentages'] != '') {
								$new_data[$key][$index]['price'] = round($new_data[$key][$index]['price'], (int)$this->request->post['round_percentages']);
							}
						}
					}
				}
			}

			//var_dump($new_data);
			$this->model_catalog_product->editProduct($product_id, $new_data);
		}
	}
}
 