<?php
class ControllerProductManufacturer extends Controller {
	public function index() {

		/*$this->load->language('product/manufacturer');

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

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

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

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

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

		$data['button_continue'] = $this->language->get('button_continue');
        //breadcrumbs data
        $this->load->language('common/header');

        if ($this->request->server['HTTPS']) {
        $server = $this->config->get('config_ssl');
        } else {
        $server = $this->config->get('config_url');
        }
        $data['base'] = $server;
        $data['text_home'] = $this->language->get('text_home');
		$data['breadcrumbs'] = array();

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

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_brand'),
			'href' => $this->url->link('product/manufacturer')
		);
        
        $breadcrumbs1 = array();
            $count=1;
            foreach($data['breadcrumbs'] as $bread){
                $breadcrumbs1 = array([
                 "@type"=> "ListItem",
                 "position"=> $count,
                 "name"=> $bread['text'],
                 "item"=> $bread['href']]);
                $count++;
            }
        $data['breadcrumbs1']=  json_encode($breadcrumbs1);

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

		$results = $this->model_catalog_manufacturer->getManufacturers();

		foreach ($results as $result) {
			if (is_numeric(utf8_substr($result['name'], 0, 1))) {
				$key = '0 - 9';
			} else {
				$key = utf8_substr(utf8_strtoupper($result['name']), 0, 1);
			}

			if (!isset($data['categories'][$key])) {
				$data['categories'][$key]['name'] = $key;
			}

			$data['categories'][$key]['manufacturer'][] = array(
				'name' => $result['name'],
				'href' => $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $result['manufacturer_id'], true)
			);
		}

		$data['continue'] = $this->url->link('common/home');

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

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

	public function info() {

		/*$this->load->language('product/manufacturer');

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

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

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

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

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'p.sort_order';
		}

		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;
		}

		if (isset($this->request->get['limit'])) {
			$limit = (int)$this->request->get['limit'];
		} else {
			$limit = (int)$this->config->get($this->config->get('config_theme') . '_product_limit');
		}

		// FİLTRE KODLARI **
		if (isset($this->request->get['brand'])) {
			unset($this->session->data['filter_brand']);
			$this->session->data['filter_brand'] = $this->exportFilterElement($this->request->get['brand']);
		} else {
			if(isset($this->session->data['filter_brand']) AND $this->session->data['filter_brand']){
				unset($this->session->data['filter_brand']);
			}
		}

		if (isset($this->request->get['attribute'])) {
			unset($this->session->data['filter_attribute']);
			$this->session->data['filter_attribute'] = $this->exportFilterElement($this->request->get['attribute']);
		} else {
			if(isset($this->session->data['filter_attribute']) AND $this->session->data['filter_attribute']){
				unset($this->session->data['filter_attribute']);
			}
		}

		if (isset($this->request->get['option'])) {
			unset($this->session->data['filter_option']);
			$this->session->data['filter_option'] = $this->exportFilterElement($this->request->get['option']);
		} else {
			if(isset($this->session->data['filter_option']) AND $this->session->data['filter_option']){
				unset($this->session->data['filter_option']);
			}
		}

		// FİLTRE KODLARI **

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

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

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_brand'),
			'href' => $this->url->link('product/manufacturer', '', true)
		);
        
		$manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($manufacturer_id);

		if ($manufacturer_info) {
			$this->document->setTitle($manufacturer_info['name']);

			$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'];
			}

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

			$data['breadcrumbs'][] = array(
				'text' => $manufacturer_info['name'],
				'href' => $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'] . $url, true)
			);
            
            $breadcrumbs1 = array();
            $count=1;
            foreach($data['breadcrumbs'] as $bread){
                $breadcrumbs1 = array([
                 "@type"=> "ListItem",
                 "position"=> $count,
                 "name"=> $bread['text'],
                 "item"=> $bread['href']]);
                $count++;
            }
        $data['breadcrumbs1']=  json_encode($breadcrumbs1);
			$data['heading_title'] = $manufacturer_info['name'];

			$data['text_empty'] = $this->language->get('text_empty');
			$data['text_quantity'] = $this->language->get('text_quantity');
			$data['text_manufacturer'] = $this->language->get('text_manufacturer');
			$data['text_model'] = $this->language->get('text_model');
			$data['text_price'] = $this->language->get('text_price');
			$data['text_tax'] = $this->language->get('text_tax');
			$data['text_points'] = $this->language->get('text_points');
			$data['text_compare'] = sprintf($this->language->get('text_compare'), (isset($this->session->data['compare']) ? count($this->session->data['compare']) : 0));
			$data['text_sort'] = $this->language->get('text_sort');
			$data['text_limit'] = $this->language->get('text_limit');

			$data['text_f_category'] = $this->language->get('text_f_category');
            $data['text_f_brand'] = $this->language->get('text_f_brand');
            $data['text_f_option'] = $this->language->get('text_f_option');
            $data['text_f_attribure'] = $this->language->get('text_f_attribure');

			$data['button_cart'] = $this->language->get('button_cart');
			$data['button_wishlist'] = $this->language->get('button_wishlist');
			$data['button_compare'] = $this->language->get('button_compare');
			$data['button_continue'] = $this->language->get('button_continue');
			$data['button_list'] = $this->language->get('button_list');
			$data['button_grid'] = $this->language->get('button_grid');
			$data['quick_view'] = $this->language->get('quick_view');

			$data['compare'] = $this->url->link('product/compare');

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

			$filter_data = array(
				'filter_manufacturer_id' => $manufacturer_id,
				'sort'                   => $sort,
				'order'                  => $order,
				'start'                  => ($page - 1) * $limit,
				'limit'                  => $limit,
				'brand'			 	 	=> isset($this->session->data['filter_brand']) ? $this->session->data['filter_brand'] : false, 
				'attribute'			 	=> isset($this->session->data['filter_attribute']) ? $this->session->data['filter_attribute'] : false, 
				'option'			 	=> isset($this->session->data['filter_option']) ? $this->session->data['filter_option'] : false, 
			
			);

			$product_total = $this->model_catalog_product->getTotalProducts($filter_data);

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

			foreach ($results as $result) {
				if ($result['image']) {
					$image = $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'));
				} else {
					$image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'));
				}
			
					$images = $this->model_catalog_product->getProductImages($result['product_id']);
	
					if(isset($images[0]['image']) && !empty($images)){
						$images = $images[0]['image'];
				    }else
				    {
				     	$images = $image;
				    }


				if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
					$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
				} else {
					$price = false;
				}

				if ((float)$result['special']) {
					$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);	
					if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
						if ($result['currency_id'] == 1) {
							$soft_currency_special = $this->currency->format($result['special'], 'TRY');
						} else {
							$soft_currency_special = $this->currency->format($result['special'], 'USD');
						}
					} else {
						$soft_currency_special = false;
					}
				} else {
					$special = false;
					$soft_currency_special = false;
				}

				if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
					if ($result['currency_id'] == 1) {
						$soft_currency_price = $this->currency->format($result['price'], 'TRY');
					} else {
						$soft_currency_price = $this->currency->format($result['price'], 'USD');
					}
				} else {
					$soft_currency_price = false;
				}

				if ($this->config->get('config_tax')) {
					$tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
				} else {
					$tax = false;
				}

				if ($this->config->get('config_review_status')) {
					$rating = (int)$result['rating'];
				} else {
					$rating = false;
				}

				$data['products'][] = array(
					'product_id'  => $result['product_id'],
					'thumb'       => $image,
					'thumb_swap'  => $this->model_tool_image->resize($images, $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height')),
					'name'        => $result['name'],
					'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get($this->config->get('config_theme') . '_product_description_length')) . '..',
					'price'       => $price,
					'special'     => $special,
					'soft_currency_price'     => $soft_currency_price,
					'soft_currency_special'   => $soft_currency_special,
					'percentsaving' 	 => ($result['price'] && $result['special']) ? round((($result['price'] - $result['special'])/$result['price'])*100, 0) : '',
					'tax'         => $tax,
					'minimum'     => $result['minimum'] > 0 ? $result['minimum'] : 1,
					'rating'      => $result['rating'],
					'quick'        => $this->url->link('product/quick_view','&product_id=' . $result['product_id']),
					'href'        => $this->url->link('product/product', '&product_id=' . $result['product_id'] . $url, true)
				);
			}

			$pagination = new Pagination();
			$pagination->total = $product_total;
			$pagination->page = $page;
			$pagination->limit = $limit;
			$pagination->url = $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'] .  $url . '&page={page}');

			$data['pagination'] = $pagination->render();
			$data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($product_total - $limit)) ? $product_total : ((($page - 1) * $limit) + $limit), $product_total, ceil($product_total / $limit));

			
			if ($page == 1) {
			    $this->document->addLink($this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'], true), 'canonical');
			} elseif ($page == 2) {
			    $this->document->addLink($this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'], true), 'prev');
			} else {
			    $this->document->addLink($this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'] . $url . '&page='. ($page - 1), true), 'prev');
			}

			if ($limit && ceil($product_total / $limit) > $page) {
			    $this->document->addLink($this->url->link('product/manufacturer/info', 'manufacturer_id=' . $this->request->get['manufacturer_id'] . $url . '&page='. ($page + 1), true), 'next');
			}

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

			$data['continue'] = $this->url->link('common/home');

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

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

			
		} else {
			$url = '';

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

			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'];
			}

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

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('text_error'),
				'href' => $this->url->link('product/manufacturer/info', $url)
			);
            
			$this->document->setTitle($this->language->get('text_error'));

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

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

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

			$data['continue'] = $this->url->link('common/home');

			$this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . ' 404 Not Found');

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

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

			
		}*/
	}

