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

			$data['idquantity'] = $this->config->get('quantity_id');
			

        if ($this->config->get('mlseo_fix_search')) {
          $data['csp_search_url'] = $this->url->link('product/search');
        } else {
          $data['csp_search_url'] = 'index.php?route=product/search';
        }
      

        $this->load->language('extension/module/notify_when_available');
        $data['text_out_of_stock'] = $this->language->get('text_out_of_stock');
        $data['out_of_stock_show'] = $this->config->get('module_notify_when_available_stock');
        $data['out_of_stock_notify'] = $this->config->get('module_notify_when_available_notify');
        
		$this->load->language('product/search');

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

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

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

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


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

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			
            if (defined('OPENCARTVIP_ACTIVE')) {
                $order = $this->opencartvip->settings->get('productOrder');
            } 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 = $this->config->get('theme_' . $this->config->get('config_theme') . '_product_limit');
		}

		if (isset($this->request->get['search'])) {
			$this->document->setTitle($this->language->get('heading_title') .  ' - ' . $this->request->get['search']);
		} else {
			$this->document->setTitle($this->language->get('heading_title'));
		}

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

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

		$url = '';

		if (isset($this->request->get['search'])) {
			$url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8'));
		}


		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('heading_title'),
			'href' => $this->url->link('product/search', $url)
		);

		if (isset($this->request->get['search'])) {
			$data['heading_title'] = $this->language->get('heading_title') .  ' - ' . $this->request->get['search'];
		} else {
			$data['heading_title'] = $this->language->get('heading_title');
		}

	

	

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

		if (isset($this->request->get['search']) || isset($this->request->get['tag'])) {
			$filter_data = array(
				'filter_name'         => $search,
				'sort'                => $sort,
				'order'               => $order,
				'start'               => ($page - 1) * $limit,
				'limit'               => $limit
			);

			
            if (defined('OPENCARTVIP_ACTIVE')) {
                $this->load->model('opencartvip/filter');

                $filter_data = array_merge($this->model_opencartvip_filter->parseFilterData(), $filter_data);

                $this->model_opencartvip_filter->setFilterData($filter_data);

                $product_total = $this->model_opencartvip_filter->getTotalProducts();
            } else {
                $product_total = $this->model_catalog_product->getTotalProducts($filter_data);
            }
            

			
            if (defined('OPENCARTVIP_ACTIVE')) {
                $results = $this->model_opencartvip_filter->getProducts($filter_data);
            } else {
                $results = $this->model_catalog_product->getProducts($filter_data);
            }
            

            if (defined('OPENCARTVIP_ACTIVE')) {
                $this->load->model('opencartvip/product');

                $data['image_width'] = $this->opencartvip->settings->get('image_dimensions_product.width');
                $data['image_height'] = $this->opencartvip->settings->get('image_dimensions_product.height');

                if ($this->opencartvip->settings->get('performanceLazyLoadImagesStatus')) {
			        $data['dummy_image'] = $this->model_opencartvip_image->transparent($data['image_width'], $data['image_width']);
                }
            }
            

			foreach ($results as $result) {
				if ($result['image']) {
					if (defined('OPENCARTVIP_ACTIVE')) {
                $image = $this->model_opencartvip_image->resize($result['image'], $this->opencartvip->settings->get('image_dimensions_product.width'), $this->opencartvip->settings->get('image_dimensions_product.height'), $this->opencartvip->settings->get('image_dimensions_product.resize'));
            } else {
                $image = $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            }
				} else {
					$image = $this->model_tool_image->resize('placeholder.png', $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
				}

				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']);
				} else {
					$special = 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;
				}


            if (defined('OPENCARTVIP_ACTIVE')) {
            

                if ($this->opencartvip->document->isDesktop() && $this->opencartvip->settings->get('globalProductGridSecondImageStatus') && ($additional_image = $this->opencartvip->productSecondImage($result))) {
                    $second_image = $this->model_opencartvip_image->resize($additional_image, $this->opencartvip->themeConfig('image_product_width'), $this->opencartvip->themeConfig('image_product_height'), $this->opencartvip->themeConfig('image_product_resize'));
                   
                } else {
                    $second_image = false;
                }
            }
            

			if(isset($product_info)){
				$value = $product_info;
			}elseif(isset($result)){
				$value = $result;
			}elseif(isset($product)){
				$value = $product;
			}
			

				if($this->config->get('reviewpro_fields')['status']){
					$this->load->model('extension/reviewpro');
					$rating_desc = $this->model_extension_reviewpro->getratinglist();
					$avgrating = array();
					$total_avg = 0;
					$items = 0;
					foreach ($rating_desc as $rating_result) {
						$count = $this->model_extension_reviewpro->getratingparcount($rating_result['rating_id'],$result['product_id']);
						$avg = $this->model_extension_reviewpro->getratingparavg($rating_result['rating_id'], $result['product_id']);
						if($count){
							$total_avg = $avg + $total_avg;
							$items++;
						}
					}
					if($total_avg){
						$averagerating = round($total_avg / $items, 1);
					}else{
						$averagerating = 0;
					}
					$rating = round($averagerating);
				}
			
				$data['products'][] = array(

                'quantity'       => defined('OPENCARTVIP_ACTIVE') ? $result['quantity'] : null,
				'stock_status'   => defined('OPENCARTVIP_ACTIVE') ? $result['stock_status'] : null,
				'second_thumb'   => defined('OPENCARTVIP_ACTIVE') ? $second_image : null,
				'labels'         => defined('OPENCARTVIP_ACTIVE') ? $this->opencartvip->productLabels($result, $price, $special) : null,
				'extra_buttons'  => defined('OPENCARTVIP_ACTIVE') ? $this->opencartvip->productExtraButton($result, $price, $special) : null,
				'date_end'       => defined('OPENCARTVIP_ACTIVE') ? $this->opencartvip->productCountdown($result) : null,
				'price_value'    => defined('OPENCARTVIP_ACTIVE') ? ($result['special'] ? $result['special'] > 0 : $result['price'] > 0) : null,
				'stat1'          => defined('OPENCARTVIP_ACTIVE') ? $this->opencartvip->productStat($result, $this->opencartvip->settings->get('globalProductStat1')) : null,
				'stat2'          => defined('OPENCARTVIP_ACTIVE') ? $this->opencartvip->productStat($result, $this->opencartvip->settings->get('globalProductStat2')) : null,
            
					'product_id'  => $result['product_id'],

        'quantity'  => $result['quantity'],
        
					'thumb'       => $image,
					'name'        => $result['name'],
					'price'       => $price,
					'special'     => $special,
					'tax'         => $tax,
'max'         => $value['quantity'],
						  'min'         => $value['minimum'],	
			
					'minimum'     => $result['minimum'] > 0 ? $result['minimum'] : 1,
					
				'rating'      => $rating,
			
					'href'        => $this->config->get('mlseo_fpp_remove_search') ? $this->url->link('product/product', 'product_id=' . $result['product_id']) : $this->url->link('product/product', 'product_id=' . $result['product_id'] . $url)
				);
			}

			$url = '';

			if (isset($this->request->get['search'])) {
				$url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8'));
			}



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


            if (defined('OPENCARTVIP_ACTIVE')) {
                $url .= $this->model_opencartvip_filter->buildFilterData($filter_data);
            }
            
			$data['sorts'] = array();

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

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

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

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

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

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

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

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

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

			$url = '';

			if (isset($this->request->get['search'])) {
				$url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['tag'])) {
				$url .= '&tag=' . urlencode(html_entity_decode($this->request->get['tag'], ENT_QUOTES, 'UTF-8'));
			}

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

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

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

			$limits = array_unique(array($this->config->get('theme_' . $this->config->get('config_theme') . '_product_limit'), 25, 50, 75, 100));

			sort($limits);


            if (defined('OPENCARTVIP_ACTIVE')) {
                $url .= $this->model_opencartvip_filter->buildFilterData($filter_data);
            }
            
			foreach($limits as $value) {
				$data['limits'][] = array(
					'text'  => $value,
					'value' => $value,
					'href'  => $this->url->link('product/search', $url . '&limit=' . $value)
				);
			}

			$url = '';

			if (isset($this->request->get['search'])) {
				$url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8'));
			}


			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['limit'])) {
				$url .= '&limit=' . $this->request->get['limit'];
			}


            if (defined('OPENCARTVIP_ACTIVE')) {
                $url .= $this->model_opencartvip_filter->buildFilterData($filter_data);
            }
            
			$pagination = new Pagination();
			$pagination->total = $product_total;
			$pagination->page = $page;
			$pagination->limit = $limit;
			$pagination->url = $this->url->link('product/search', $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));

		}

		$data['search'] = $search;


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

		$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');

		$this->response->setOutput($this->load->view('product/search', $data));
	}
}
