<?php
/*
 * @version			$Id: index.php 10381 2008-06-01 03:35:53Z $
 * @package			Carteasy
 * @copyright		Copyright (C) 2005 - 2011 Wlanium
 * @license			proprietary
 * @author			Thomas Bartelt
 * Carteasy is a web shop system
 */

#[\AllowDynamicProperties]
class Structure extends Main {

	protected $base_object;
	public $list_table_config = array(
		'title' => 'Seitenstruktur',
		'db_table' => 'structure',
		'list_fields' => array(
			array(
				'db_field' => 'id',
				'name' => 'Pfad',
				'rewrite_function' => 'full_name_path',
				'sortable' => 0
			),
			array(
				'db_field' => 'name',
				'name' => 'Bezeichnung',
				'sortable' => 0
			),
			array(
				'db_field' => 'type',
				'name' => 'Seitentyp',
				'rewrite_function' => 'type_values',
				'sortable' => 0
			),
			array(
				'db_field' => 'active',
				'name' => 'Status',
				'rewrite_function' => 'state_values',
				'sortable' => 0
			)
		),
		'search_fields' => array('name'),
		'db_id_field' => 'id',
		'edit_link' => 'index.php?admin_modul=admin_structure&id=',
		'toolbar' => array(
			'delete' => 1,
			'new' => 'index.php?admin_modul=admin_structure',
			'copy' => 0,
			'select_all' => 1,
			'edit' => 0,
			'actions' => 0,
			'filter' => 0,
			'search' => 1
		)
	);
	public $content_module = array(
		'0' => 'website_dyncontent',
		'1' => 'website_internal_link',
		'2' => 'website_external_link',
		'3' => 'website_contact',
		'4' => 'website_shoppingcart',
		'5' => 'website_customercenter',
		'6' => 'website_shippingtable',
		'7' => 'website_cashdesk',
		'8' => 'website_search',
		'9' => 'website_customer_registration',
		'10' => 'website_customer_login',
		'11' => 'website_item_memory',
		'12' => 'website_sitemap',
		'13' => 'website_password_forgotten',
		'14' => 'website_item_memory', // redundant
		'15' => 'website_sitemap',
		'16' => 'website_recommendation',
		'17' => 'website_order_editor',
		'18' => 'website_manufacturers',
		'19' => 'website_google_map',
		'20' => 'website_show_opinion',
		'21' => 'website_new_opinion',
		'22' => 'website_newsletter_registration',
		'23' => 'website_news',
		'24' => 'website_recommendation',
		'25' => 'website_item_type_list'
	);
	private $structure_fields = array(
		'parent_id' => 'integer',
		'name' => 'text',
		'type' => 'integer',
		'item_type' => 'integer',
		'link_reference' => 'text',
		'link_target' => 'integer',
		'link_image' => 'text',
		'link_css' => 'text',
		'header_image_link' => 'text',
		'active' => 'integer',
		'customer_group' => 'integer',
		'sitemap_activ' => 'integer',
		'show_after_login' => 'integer',
		'short_uri' => 'text',
		'image_alt_text' => 'text',
		'theme_id' => 'integer',
		'seo_title' => 'text',
		'seo_description' => 'text',
		'seo_keywords' => 'text',
		'get_parent_discounts' => 'integer'
	);
	public $structure_id = 0;
	public $activated_structures = array();
	private $config;
	private $error;
	private $url;

	public function __construct($base_object) {
		$this->config_object = $base_object->config;
		$this->db = $base_object->db;
		$this->base_object = $base_object;
		$this->path = ROOT_DIR.'web/'.SHOP_SYSTEM.'/images/structure/';
		$this->header_path = ROOT_DIR.'web/'.SHOP_SYSTEM.'/images/header/';
		$this->url = './web/'.SHOP_SYSTEM.'/images/structure/';
		$this->error = '';

		$this->structure_fields['name_en'] = 'text';
	}

	// end __construct

	public function type_values() {
		return array(
			'0' => 'Dynamische Seite',
			'1' => 'Interne Verlinkung',
			'2' => 'Externe Verlinkung',
			'3' => 'Kontaktformular',
			'4' => 'Warenkorbansicht',
			'5' => 'Kundencenter',
			'6' => 'Versandkostentabelle',
			'7' => 'Kassengang',
			'8' => 'Suche',
			'9' => 'Kundenregistrierung',
			'10' => 'Kundenlogin',
			'11' => 'Gemerkte Artikel',
			'12' => 'Sitemap',
			'13' => 'Passwort vergessen',
			'14' => 'Gemerkte Artikel', // redundant
			'15' => 'Sitemap',
			'16' => 'Seite weiterempfehlen',
			'17' => 'Bestellbearbeitung',
			'18' => 'Herstellerübersicht',
			'19' => 'Google Maps',
			'20' => 'Kundenbewertungen',
			'21' => 'Neue Kundenbewertung',
			'22' => 'Newsletter Registrierung',
			'23' => 'News',
			'24' => 'Seite weiterempfehlen',
			'25' => 'Artikelliste nach Typen'
		);
	}

	public function state_values() {
		return array(
			'0' => 'inaktiv',
			'1' => 'aktiv',
			'2' => 'gruppenspezifisch'
		);
	}