	public function getAttributesJSON(){  

		/*$path = $this->session->data['path'];
		$this->load->model('catalog/product');
		$attribute_filter_data = array(
			'category_id' => $this->session->data['category_id'],
		);
		$data['f_attribute_list'] = array();
		$data['attributes'] = array();
		$attribute_groups = $this->model_catalog_product->getAttributeGroups($attribute_filter_data);
		foreach ($attribute_groups as $key => $attribute_group) {
			$attributes = $this->model_catalog_product->getAttributeValues($attribute_group['attribute_group_id'], $attribute_filter_data);
			$attribute_values = array();
			foreach ($attributes as $attribute) {
				$attribute_values[] = array(
					'attribute_id' 	=> $attribute['attribute_id'],
					'name' 			=> $attribute['name'],
					'href'			=> $path . $this->getBrandsIds() . $this->getAttributesIds() . $attribute['attribute_id'] . $this->getOptionsIds(),
				);
				if(isset($this->session->data['filter_attribute']) AND $this->session->data['filter_attribute']){
					if(in_array($attribute['attribute_id'], $this->session->data['filter_attribute'])){
						$data['f_attribute_list'][] = array(
							'name' => $attribute['name'],
							'href' => $path . $this->getBrandsIds() . ( $this->removeFilterElement($attribute['attribute_id'], $this->session->data['filter_attribute']) ? '&attribute=' . $this->removeFilterElement($attribute['attribute_id'], $this->session->data['filter_attribute']) : '' ) . $this->getOptionsIds(),
						);
					}
				}
			}
			$data['attributes'][] = array(
				'attribute_group_id' => $attribute_group['attribute_group_id'],
				'name' => $attribute_group['name'],
				'attribute_values' => $attribute_values, 
			);
		}

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

	public function getOptionsJSON(){
		/*$path = $this->session->data['path'];
		$this->load->model('catalog/product');
		$option_filter_data = array(
			'category_id' => $this->session->data['category_id'],
		); 

		$options = $this->model_catalog_product->getOptions($option_filter_data);
		$data['f_option_list'] = array();
		$data['options'] = array();
		foreach($options as $option){
            $option_values = array();
            $get_option_values = $this->model_catalog_product->getOptionValues($option['option_id'], $option_filter_data);
            foreach($get_option_values as $option_value){ 
                $option_values[] = array(
                    'ov_option_id' 	=> $option_value['ov_option_id'],
                    'name' 	        => $option_value['name'],
                    'href'			=> $path . $this->getBrandsIds() . $this->getAttributesIds() . $this->getOptionsIds() . $option_value['ov_option_id'],
                );

                if(isset($this->session->data['filter_option']) AND $this->session->data['filter_option']){
                    if(in_array($option_value['ov_option_id'], $this->session->data['filter_option'])){
                        $data['f_option_list'][] = array(
                            'name' => $option_value['name'],
                            'href' => $path . $this->getBrandsIds() . $this->getAttributesIds(). ( $this->removeFilterElement($option_value['ov_option_id'], $this->session->data['filter_option']) ? '&option=' . $this->removeFilterElement($option_value['ov_option_id'], $this->session->data['filter_option']) : '' ),
                        );
                    }
                }
            }
			$data['options'][] = array(
				'option_id' 	=> $option['option_id'],
                'name'     		=> $option['name'],
                'option_values' => $option_values
			);
			
		}

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

		//getOptions*/
	}

