<?php
class ControllerProductCompare extends Controller {
	public function index() {
		$this->language->load('product/compare');

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

		$this->load->type('tipocomum');

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

		if (!isset($this->session->data['compare'])) {
			$this->session->data['compare'] = array();
		}

		if (isset($this->request->get['remove'])) {
			$key = array_search($this->request->get['remove'], $this->session->data['compare']);

			if ($key !== false) {
				unset($this->session->data['compare'][$key]);
			}

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

			$this->redirect($this->url->link('product/compare'));
		}

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

		$this->data['breadcrumbs'] = array();

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

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('product/compare'),
			'separator' => $this->language->get('text_separator')
		);

		$this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);

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

		$this->data['text_product'] = $this->language->get('text_product');
		$this->data['text_name'] = $this->language->get('text_name');
		$this->data['text_image'] = $this->language->get('text_image');
		$this->data['text_price'] = $this->language->get('text_price');
		$this->data['text_model'] = $this->language->get('text_model');
		$this->data['text_manufacturer'] = $this->language->get('text_manufacturer');
		$this->data['text_availability'] = $this->language->get('text_availability');
		$this->data['text_rating'] = $this->language->get('text_rating');
		$this->data['text_summary'] = $this->language->get('text_summary');
		$this->data['text_weight'] = $this->language->get('text_weight');
		$this->data['text_dimension'] = $this->language->get('text_dimension');
		$this->data['text_empty'] = $this->language->get('text_empty');
        $this->data['text_msg'] = $this->language->get('text_msg');

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

		//adicionar para que se caso o clique em comprar e o produto for grade redirecionar para a tela do produto
		$this->data['layout_id']			 = Type_IdLayout::Tp_Idcategory;

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

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

		$this->data['review_status'] = $this->config->get('config_review_status');

		$this->data['products'] = array();

		$this->data['attribute_groups'] = array();

		foreach ($this->session->data['compare'] as $key => $product_id) {
			$product_info = $this->model_catalog_product->getProduct($product_id);

			if ($product_info) {
				if ($product_info['image']) {
					$image = $this->dmodel_tool_image->resize($product_info['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
				} else {
					$image = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
				}

				if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
					$price = $this->currency->format($product_info['price']);
				} else {
					$price = false;
				}

				if ((float)$product_info['special']) {
					$special = $this->currency->format($product_info['special']);
				} else {
					$special = false;
				}

				// if ($product_info['quantity'] <= 0) {
				// 	$availability = $product_info['stock_status'];
				// } elseif ($this->config->get('config_stock_display')) {
				// 	$availability = $product_info['quantity'];
				// } else {
				// 	$availability = $this->language->get('text_instock');
				// }


				if ($product_info['qty'] <= 0) {
					$availability = $this->language->get('text_soldout');
					$availability_css = 'background-warning text-warning border-warning';
				} else {
					$availability = $this->language->get('text_instock');
					$availability_css = 'background-success text-success border-success';
				}

				$attribute_data = array();

				$attribute_groups = $this->model_catalog_product->getProductAttributes($product_id);

				foreach ($attribute_groups as $attribute_group) {
					foreach ($attribute_group['attribute'] as $attribute) {
						$attribute_data[$attribute['attribute_id']] = $attribute['text'];
					}
				}
					
				//KIT
				$this->load->dmodel('catalog/product');
				$itens_kit = $this->dmodel_catalog_product->getProductKitItens($product_info['product_kit_id']);
				//KIT

				$this->data['products'][$product_id] = array(
					'product_id'       => $product_info['product_id'],
					'name'             => $product_info['name'],
					'thumb'            => $image,
					'price'            => $price,
					'special'          => $special,
					'description'      => utf8_substr(strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8')), 0, 200) . '...',
					'model'            => $product_info['model'],
					'manufacturer'     => $product_info['manufacturer'],
					'availability'     => $availability,
					'availability_css' => $availability_css,
					'rating'           => (int)$product_info['rating'],
					'reviews'          => sprintf($this->language->get('text_reviews'), (int)$product_info['reviews']),
					'weight'           => $this->weight->format($product_info['weight'], $product_info['weight_class_id']),
					'length'           => $this->length->format($product_info['length'], $product_info['length_class_id']),
					'width'            => $this->length->format($product_info['width'], $product_info['length_class_id']),
					'height'           => $this->length->format($product_info['height'], $product_info['length_class_id']),
					'attribute'        => $attribute_data,
					'href'             => $this->url->link('product/product', 'product_id=' . $product_id),
					'remove'           => $this->url->link('product/compare', 'remove=' . $product_id),
					'notification_value' => isset($this->cart->getProducts()[$product_id.'::']) ? $this->cart->getProducts()[$product_id.'::']['quantity'] : false,
					'itens_kit' 	   =>$itens_kit
        );


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

				foreach ($attribute_groups as $attribute_group) {
					$this->data['attribute_groups'][$attribute_group['attribute_group_id']]['name'] = $attribute_group['name'];

					foreach ($attribute_group['attribute'] as $attribute) {
						$this->data['attribute_groups'][$attribute_group['attribute_group_id']]['attribute'][$attribute['attribute_id']]['name'] = $attribute['name'];
					}
				}
			} else {
				unset($this->session->data['compare'][$key]);
			}
		}

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

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/compare.twig')) {
			$this->template = $this->config->get('config_template') . '/template/product/compare.twig';
		} else {
			$this->template = 'default/template/product/compare.twig';
		}

		$this->children = array(
			'common/breadcrumbs',
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'
		);

		$this->response->setOutput($this->render());
  	}

	public function add() {
		$this->language->load('product/compare');
		$this->load->helper('ftr_geral');
		$json = array();

		if (!isset($this->session->data['compare'])) {
			$this->session->data['compare'] = array();
		}

		if (isset($this->request->post['product_id'])) {
			$product_id = $this->request->post['product_id'];
		} else {
			$product_id = 0;
		}

		if(count($this->session->data['compare'])==4){
		    $json['error'] = 'Você pode comparar no máximo quatro produtos.';
        }

		if(!$json){

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

            $product_info = $this->model_catalog_product->getProduct($product_id);

            if ($product_info) {
                if (!in_array($this->request->post['product_id'], $this->session->data['compare'])) {

                    $this->session->data['compare'][] = $this->request->post['product_id'];
                }

                $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('product/compare'));
                $json['total'] = count($this->session->data['compare']);
            }
        }

		$this->response->setOutput(json_encode($json));
	}

		public function remove() {
		$this->language->load('product/compare');
		$this->load->helper('ftr_geral');
		$json = array();

		$key = array_search($this->request->post['remove'], $this->session->data['compare']);

		if ($key !== false) {
			unset($this->session->data['compare'][$key]);
		}

		$json['success'] = $this->language->get('text_remove');
    $json['total'] = count($this->session->data['compare']);

		$this->response->setOutput(json_encode($json));
	}

}