	public function full_name_path() {
		$all_structure = $this->get_all_tree_full_path();
		$data = array();
		foreach ($all_structure as $structure) {
			if ($structure->path_name) {
				$data[$structure->id] = $structure->path_name.'-&gt;'.$structure->name;
			} else {
				$data[$structure->id] = $structure->name;
			}
		}
		return $data;
	}

	public function get_list_items($setting) {
		// init rewrite functions
		$rewrite_indexes = array();
		$count_fields = count($this->list_table_config['list_fields']);
		for ($i = 0; $i < $count_fields; $i++) {
			if (isset($this->list_table_config['list_fields'][$i]['rewrite_function'])) {
				$this->list_table_config['list_fields'][$i]['rewrite_function'] = $this->{$this->list_table_config['list_fields'][$i]['rewrite_function']}();
				$rewrite_indexes[] = $i;
			}
		}

		$data = array();
		$filter_sql = '';
		// search
		if (isset($setting['search_string']) && $setting['search_string'] != '') {
			$count_search_fields = count($this->list_table_config['search_fields']);
			for ($i = 0; $i < $count_search_fields; $i++) {
				if ($i == 0) {
					$filter_sql .= " WHERE ".$this->list_table_config['search_fields'][$i]." like '%".$setting['search_string']."%'";
				} else {
					$filter_sql .= " || ".$this->list_table_config['search_fields'][$i]." like '%".$setting['search_string']."%'";
				}
			}
		}
		// list filter
		$list_filter = '';
		if (isset($this->list_table_config['list_filter']) && $this->list_table_config['list_filter']) {
			foreach ($this->list_table_config['list_filter'] as $filter_item) {
				if ($list_filter) {
					$list_filter .= " AND ".$filter_item['db_field']." ".$filter_item['relational_operator']." '".$filter_item['value']."'";
				} else {
					$list_filter .= $filter_item['db_field']." ".$filter_item['relational_operator']." '".$filter_item['value']."'";
				}
			}
			if ($filter_sql) {
				$filter_sql .= ' AND ('.$list_filter.')';
			} else {
				$filter_sql .= ' WHERE '.$list_filter;
			}
		}

		// group by
		$group_by = '';
		if (isset($this->list_table_config['list_group_by']) && $this->list_table_config['list_group_by']) {
			$group_by = ' GROUP BY '.$this->list_table_config['list_group_by'];
		}

		// get count items
		$sql = "SELECT COUNT(distinct(".$this->list_table_config['db_id_field'].")) FROM ".$this->list_table_config['db_table'].$filter_sql;
		$result = $this->db->query($sql);
		if ($this->db->error) {
			$log_object = Logger::get_instance();
			$log_object->info('Error in /core/main_class.php->get_list_items()', $this->db->error.', sql:'.$sql);
			$count = 0;
		} else {
			$count = $result->fetch_array();
		}
		$data['count_list_items'] = $count[0];
		/*$data['count_pages'] = (int)ceil($data['count_list_items'] / $setting['max_list_items']);
		if ($data['count_pages'] < 1) {*/
		$data['count_pages'] = 1;
		/*}
		if ($data['count_pages'] < $setting['actual_page']) {
			$setting['actual_page'] = $data['count_pages'];
		}*/

		$select_fields = ' '.$this->list_table_config['db_id_field'].' as object_id';
		$count_fields = count($this->list_table_config['list_fields']);
		for ($i = 0; $i < $count_fields; $i++) {
			$select_fields .= ', '.$this->list_table_config['list_fields'][$i]['db_field'];
		}
		$sql = "SELECT ".$select_fields." FROM ".$this->list_table_config['db_table'].$filter_sql.$group_by;

		// set order
		if (isset($setting['sort_item']) && $setting['sort_item'] && isset($setting['sort_direction'])) {
			if ($setting['sort_direction'] == 'up') {
				$sql .= " ORDER BY ".$setting['sort_item']." ASC ";
			} else {
				$sql .= " ORDER BY ".$setting['sort_item']." DESC ";
			}
		}

		// set limit
		/* if (isset($setting['max_list_items']) && isset($setting['actual_page'])) {
			if ($setting['actual_page'] == 1) {
				$sql .= " LIMIT 0, ".$this->db->real_escape_string($setting[max_list_items]);
			}
			else {
				$start = (($setting['actual_page'] - 1) * $setting['max_list_items']);
				$sql .= " LIMIT ".$start.', '.$this->db->real_escape_string($setting['max_list_items']);
			}
		} */
		$data['actual_page'] = $setting['actual_page'];
		$data['sort_item'] = $setting['sort_item'];
		$data['sort_direction'] = $setting['sort_direction'];
		$result = $this->db->query($sql);
		if ($this->db->error) {
			$log_object = Logger::get_instance();
			$log_object->info('Error in /core/main_class.php->get_list_items()', $this->db->error.', sql:'.$sql);
		}

		$data['list_items'] = array();
		if ($result) {
			while ($row = $result->fetch_assoc()) {
				// rewrite result
				if ($rewrite_indexes) {
					foreach ($rewrite_indexes as $index) {
						if (isset($this->list_table_config['list_fields'][$index]['rewrite_function'][$row[$this->list_table_config['list_fields'][$index]['db_field']]])) {
							$row[$this->list_table_config['list_fields'][$index]['db_field']] = $this->list_table_config['list_fields'][$index]['rewrite_function'][$row[$this->list_table_config['list_fields'][$index]['db_field']]];
						} else {
							$row[$this->list_table_config['list_fields'][$index]['db_field']] = '[not defiened]';
						}
					}
				}
				$data['list_items'][] = $row;
			}
		}

		foreach ($data['list_items'] as $nr => $inhalt) {
			$name[$nr] = strtolower($inhalt['id']);
		}

		array_multisort($name, SORT_ASC, $data['list_items']);

		return $data;
	}