	public function getSortsJSON(){

		/*$path = $this->session->data['path'] . $this->getBrandsIds() . $this->getAttributesIds() . $this->getOptionsIds();
		$this->load->language('product/category');

		$data['sorts'] = array();
		$data['sorts'][] = array(
			'text'  => $this->language->get('text_default'),
			'value' => 'p.sort_order-ASC',
			'href'  => $path . '&sort=p.sort_order&order=ASC',
		);

		$data['sorts'][] = array(
			'text'  => $this->language->get('text_name_asc'),
			'value' => '&sort=pd.name&order=ASC',
			'href'  => $path . '&sort=pd.name&order=ASC'
		);

		$data['sorts'][] = array(
			'text'  => $this->language->get('text_name_desc'),
			'value' => '&sort=pd.name&order=DESC',
			'href'  => $path . '&sort=pd.name&order=DESC'
		);

		$data['sorts'][] = array(
			'text'  => $this->language->get('text_price_asc'),
			'value' => '&sort=p.price&order=ASC',
			'href'  => $path . '&sort=p.price&order=ASC'
		);

		$data['sorts'][] = array(
			'text'  => $this->language->get('text_price_desc'),
			'value' => '&sort=p.price&order=DESC',
			'href'  => $path . '&sort=p.price&order=DESC'
		);

		if ($this->config->get('config_review_status')) {
			$data['sorts'][] = array(
				'text'  => $this->language->get('text_rating_desc'),
				'value' => '&sort=rating&order=DESC',
				'href'  => $path . '&sort=rating&order=DESC'
			);

			$data['sorts'][] = array(
				'text'  => $this->language->get('text_rating_asc'),
				'value' => '&sort=rating&order=ASC',
				'href'  => $path . '&sort=rating&order=ASC'
			);
		}

		$data['sorts'][] = array(
			'text'  => $this->language->get('text_model_asc'),
			'value' => '&sort=p.model&order=ASC',
			'href'  => $path . '&sort=p.model&order=ASC'
		);

		$data['sorts'][] = array(
			'text'  => $this->language->get('text_model_desc'),
			'value' => '&sort=p.model&order=DESC',
			'href'  => $path . '&sort=p.model&order=DESC'
		);	

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

	private function exportFilterElement($elements){
		if(isset($elements) AND $elements){
			$dizi = array();
			$elements = explode('-', $elements);
			foreach ($elements as $key => $value) {
				if($value){
					$dizi[] = $value;
				}
			}

			return array_unique($dizi);

		}else{
			return false;
		}
	}

	private function removeFilterElement($element, $elements = array()){
		if($element AND $elements) {
			$string = '';
			foreach ($elements as $key => $value) {
				if($value != $element){
					$string .= $value . '-';
				}
			}
			$string = rtrim($string,'-');
			return $string ? $string : false;

		}else{
			return false;
		}
	}

	public function getBrandsIds(){
		/*$brands_ids = '';
		$i = 0;
		if(isset($this->session->data['filter_brand']) AND $this->session->data['filter_brand']){
			foreach($this->session->data['filter_brand'] as $brand){ 
				if($brand != ''){
					$i++;
					$brands_ids .= $brand . '-';
				}
				
			}
		}
		else{
			return '&brand=';
		}
		
		return ($i > 0) ? '&brand=' . $brands_ids : '';*/
	}

	public function getAttributesIds(){
		/*$attributes_ids = '';
		$i = 0;
		if(isset($this->session->data['filter_attribute']) AND $this->session->data['filter_attribute']){
			foreach($this->session->data['filter_attribute'] as $attribute){
				if($attribute != ''){
					$i++;
					$attributes_ids .= $attribute . '-';
				}
			}
		}
		else{
			return '&attribute=';
		}
		return ($i > 0) ? '&attribute=' . $attributes_ids : '';*/
	}

	public function getOptionsIds(){
		/*$options_ids = '';
		$i = 0;
		if(isset($this->session->data['filter_option']) AND $this->session->data['filter_option']){
			foreach($this->session->data['filter_option'] as $option){
				if($option != ''){
					$i++;
					$options_ids .= $option . '-';
				}
			}
		}
		else{
			return '&option=';
		}
		return ($i > 0) ? '&option=' . $options_ids : '';*/
	}

	public function createcache(){

		$this->load->model('catalog/manufacturer');
		$this->model_catalog_manufacturer->createCache();
		$log = new Log("manufacturerCahacheFile.txt");
		$log->write("It worked!");
	}
}