	public function get_error() {
		return $this->error;
	}

	// end get_error

	public function get_data($id = false) {
		$sql = "SELECT * FROM structure ";

		if ($id) {
			$sql .= "WHERE id=".$this->db->real_escape_string($id);
		} else if ($this->structure_id) {
			$sql .= "WHERE id=".$this->db->real_escape_string($this->structure_id);
		} else {
			$this->error = 'no id';

			return false;
		}

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

		if ($result->num_rows > 0) {
			return $result->fetch_object();
		}

		$this->error = 'no results';

		return false;
	}

	// end get_data

	public function create($data) {
		if ($data) {
			if (isset($data['short_uri'])) {
				if (!$data['short_uri']) {
					$data['short_uri'] = $data['name'];
				}
				$data['short_uri'] = $this->short_uri($data['short_uri']);
			}

			$sql = "INSERT INTO structure SET ";

			foreach ($data as $var_name => $value) {
				$value = $this->db->real_escape_string($value);
				if ($this->structure_fields[$var_name] == 'integer') {
					$sql .= $var_name.' = '.$value.', ';
				} else {
					$sql .= $var_name.' = "'.$value.'", ';
				}
			}

			$sql = substr($sql, 0, -2);

			$result = $this->db->query($sql);
			if ($result) {
				$this->structure_id = $this->db->insert_id;

				// multi create
				$additional_names = array(2, 3, 4, 5, 6, 7, 8, 9, 10);
				foreach ($additional_names as $number) {
					$name = $_POST['multi_create_name'.$number];
					if ($name) {
						$data['name'] = $name;
						if (isset($data['short_uri'])) {
							if (!$data['short_uri']) {
								$data['short_uri'] = $data['name'];
							}
							$data['short_uri'] = $this->short_uri($data['short_uri']);
						}
						$sql = "INSERT INTO structure SET ";
						foreach ($data as $var_name => $value) {
							$value = $this->db->real_escape_string($value);
							if ($this->structure_fields[$var_name] == 'integer') {
								$sql .= $var_name.' = '.$value.', ';
							} else {
								$sql .= $var_name.' = "'.$value.'", ';
							}
						}
						$sql = substr($sql, 0, -2);
						$this->db->query($sql);
					}
				}

				return $this->structure_id;
			}
		}
		return false;
	}

	function short_uri($short_uri, $id = false) {
		$short_uri = str_replace(array('ä', 'Ä', 'ö', 'Ö', 'ü', 'Ü', 'ß'), array('ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss'), $short_uri);
		$short_uri = preg_replace("@[^0-9aA-zZ\-]@si", "-", $short_uri);
		$short_uri = preg_replace("@(-{2,})@si", "-", $short_uri);

		$new_uri = '';
		$old_uri = $short_uri;
		$i = 0;
		while ($new_uri == '') {
			if ($id) {
				$sql = "SELECT id FROM structure WHERE short_uri = '$short_uri' AND id != $id";
			} else {
				$sql = "SELECT id FROM structure WHERE short_uri = '$short_uri'";
			}
			$result = $this->db->query($sql);
			if ($result->num_rows == 0) {
				$new_uri = $short_uri;
			} else {
				$i++;
				$short_uri = $old_uri.'_'.$i;
			}
		}
		return $new_uri;
	}

	public function update($data) {
		if (isset($data['short_uri'])) {
			if (!$data['short_uri']) {
				$data['short_uri'] = $data['name'];
			}
			$data['short_uri'] = $this->short_uri($data['short_uri'], $this->structure_id);
		}

		if ($data) {
			$sql = "UPDATE structure SET ";
			foreach ($data as $var_name => $value) {
				$value = $this->db->real_escape_string($value);
				if ($this->structure_fields[$var_name] == 'integer') {
					$sql .= $var_name.'='.$value.', ';
				} else {
					$sql .= $var_name.'="'.$value.'", ';
				}
			}
			$sql = substr($sql, 0, -2);


			$sql .= ' WHERE id='.$this->structure_id;
			$this->db->query($sql);
		}
		return;
	}

	public function update_sort($sort_item_ids, $sort_item_pos) {
		for ($i = 0; $i < count($sort_item_ids); $i++) {
			$sql = "UPDATE structure
					SET pos=".$this->db->real_escape_string($sort_item_pos[$i])."
					WHERE id=".$this->db->real_escape_string($sort_item_ids[$i]);
			$this->db->query($sql);
		}
		return;
	}

	public function get_all() {
		$result = $this->db->query("SELECT * FROM structure ORDER BY pos");

		while ($obj = $result->fetch_object()) {
			$data[$obj->id] = $obj;
		}

		return $data;
	}


	// end get_all

	public function get_all_tree($parent_id, $selected_ids = false, $customer_group_id = 0) {
		$selected_data = array();
		$this->db = Registry::get('base')->db;

		$rev_array = array();
		if ($selected_ids && $selected_ids[0]) {
			$sql = "SELECT * FROM structure WHERE parent_id in(".implode(",", $selected_ids).") AND (active = 1 OR (active = 2 && customer_group=".$customer_group_id.")) ORDER BY pos ASC";
			$result = $this->db->query($sql);
			$rev_array = array_reverse($selected_ids);
			while ($obj = $result->fetch_object()) {
				$index = array_search($obj->parent_id, $rev_array);
				if ($index >= 0) {
					$obj->level = $index + 2;
				}
				if (array_search($obj->id, $rev_array)) {
					$obj->activated = 1;
				}
				//$obj->parent_short_uri = $parent_short_uri;
				$selected_data[$obj->parent_id][] = $obj;
			}
		}
		$sql = "SELECT * FROM structure
				WHERE parent_id=".$parent_id." AND (active = 1 OR (active = 2 && customer_group=".$customer_group_id."))
				ORDER BY pos ASC";
		$result = $this->db->query($sql);
		// level 1
		while ($obj = $result->fetch_object()) {
			$obj->level = 1;
			$obj->full_short_uri = $obj->short_uri;
			if (isset($rev_array[0]) && $rev_array[0] == $obj->id) {
				$obj->activated = 1;
				$this->activated_structures[] = $obj;
			}
			$data[] = $obj;
			// level 2
			if (isset($selected_data[$obj->id])) {
				foreach ($selected_data[$obj->id] as $obj_2) {
					// level 1
					$obj_2->full_short_uri = $obj->short_uri.'/'.$obj_2->short_uri;
					if (isset($obj_2->activated)) {
						$this->activated_structures[] = $obj_2;
					}
					$data[] = $obj_2;
					//level 3
					if (isset($selected_data[$obj_2->id])) {
						foreach ($selected_data[$obj_2->id] as $obj_3) {
							$obj_3->full_short_uri = $obj->short_uri.'/'.$obj_2->short_uri.'/'.$obj_3->short_uri;
							if (isset($obj_3->activated)) {
								$this->activated_structures[] = $obj_3;
							}
							$data[] = $obj_3;
							// level 4
							if (isset($selected_data[$obj_3->id])) {
								foreach ($selected_data[$obj_3->id] as $obj_4) {
									$obj_4->full_short_uri = $obj->short_uri.'/'.$obj_2->short_uri.'/'.$obj_3->short_uri.'/'.$obj_4->short_uri;
									if (isset($obj_4->activated)) {
										$this->activated_structures[] = $obj_4;
									}
									$data[] = $obj_4;
									//level 5
									if (isset($selected_data[$obj_4->id])) {
										foreach ($selected_data[$obj_4->id] as $obj_5) {
											$obj_5->full_short_uri = $obj->short_uri.'/'.$obj_2->short_uri.'/'.$obj_3->short_uri.'/'.$obj_4->short_uri.'/'.$obj_5->short_uri;
											if (isset($obj_5->activated)) {
												$this->activated_structures[] = $obj_5;
											}
											$data[] = $obj_5;
											//level 6
											if (isset($selected_data[$obj_5->id])) {
												foreach ($selected_data[$obj_5->id] as $obj_6) {
													$obj_6->full_short_uri = $obj->short_uri.'/'.$obj_2->short_uri.'/'.$obj_3->short_uri.'/'.$obj_4->short_uri.'/'.$obj_5->short_uri.'/'.$obj_6->short_uri;
													if (isset($obj_6->activated)) {
														$this->activated_structures[] = $obj_6;
													}
													$data[] = $obj_6;
													//level 7
													if (isset($selected_data[$obj_6->id])) {
														foreach ($selected_data[$obj_6->id] as $obj_7) {
															$obj_7->full_short_uri = $obj->short_uri.'/'.$obj_2->short_uri.'/'.$obj_3->short_uri.'/'.$obj_4->short_uri.'/'.$obj_5->short_uri.'/'.$obj_6->short_uri.'/'.$obj_7->short_uri;
															if (isset($obj_7->activated)) {
																$this->activated_structures[] = $obj_7;
															}
															$data[] = $obj_7;
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}

		$dataRemapped = array();
		foreach ($data as $sData) {
			$dataRemapped[$sData->id] = $sData;
		}

		return $dataRemapped;
	}

	// end get_all

	public function delete($id = false) {
		$sql = "DELETE FROM structure";

		if ($id) {
			$sql .= " WHERE id=".$this->db->real_escape_string($id);
		} else if ($this->structure_id) {
			$sql .= " WHERE id=".$this->db->real_escape_string($this->structure_id);
		} else {
			$this->error = 'no id';

			return false;
		}

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

		if ($result) {
			return true;
		}
		$this->error = "can't delete";

		return false;
	}

	public function data_filter($request) {
		$data = array();
		foreach ($this->structure_fields as $field_name => $var_type) {
			if (isset($request[$field_name])) {
				if ($var_type == 'text') {
					$data[$field_name] = $request[$field_name];
				} else {
					$data[$field_name] = (int) $request[$field_name];
				}
			}
		}
		return $data;
	}

	/*public function get_all_tree_full_path($path_start, $delimeter = '->') {
		$this->db = Registry::get('base')->db;
		$result = $this->db->query("SELECT * FROM structure ORDER BY parent_id, pos");
		$data = array();
		while ($obj = $result->fetch_object()) {
		$data[] = $obj;
	}

	return $this->make_tree($data, 0, 0, '', $path_start, '', $delimeter, false);
	}

	private function make_tree($data, $parent_id, $level, $path_name, $path_start, $uri_path, $delimeter, $max_level = false) {
		$tree = array();
		foreach ($data as $obj) {
			if ($obj->parent_id == $parent_id && ($level <= $max_level || !$max_level)) {
				$obj->path_name = $path_name;
				$obj->uri_path = $uri_path;
				$obj->level = $level + 1;
				$tree[] = $obj;
				$next_path = ($path_name) ? $path_name.$delimeter.$obj->name : $obj->name;
				$next_uri_path = ($uri_path) ? $uri_path.'/'.$obj->short_uri : $obj->short_uri;

				if ($obj->level == $path_start) {
					$next_path = '';
					$next_uri_path = '';
				}
				$result = $this->make_tree($data, $obj->id, $obj->level, $next_path, $path_start, $next_uri_path, $delimeter, $max_level);
				$tree = array_merge($tree, $result);
			}
		}

		return $tree;
	}*/

	public function get_all_tree_full_path($path_start = false, $delimeter = '->') {
		$this->db = Registry::get('base')->db;
		$result = $this->db->query("SELECT * FROM structure ORDER BY parent_id, pos");
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}

		return $this->make_tree($data, 0, 0, '', $path_start, '', $delimeter, false);
	}

	private function make_tree($data, $parent_id, $level, $path_name, $path_start, $uri_path, $delimeter, $max_level = false) {
		$tree = array();
		foreach ($data as $obj) {

			if ($obj->parent_id == $parent_id && ($level <= $max_level || !$max_level)) {
				$obj->path_name = $path_name;
				$obj->uri_path = $uri_path;
				$obj->level = $level + 1;
				$tree[] = $obj;
				$next_path = ($path_name) ? $path_name.$delimeter.$obj->name : $obj->name;
				$next_uri_path = ($uri_path) ? $uri_path.'/'.$obj->short_uri : $obj->short_uri;

				if ($obj->level == $path_start) {
					$next_path = '';
					$next_uri_path = '';
				}

				$result = $this->make_tree($data, $obj->id, $obj->level, $next_path, $path_start, $next_uri_path, $delimeter, $max_level);

				$tree = array_merge($tree, $result);
			}
		}

		$treeN = array();
		foreach ($tree as $key => $treeObj) {
			$treeN[$treeObj->id] = $treeObj;
		}

		return $treeN;
	}

	public function get_tree_html($link) {
		$result = $this->db->query("SELECT * FROM structure ORDER BY parent_id, pos");
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}

		$html_tree = $this->make_tree_html($data, 0, 0, $link);
		return $html_tree;
	}

	private function make_tree_html($data, $parent_id, $level, $link) {
		$html_tree = '';
		foreach ($data as $obj) {
			if ($obj->parent_id == $parent_id) {
				$obj->path_name = $path_name;
				$obj->level = $level + 1;
				$html_tree .= '<li id="phtml_'.$obj->id.'"><a href="'.$link.$obj->id.'">'.$obj->name.'</a>';

				$result = $this->make_tree_html($data, $obj->id, $obj->level, $link);
				$html_tree .= $result;
				$html_tree .= '</li>';
			}
		}
		if ($html_tree) {
			return '<ul>'.$html_tree.'</ul>';
		} else {
			return '';
		}
	}

	public function is_set($id) {
		$sql = "SELECT * FROM structure WHERE id=".$this->db->real_escape_string($id);

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

		if ($result->num_rows > 0) {
			return true;
		}

		return false;
	}

// end is_set

	public function get_all_item_categories() {
		$result = $this->db->query("SELECT id, name FROM structure WHERE type = 0");

		while ($row = $result->fetch_object()) {
			$data[] = $row;
		}

		return $data;
	}

	public function set_site_configuration_type($type) {
		$sql = "UPDATE structure
				SET get_parent_site_configuration='.$type.'
				WHERE id=".$this->db->real_escape_string($this->structure_id);

		return $this->db->query($sql);
	}

	public function get_type_modul($type_id) {
		if (isset($this->content_module[$type_id])) {
			return $this->content_module[$type_id];
		} else {
			return false;
		}
	}

	// todo
	// methods to manage main menus
	// one method to get a named and registered main menu (recursive, builds data tree)
	// one method to flaten tree
	// one method to generate UL
	// one method to generate other types of listing

	public function get_progressive_tree($selected_ids = false) {
		$result = $this->db->query("SELECT * FROM structure ORDER BY parent_id, pos");
		$data = array();
		while ($obj = $result->fetch_object()) {
			if (is_array($selected_ids)) {
				foreach ($selected_ids as $id) {
					if ($id == $obj->id) {
						$obj->activated = true;
					}
				}
			}

			$data[] = $obj;
		}

		$data = $this->make_tree($data, 3, 1, '', max_level: 2);

		return $data;
	}

	public function get_item_category_tree($children = false) {
		// item_category has the id of 3
		if ($children) {
			$data[] = $this->get_all_parents(3, 1);
			/*$sub_data[] =  $this->get_all_parents(1, 2);
			foreach ($sub_data as $point) {
				$data[] = $point;
			}*/

			return $data;
		}
		return $this->get_all_parents(3, 1);
	}

	public function get_item_category_like_richard($id, $selected_ids) {
		// item_category has the id of 3
		if ($children) {
			$data[] = $this->get_all_parents($id, 1);
			//$sub_data[] =  $this->get_all_parents(1, 2);
			//foreach ($sub_data as $point) {
			//	$data[] = $point;
			//}

			return $data;
		}
		return $this->get_all_parents($id, 1);
	}

	private function get_all_children($id, $level, $depth) {
		$url = 'http://'.$_SERVER['SERVER_NAME'].'/index.php';
		$html = '';

		if ($level > $depth) {
			return false;
		}

		$sql = "SELECT * FROM structure WHERE parent_id=$id";

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

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$obj->level = 'level_'.$level;
				$obj->children = $this->get_all_children($obj->id, $level + 1, $depth);
				if ($obj->children) {
					$html .= '<li class="'.$obj->level.'"><a href="'.$url.'?menu_id='.$obj->id.'">'.$obj->name.'</a><ul>'.$obj->children.'</ul></li>';
				} else {
					$html .= '<li class="'.$obj->level.'"><a href="'.$url.'?menu_id='.$obj->id.'">'.$obj->name.'</a></li>';
				}
				$data[] = $obj;
			}

			return $html;
		}

		return false;
	}

	// diese methode war "private" und wurde nicht genutzt, wird nun aber in der website_class - main_widget_item_categories_dropdown() genutzt (holzeisstock)
	public function get_all_children_flat($id, $level, $depth, $customer_group_id = 0) {
		$url = 'http://'.$_SERVER['SERVER_NAME'].'/index.php';

		if ($level > $depth) {
			return false;
		}

		$sql = "SELECT * FROM structure WHERE parent_id=".$this->db->real_escape_string($id)."
				AND (active=1 OR (active=2 AND customer_group=".$this->db->real_escape_string($customer_group_id).")) ORDER BY pos";

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

		if ($result->num_rows > 0) {
			$data = array();

			while ($obj = $result->fetch_object()) {
				$obj->level = $level;
				$children = $this->get_all_children_flat($obj->id, $level + 1, $depth);

				$obj->number_of_children = (is_array($children)) ? count($children) : 0;
				$data[] = $obj;
				if ($children) {
					foreach ($children as $child) {
						$data[] = $child;
					}
				}
			}

			return $data;
		}

		return false;
	}

	private function get_all_parents($id, $level) {
		$url = 'http://'.$_SERVER['SERVER_NAME'].'/index.php';

		$sql = "SELECT * FROM structure WHERE parent_id=$id";

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

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$obj->level = 'level_'.$level;

				$data[] = $obj;
			}

			return $data;
		}

		return false;
	}

	public function get_by_id($id) {
		$sql = "SELECT * FROM structure WHERE id=$id";

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

		if ($result->num_rows > 0) {
			return $result->fetch_object();
		}

		return false;
	}

	public function get_subcategories($id) {
		$sql = "SELECT name FROM structure WHERE parent_id=$id";

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

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$return[] = $obj->name;
			}

			return $return;
		}

		return false;
	}

	public function get_subcategory_objects($id) {
		$sql = "SELECT * FROM structure
				WHERE parent_id = ".$this->db->real_escape_string($id)."
				ORDER BY pos";

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

		if ($result->num_rows > 0) {
			$return = array();

			while ($obj = $result->fetch_object()) {
				$return[$obj->id] = $obj;
			}

			return $return;
		}

		return false;
	}

	public function get_structure_family($id) {
		$parents = $this->get_subcategory_objects($id);

		$parent_ids = array_keys($parents);

		if (count($parent_ids) > 0) {
			$sql = "SELECT * FROM structure
					WHERE parent_id IN(".implode(',', $parent_ids).")
					ORDER BY pos";

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

			if ($result->num_rows > 0) {
				while ($obj = $result->fetch_object()) {
					$parents[$obj->parent_id]->children[$obj->id] = $obj;
				}

				return $parents;
			}
		}

		return $parents;
	}

	public static function get_name_by_id($id) {
		$db = Registry::get('base')->db;

		$sql = "SELECT name FROM structure WHERE parent_id=$id";

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

		if ($result->num_rows > 0) {
			return $result->fetch_object()->name;
		}

		return false;
	}

	public static function get_name_by_id_static($id) {
		if (empty($id)) return false;

		$db = Registry::get('base')->db;

		$sql = "SELECT name FROM structure WHERE id=$id";

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

		if ($result->num_rows > 0) {
			return $result->fetch_object()->name;
		}

		return false;
	}

	public function getWhereManufacturerItems($manufacturer_id) {
		$db = Registry::get('base')->db;

		// Without parent SURIs, with parents
		$sql = "
				SELECT DISTINCT
					s.short_uri,
					s.name,
					s.parent_id,
					s.id
				FROM
					structure s
				LEFT JOIN
					item_structure_assign isa
				ON
					s.id = isa.structure_id
				LEFT JOIN
					items i
				ON
					i.id = isa.item_id
				WHERE
					i.manufacturer_id = '".$manufacturer_id."'
				AND 
					s.id IS NOT NULL
				ORDER BY
					s.name
			";
		$result = $db->query($sql);

		$structureItems = array();

		while ($S = $result->fetch_object()) {
			$structureItems[] = $S;
		}

		return $structureItems;
	}

	public static function getLayoutMenu($parent_id = false, $parent_ids = false) {
		$db = Registry::get('base')->db;

		if ($parent_id) {
			$parent_ids = array($parent_id);
		}

		$result = $db->query("
			SELECT * FROM structure 
			WHERE parent_id IN (".implode(',', $parent_ids).")
			AND active != 0 ORDER BY pos ASC
		");

		$usedIDs = array();
		while ($obj = $result->fetch_object()) {
			$obj->level = 1;
			$data[$obj->id] = $obj;

			$usedIDs[] = $obj->id;
		}

		if (count($usedIDs) > 0) {
			$subs = self::getLayoutMenu(false, $usedIDs);

			if (is_array($subs) && count($subs) > 0) {
				foreach ($subs as $subId => $subData) {
					$data[$subData->parent_id]->subs[$subId] = $subData;
				}
			}
		}

		return $data;
	}

	// end get_all

	public function get_all_tree_ids($id) {
		$result = $this->db->query("SELECT id, parent_id FROM structure ORDER BY parent_id, pos");
		$data = array();
		while ($obj = $result->fetch_object()) {
			$data[] = $obj;
		}
		$tree_id_array = array();
		while ($id != 0) {
			foreach ($data as $structure) {
				if ($id == $structure->id) {
					$id = $structure->parent_id;
					$tree_id_array[] = $structure->id;
					break;
				}
			}
		}
		return $tree_id_array;
	}

	public function save_discounts($data, $manufacturers) {
		if ($data) {
			// delete old discounts
			$sql = "DELETE FROM discount_item_groups WHERE structure_id=".$this->db->real_escape_string($data['structure_id']).
				" AND customer_group_id=".$this->db->real_escape_string($data['customerGroup']);
			$result = $this->db->query($sql);

			// save get parent discounts
			$get_parent_discounts = 0;
			if (isset($data['get_parent_discounts']) && $data['get_parent_discounts'] == 1) {
				$get_parent_discounts = 1;
			}
			$result = $this->db->query("
				UPDATE structure 
				SET get_parent_discounts=".$get_parent_discounts." 
				WHERE id=".$this->db->real_escape_string($data['structure_id'])
			);

			// save parent discounts
			if ($get_parent_discounts) {
				// get parent id
				$structure_data = $this->get_by_id($data['structure_id']);
				$parent_id = $structure_data->parent_id;
				// get parent discounts
				$sql = "SELECT * FROM discount_item_groups
						WHERE structure_id=".$this->db->real_escape_string($parent_id)."
						AND customer_group_id=".$this->db->real_escape_string($data['customerGroup']);
				$result = $this->db->query($sql);
				$discounts = array();
				while ($obj = $result->fetch_object()) {
					$discounts[$obj->manufacturer_id] = $obj->discount;
				}

				// set discounts
				// insert new discounts
				$sql = "
					INSERT INTO discount_item_groups (
						structure_id,
						manufacturer_id,
						customer_group_id,
						discount
					) VALUES 
				";
				foreach ($discounts as $manufacturer_id => $discount) {
					$sql .= "(
						".$this->db->real_escape_string($data['structure_id']).",
						".$this->db->real_escape_string($manufacturer_id).",
						".$this->db->real_escape_string($data['customerGroup']).",
						".$this->db->real_escape_string($discount)."
					), ";
				}
				$sql = substr($sql, 0, -2);
				$result = $this->db->query($sql);
			} else {
				// insert new discounts
				$sql = "
					INSERT INTO discount_item_groups (
						structure_id,
						manufacturer_id,
						customer_group_id,
						discount
					) VALUES 
				";

				foreach ($manufacturers as $manufacturer) {
					if (isset($data['discount_'.$manufacturer->id]) && $data['discount_'.$manufacturer->id] > 0) {
						$sql .= "(
								".$this->db->real_escape_string($data['structure_id']).",
								".$this->db->real_escape_string($manufacturer->id).",
								".$this->db->real_escape_string($data['customerGroup']).",
								".$this->db->real_escape_string($data['discount_'.$manufacturer->id])."
							), ";
					}
				}
				$sql = substr($sql, 0, -2);
				$result = $this->db->query($sql);
			}
		}

		// set children tree discounts
		$discount_data = $this->get_discounts($data['structure_id'], $data['customerGroup']);
		$this->set_children_tree_discounts($data['structure_id'], $data['customerGroup'], $discount_data);

		return false;
	}

	private function set_children_tree_discounts($structure_id, $customer_group_id, $discount_data) {
		// get children structures
		$sql = "SELECT * FROM structure
				WHERE parent_id=".$this->db->real_escape_string($structure_id);
		$result = $this->db->query($sql);
		$structures = array();
		while ($obj = $result->fetch_object()) {
			$structures[] = $obj;
		}
		// set discounts
		foreach ($structures as $structure) {
			if ($structure->get_parent_discounts) {
				// delete old discounts
				$sql = "DELETE FROM discount_item_groups WHERE structure_id=".$this->db->real_escape_string($structure->id).
					" AND customer_group_id=".$this->db->real_escape_string($customer_group_id);
				$result = $this->db->query($sql);

				// set new discounts
				$sql = "
					INSERT INTO discount_item_groups (
						structure_id,
						manufacturer_id,
						customer_group_id,
						discount
					) VALUES 
				";
				foreach ($discount_data as $manufacturer_id => $discount) {
					$sql .= "(
						".$this->db->real_escape_string($structure->id).",
						".$this->db->real_escape_string($manufacturer_id).",
						".$this->db->real_escape_string($customer_group_id).",
						".$this->db->real_escape_string($discount)."), ";
				}
				$sql = substr($sql, 0, -2);
				$result = $this->db->query($sql);

				// recursive
				$this->set_children_tree_discounts($structure->id, $customer_group_id, $discount_data);
			}
		}
		return false;
	}

	public function get_level($structure_id, $level = 0) {
		// get children structures
		$sql = "SELECT parent_id FROM structure
				WHERE id=".$this->db->real_escape_string($structure_id);
		$result = $this->db->query($sql);
		$obj = $result->fetch_object();
		if ($obj->parent_id > 0) {
			$level += $this->get_level($obj->parent_id, 1);
		}
 		return $level;
	}

	public function get_discounts($structure_id, $customer_group_id) {
		$discounts = array();
		$sql = "SELECT * FROM discount_item_groups
				WHERE structure_id=".$this->db->real_escape_string($structure_id)."
				AND customer_group_id=".$this->db->real_escape_string($customer_group_id);
		$result = $this->db->query($sql);
		if ($result) {
			while ($obj = $result->fetch_object()) {
				$discounts[$obj->manufacturer_id] = $obj->discount;
			}
		}
		return $discounts;
	}

	public function set_image($id, $name) {
		$sql = "UPDATE structure SET image='$name' WHERE id=$id";

		//return $sql;
		return $this->db->query($sql);
	}

	public function save_image($id, $name) {
		$name = $id;

		$file_info = getimagesize($_FILES['logo_image']['tmp_name']);
		$image_type = array('', 'gif', 'jpg', 'png');
		$file_name = $name.'_'.$id.'.'.$image_type[$file_info[2]];
		$file_name = str_replace(' ', '_', $file_name);
		$file_name = str_replace(array('ä', 'Ä', 'ö', 'Ö', 'ü', 'Ü', 'ß'), array('ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss'), $file_name);
		if (move_uploaded_file($_FILES['logo_image']['tmp_name'], $this->path.$file_name)) {
			$imaginator = new phImaginator();
			$imaginator->add($this->path.$file_name);
			$imaginator->Resize_fitBoth($this->config_object->shopConfiguration['structure_max_image_width'], $this->config_object->shopConfiguration['structure_max_image_height']);
			$imaginator->save();

			$this->set_image($id, $file_name);
			//return
			return $this->url.$file_name;
		} else {
			return false;
		}
	}

	public function get_image_url() {
		return $this->url;
	}

	public function set_header_image($id, $name) {
		$sql = "UPDATE structure SET header_image='$name' WHERE id=$id";

		//return $sql;
		return $this->db->query($sql);
	}

	public function save_header_image($id, $name) {
		$name = $id;

		$file_info = getimagesize($_FILES['header_image']['tmp_name']);
		$image_type = array('', 'gif', 'jpg', 'png');
		$file_name = $name.'_'.$id.'.'.$image_type[$file_info[2]];
		$file_name = str_replace(' ', '_', $file_name);
		$file_name = str_replace(array('ä', 'Ä', 'ö', 'Ö', 'ü', 'Ü', 'ß'), array('ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss'), $file_name);
		if (move_uploaded_file($_FILES['header_image']['tmp_name'], $this->header_path.$file_name)) {
			$imaginator = new phImaginator();
			$imaginator->add($this->path.$file_name);
			$imaginator->Resize_fitBoth($this->config_object->shopConfiguration['header_max_image_width'], $this->config_object->shopConfiguration['header_max_image_height']);
			$imaginator->save();

			$this->set_header_image($id, $file_name);
			//return
			return $this->url.$file_name;
		} else {
			return false;
		}
	}

	public function get_header_image_url() {
		return './web/'.SHOP_SYSTEM.'/images/header/';
	}

	public function get_children($parent_id, $level_start, $selected_ids) {

		$level_start++;

		$result = $this->db->query("SELECT * FROM structure WHERE parent_id = '".$this->db->real_escape_string($parent_id)."'");

		$data = array();
		while ($obj = $result->fetch_object()) {
			if (is_array($selected_ids)) {
				foreach ($selected_ids as $id) {
					if ($id == $obj->id) {
						$obj->activated = true;
					}
				}
			}

			$data[] = $obj;
		}

		$data = $this->make_tree($data, $parent_id, $level_start, '', max_level: $level_start + 1);

		return $data;
	}
}

?>