<?php

$loader = $this->registry->get('load');
$loader->controller('base/base');

class ControllerListaPresenteListaPresente extends ControllerBaseBase {

	private $error = array();
  protected $referencePathFile = 'listapresente/listapresente';

	public function loadscripts() {
		$this->document->addScript(array(
			'public/js/postcode.js',
			'public/js/menuAccount.js',
		));
	}

	protected function loadLanguage() {
		$language = $this->language->load('listapresente/listapresente');
		$languageEdit = $this->language->load('listapresente/edit');
		$languageNew = $this->language->load('listapresente/new');
		$languageSearch = $this->language->load('listapresente/pesquisa');
		$languageProduct = $this->language->load('listapresente/produto');

		$this->dataVue['language'] = array_merge($this->dataVue, $language, $languageEdit, $languageNew, $languageSearch, $languageProduct);
		$this->data['language'] = array_merge($this->dataVue, $language, $languageEdit, $languageNew, $languageSearch, $languageProduct);
	}

	public function checkLicence() {
		if (!file_exists(DIR_APPLICATION . '../admin/controller/module/futura/futuralistapresente.dat')) {
			$this->session->data['warning'] = 'Licença inválida! Contate o suporte da loja para identificar o problema. Módulo: Lista de Presentes | Código de erro: 01';
			$this->redirect( $this->url->link( 'account/account', '', 'SSL' ) );
		}else {
			require_once(DIR_APPLICATION . '../admin/controller/module/futura/futuralistapresente.dat');
		}

		if (!$licenca->verifyValidade()){
			$this->session->data['warning'] = 'Licença inválida! Contate o suporte da loja para identificar o problema. Módulo: Lista de Presentes | Código de erro: 03';
			$this->redirect( $this->url->link( 'account/account', '', 'SSL' ) );
		}
	}

	// Route: listapresente/listapresente
	public function index() {
		$this->loadscripts();
		$this->loadLanguage();
		$this->getList();
	}

	public function getList() {
		$this->checkLicence();
		$this->document->addScript(
			'catalog/view/theme/vista/public/js/listapresente/listapresente.js',	
		);

		if (!$this->config->get('listapresente_status')) {
			$this->redirect( $this->url->link('common/home', '', 'SSL'));
		}

		if (!$this->customer->isLogged()) {
			$this->session->data['redirect'] = $this->url->link('listapresente/listapresente', '', 'SSL');
			$this->redirect($this->url->link('account/login', '', 'SSL'));
		}

		if (!empty($this->session->data['successNew'])) {
			$this->dataVue['successNew'] = $this->session->data['successNew'];
			unset($this->session->data['successNew']);
		}

		if (!empty($this->session->data['successEdit'])) {
			$this->dataVue['successEdit'] = $this->session->data['successEdit'];
			unset($this->session->data['successEdit']);
		}
	
		$this->data['futuragrade_status'] = $this->config->get('futuragrade_status');
		$this->load->model('listapresente/listapresente');
		
		$listas = $this->model_listapresente_listapresente->getListas();
		$this->dataVue['listas'] = array();
		foreach ($listas as $lista) {
			$compradores = $this->model_listapresente_listapresente->getCompLista($lista['id_lista']);
			$this->dataVue['listas'][] = array(
				'id'            => $lista['id_lista'],
				'nome'          => $lista['nome_lista'],
				'data_validade' => implode('/',array_reverse(explode('-',$lista['data_valid_lista']))),
				'data_lista'    => implode('/',array_reverse(explode('-',$lista['data_cad_lista']))),
				'data_evento'   => implode('/',array_reverse(explode('-',$lista['data_eve_lista']))),
				'categoria'     => $lista['desc_cat_lista'],
				'logradouro'    => $lista['logradouro'],
				'cep'           => $lista['cep'],
				'numero'        => $lista['numero'],
				'bairro'        => $lista['bairro'],
				'cidade'        => $lista['cidade'],
				'estado'        => $lista['estado'],
				'latitude'      => $lista['latitude'],
				'longitude'     => $lista['longitude'],
				'complemento'   => $lista['complemento'],
				'status'        => ($lista['status_lista'] == 0 ? 'Inativa' : 'Ativa'),
				'itens'         => (0 < $lista['qtde'] ? $lista['qtde'] : 0),
				'compradores'   => $compradores,
				'href'          => $this->url->link('listapresente/listapresente/edit', 'id_lista=' . $lista['id_lista']),
				'remove'        => $this->url->link('listapresente/listapresente', 'remove=' . $lista['id_lista'])
			);
		}

		$this->dataVue['total'] = $this->model_listapresente_listapresente->getTotalListas(array('lista_id_cliente' => $this->customer->getID()));
		$this->load->dmodel('tool/image');

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

		$this->data['breadcrumbs'] 	 = array();
		$this->data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home'),
			'separator' => false
		);
		$this->data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_giftList_account'),
			'href' => $this->url->link('account/account', '', 'SSL' ),
			'separator' => $this->language->get('text_separator')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('listapresente/listapresente'),
			'separator' => $this->language->get('text_separator')
		);
		$this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);

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

		$this->data['error_warning'] = (isset($this->session->data['warning']) ? $this->session->data['warning'] : '');
		if (isset($this->data['error_warning']) == isset($this->session->data['warning'])) {
			unset($this->session->data['warning']);
		}	

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

		if (!$this->ftrgeralregistry->isApp()) {
			array_push($this->children, 'module/account');
		}

		$this->response->setOutput( $this->render('listapresente/listapresente') );
	}

	public function onRemoveList() {
		$this->load->model('listapresente/listapresente');
		$this->loadLanguage();
		$json_response = [];

		if (isset($this->request->get['id'])) {
			$key = $this->request->get['id'];
						
			if ($this->model_listapresente_listapresente->delete($key)) {
				$json_response['success'] = $this->language->get('text_remove_list');
				return $this->response->setOutputJson($json_response);
			}else {
				$json_response['warning'] = $this->language->get('error_lista_remove');
				return $this->response->setOutputJson($json_response);
			}
		}
	}

	public function validateLimitList() {
		$this->loadLanguage();
		$this->load->model('listapresente/listapresente');

		$json = [];
		$total = $this->model_listapresente_listapresente->getTotalListas(array('lista_id_cliente' => $this->customer->getID()));
		$list_quantity = $this->config->get('futuralistapresente_max_listas');

		if (isset($list_quantity) &&  isset($total) && $list_quantity <= $total) {
			$json['message'] = $this->language->get('error_max_lista');
			$this->response->setOutputJson($json);
		} else {
			$json['link_new'] = $this->url->link('listapresente/listapresente/new', '', 'SSL');
			$this->response->setOutputJson($json);
		}
	}

	// Callback in edit() and new()
	public function getForm() {

		$this->loadLanguage();
		$this->loadscripts();
		$this->load->model('localisation/zone');
		$this->load->model('listapresente/listapresente');
		$this->load->dmodel('tool/image');
		$this->document->addScript(
			'catalog/view/theme/vista/public/js/listapresente/form.js',	
		);

		if (!$this->config->get('listapresente_status')){
			$this->redirect($this->url->link('common/home', '', 'SSL'));
		}

		if (!$this->customer->isLogged()){
			$this->session->data['redirect'] = $this->url->link('account/edit', '', 'SSL');
			$this->redirect($this->url->link('account/login', '', 'SSL'));
		}

		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' 			=> $this->language->get('text_home'),
			'href' 			=> $this->url->link('common/home'),
			'separator' => false
		);
		$this->data['breadcrumbs'][] = array(
			'text'			=> $this->language->get('text_list'),
			'href' 			=> $this->url->link('listapresente/listapresente', '', 'SSL'),
			'separator' => $this->language->get('text_separator')
		);
		if(!isset($this->request->get['id_lista'])){
			$this->data['breadcrumbs'][] = array(
				'text' 			=> $this->language->get('text_new'),
				'href' 			=> $this->url->link('listapresente/listapresente/new', '', 'SSL'),
				'separator' => $this->language->get('text_separator')
			);
		}else{
			$this->data['breadcrumbs'][] = array(
				'text' 			=> $this->language->get('text_edit'),
				'href' 		  => $this->url->link('listapresente/listapresente/edit', '&id_lista='.$this->request->get['id_lista'], 'SSL' ),
				'separator' => $this->language->get( 'text_separator' )
			);
			$lista_info = $this->model_listapresente_listapresente->getLista($this->request->get['id_lista']);
		}
		$this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);
		
		// Categorys
		$categorias = $this->model_listapresente_listapresente->getCategorias($this->config->get('futuralistapresente_cat_habilitas'));
		$categoria_id = (!empty($lista_info) ? $lista_info['categoria_id'] : NULL);
		$this->data['categorias'] = array();
		if ($categorias) {
			foreach ($categorias as $categoria) {
				$this->dataVue['categorias'][] = array(
					'name'     => $categoria['desc_cat_lista'],
					'value'    => $categoria['id_cat_lista'],
					'selected' => (!is_null($categoria_id) && ($categoria_id == $categoria['id_cat_lista'])) ? true : false
				);
			}
		}

		// Settings
		$this->dataVue['settings'] = array(
			'action' => (isset($this->request->get['id_lista']) ? $this->url->link( 'listapresente/listapresente/edit&id_lista=' . $this->request->get['id_lista'], '', 'SSL' ) : $this->url->link( 'listapresente/listapresente/new', '', 'SSL' )),
			'intervalo_Validade' => $this->config->get('futuralistapresente_Intervalo_Validade'),
			'postcode_readonly'  => true,
			'listaid'            => (!empty($lista_info) ? $lista_info['id'] : ''),
			'nome'               => (isset($this->request->post['nome']) ? $this->request->post['nome'] : (!empty($lista_info) ? $lista_info['nome'] : '')),
			'validade'           => (isset($this->request->post['validade']) ? $this->request->post['validade'] : (!empty($lista_info) ? ftr_geral::formatDate($lista_info['validade'],'br') : '')),
			'cadastro'           => (isset($this->request->post['cadastro']) ? $this->request->post['cadastro'] : (!empty($lista_info) ? ftr_geral::formatDate($lista_info['cadastro'],'br') : date('d/m/Y'))),
			'evento'             => (isset($this->request->post['evento']) ? $this->request->post['evento'] : ''),
			'data'               => (isset($this->request->post['data']) ? $this->request->post['data'] : (!empty($lista_info) ? ftr_geral::formatDate($lista_info['evento'],'br') : '')),
			'cliente'            => (isset($this->request->post['cliente']) ? $this->request->post['cliente'] : $this->customer->getFirstName() . ' ' . $this->customer->getLastName()),
			'categoria'          => (isset($this->request->post['categoria']) ? $this->request->post['categoria'] : (!empty($lista_info) ? $lista_info['categoria'] : '')),
			'parceiro'           => (isset($this->request->post['parceiro']) ? $this->request->post['parceiro'] : (!empty($lista_info) ? $lista_info['parceiro'] : '')),
			'status'             => (isset($this->request->post['status']) ? $this->request->post['status'] : (!empty($lista_info) ? $lista_info['status'] : '')),
			'frase'              => (isset($this->request->post['frase']) ? $this->request->post['frase'] : ( !empty($lista_info) ? $lista_info['frase'] : '')),
			'logradouro'         => (isset($this->request->post['logradouro']) ? $this->request->post['logradouro'] : (!empty($lista_info) ? $lista_info['logradouro'] : '')),
			'numero'             => (isset($this->request->post['numero']) ? $this->request->post['numero'] : (!empty($lista_info) ? $lista_info['numero'] : '')),
			'complemento'        => (isset($this->request->post['complemento']) ? $this->request->post['complemento'] : ( !empty($lista_info) ? $lista_info['complemento'] : '')),
			'apelido'            => (isset($this->request->post['apelido']) ? $this->request->post['apelido'] : ( !empty($lista_info) ? $lista_info['apelido'] : '')),
			'bairro'             => (isset($this->request->post['bairro']) ? $this->request->post['bairro'] : (!empty($lista_info) ? $lista_info['bairro'] : '')),
			'postcode'           => (isset($this->request->post['postcode']) ? $this->request->post['postcode'] : (!empty($lista_info) ? $lista_info['cep'] : '')),
			'estado'             => (isset($this->request->post['estado']) ? $this->request->post['estado'] : ( !empty($lista_info) ? $lista_info['estado'] : '')),
			'cidade'             => (isset( $this->request->post['cidade']) ? $this->request->post['cidade'] : ( !empty($lista_info) ? $lista_info['cidade'] : '')),
			'zones'              => $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil),
			'zone_selected'      => $this->config->get('config_zone_id'),
			'back'               => $this->url->link('listapresente/listapresente', '', 'SSL'),
			'link_main'          => $this->url->link('common/home', '', 'SSL'),
		);	
		
		// Products 
		$this->data['produtos'] = array();
		$this->dataVue['produtos'] = array();
		$this->dataVue['buyers'] = array();
		if(isset($lista_info['produtos']) && isset($this->request->get['id_lista'])){
			
			$this->load->dmodel('tool/image');
			$ListID = $this->request->get['id_lista'];
			foreach ($lista_info['produtos'] as $produto) {

				if ($produto['imagem']) {
					$watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
					$image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $produto['data_atualizacao_replicacao']) . $watermark_config_date_number;
					$imagem = $this->dmodel_tool_image->resizeWithWatermark( $produto['imagem'], $this->config->get('futuralistapresente_config_image_lista_width'), $this->config->get('futuralistapresente_config_image_lista_height')) . $image_version_number;
				} else {
					$imagem = $this->dmodel_tool_image->resize('data\sem-imagem.png', $this->config->get('futuralistapresente_config_image_lista_width'), $this->config->get('futuralistapresente_config_image_lista_height'));
				}

				$cont = $produto['qtde'] - $produto['qtdeComp'];
				if (( !$produto['qtde'] && $produto['qtdeComp'] )) {
					$status = 'Sucesso';
				} else {
					if (( !$produto['qtde'] && !$produto['qtdeComp'] )) {
						$status = 'Inativo';
					} else {
						$status = 'Em estoque';
					}
				}

				$opcoes = '';
				$opcoes2 = '';
				if ($produto['opcoes']) {
					foreach ($produto['opcoes'] as $opcao) {
						$opcoes .= '<span>' . $opcao['nome_opcao'] . ' = ' . $opcao['valor_opcao'] . '</span><br />';
						$opcoes2 .= '<span>' . $opcao['nome_opcao'] . ' = ' . $opcao['valor_opcao'] . '</span> | ';
					}
				}

				//KIT
				$this->load->dmodel('catalog/product');
				$itens_kit = $this->dmodel_catalog_product->getProductKitItens($produto['product_kit_id']);			
				$special = ((float)$produto['special'] ? $this->currency->format($produto['special']) : false);	

				$order_status = $this->config->get('futuralistapresente_order_status_sale');
				$compradores = $this->model_listapresente_listapresente->getCompProd($ListID, $produto['item_id'], $order_status);
				$hasBuyer = (isset($compradores) ? (!empty($compradores) ? count($compradores) : 0)  : 0);

				if ($hasBuyer > 0 ) {
					foreach ($compradores as $comprador) {
						$sameProduct = false;

						foreach ($this->dataVue['buyers'] as &$buyer) {
							if ($buyer['nome'] === $produto['nome']) {
								$sameProduct = true;
								$buyer['compradores'][] = array(
									'complete_name' => (isset($comprador['nome']) && isset($comprador['sobrenome'])) ? $comprador['nome']. ' '. $comprador['sobrenome'] : '',
									'email'         => (isset($comprador['email']) ? (!empty($comprador['email']) ? $comprador['email'] : '') : ''),
									'fone'          => (isset($comprador['fone'])  ? (!empty($comprador['fone']) ? $comprador['fone'] : '**********') : '**********'),
								);
								break;
							}
						}
		
						if (!$sameProduct) {
							$this->dataVue['buyers'][] = array(
								'nome'         => $produto['nome'],
								'qtdeComp'     => $produto['qtdeComp'],
								'compradores'  => array(
									array(
										'complete_name' => (isset($comprador['nome']) && isset($comprador['sobrenome'])) ? $comprador['nome']. ' '. $comprador['sobrenome'] : '',
										'email'         => (isset($comprador['email']) ? (!empty($comprador['email']) ? $comprador['email'] : '') : ''),
										'fone'          => (isset($comprador['fone'])  ? (!empty($comprador['fone']) ? $comprador['fone'] : '**********') : '**********'),
									)
								),
							);
						}
					}	
				}

				$this->dataVue['produtos'][] = array(
					'item'                      => intval($produto['item_id']),
					'product_id'                => intval($produto['id']),
					'nome'                      => $produto['nome'],
					'href'                      => $this->url->link('product/product', '&product_id=' . $produto['id'], 'SSL'),
					'imagem'                    => $imagem,
					'special'                   => $special,
					'qtde'                      => intval($produto['qtde']),
					'valor'                     => $this->currency->format( $produto['valor'] ),
					'qtdeComp'                  => intval($produto['qtdeComp']),
					'status'                    => $status,
					'opcoes'                    => $opcoes,
					'opcoes2'                   => $opcoes2,
					'compradores'               => $compradores,
					'color_description'         => ($this->config->get('futuragrade_status')) ? $produto['color_description'] : '',
					'size_description'          => ($this->config->get('futuragrade_status')) ? $produto['size_description'] : '',
					'specification_description' => ($this->config->get('futuragrade_status')) ? $produto['specification_description'] : '',
					'remove'                    => $this->url->link( 'listapresente/listapresente/removeproduto', 'remove=' . $produto['id'] . '&lista=' . $this->request->get['id_lista'] . '&item=' . $produto['item_id'] . '&comp=' . $produto['qtdeComp'] ),
					'itens_kit' 				        => $itens_kit
				);
			}
		}

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

		if (!$this->ftrgeralregistry->isApp()) {
			array_push($this->children, 'module/account');
		}

		$this->response->setOutput($this->render('listapresente/form'));
	}

	public function validate() {
		$this->loadLanguage();

		$infosList = isset($this->request->post) ? $this->request->post : [];
		$errors = [];

		$module_errors = $this->validate->execute([
			'nome' => [
				'value' => trim($infosList['nome']),
				'validates' => ['isEmpty'],
				'message' => $this->language->get('error_validate'),
			],
			'data' => [
				'value' => trim($infosList['data']),
				'validates' => ['isEmpty', 'isDateBiggerThanToday'],
				'message' => $this->language->get('error_validate'),
			],
			'categoria' => [
				'value' => trim($infosList['categoria']),
				'validates' => ['isEmpty', 'isIntegerNumber'],
				'message' => $this->language->get('error_validate'),
			],
			'frase' => [
				'value' => trim($infosList['frase']),
				'validates' => [], 
				'message' => $this->language->get('error_validate'),
			],
			"postcode" => [
				'value' => $infosList['postcode'],
				'validates' => [
					[
						'method' => 'isEmpty',
						'message' => $this->language->get('error_validate'),
						'condition' => isset($infosList['zone_id']) && isset($infosList['codigo_municipio']),
					],
					[
						'method' => 'isCep',
						'message' => $this->language->get('error_validate'),
					],
				]
			],
			'apelido' => [
				'value' => trim($infosList['apelido']),
				'validates' => ['isEmpty'],
			],
			'numero' => [
				'value' => trim($infosList['numero']),
				'validates' => ['isIntegerNumber'], 
				'message' => $this->language->get('error_validate'),
			],
			'complemento' => [
				'value' => trim($infosList['complemento']),
				'validates' => [], 
				'message' => $this->language->get('error_validate'),
			],
			'address_1' => [
				'value' => trim($infosList['address_1']),
				'validates' => ['isEmpty'],
			],
			'address_2' => [
				'value' => trim($infosList['address_2']),
				'validates' => ['isEmpty'],
			],
			'codigo_municipio' => [
				'value' => trim($infosList['codigo_municipio']),
				'validates' => ['isEmpty'],
			],
			'zone_id' => [
				'value' => trim($infosList['zone_id']),
				'validates' => ['isEmpty'],
			],
		]);

		$errors = array_merge($errors, $module_errors);

		if ($errors) {
			return $errors;
		}
		return; 
	}

	// Route: listapresente/listapresente/new
	public function new() {
		
		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
		
			$this->loadLanguage();
			$json_new = [];
			$errors =  $this->validate();
			
			if($errors) {
				$json_new['errors'] = $errors;
				return $this->response->setOutputJson($json_new);
			}

			$this->request->post['cadastro'] = isset($this->request->post['cadastro']) ? $this->request->post['cadastro'] : date('d/m/Y') ;
			$this->load->model('listapresente/listapresente');
			$this->model_listapresente_listapresente->addLista($this->request->post);

			$this->session->data['successNew'] = $this->language->get('text_new_success');
			$json_new['redirect'] = $this->url->link('listapresente/listapresente', '', 'SSL');
			return $this->response->setOutputJson($json_new);
		}
		
		$this->dataVue['mostrarprodutos'] = false;
		$this->getForm();
	}

	// Route: listapresente/listapresente/edit
	public function edit() {

		if ($this->request->server['REQUEST_METHOD'] == 'POST') {

			$this->loadLanguage();
			$json_edit = [];
			$errors = $this->validate();

			if($errors) {
				$json_edit['errors_validate'] = $errors;
				return $this->response->setOutputJson($json_edit);
			}

			$this->updateprodlista(); 
			$this->removeproduto();

			$this->load->model('listapresente/listapresente');
			$this->model_listapresente_listapresente->editLista( $this->request->post, $this->request->get['id_lista'] );
			
			$this->session->data['successEdit'] = $this->language->get('text_edit_success');
			$json_edit['redirect'] = $this->url->link('listapresente/listapresente', '', 'SSL');
			return $this->response->setOutputJson($json_edit);
		}

		$this->dataVue['mostrarprodutos'] = true;
		$this->getForm();
	}

	public function removeproduto() {

		if (!$this->customer->isLogged()) {
			$this->session->data['redirect'] = $this->url->link( 'account/edit', '', 'SSL' );
			$this->redirect( $this->url->link( 'account/login', '', 'SSL' ) );
		}

		$oldProductIds   = [];
		$productsIds     = []; 
		$missingId       = [];
		$deleteList      = [];

		extract($this->request->post);

		if (isset($oldProducts) && isset($produtos)) {
			foreach ($oldProducts as $oldProduct) {
				$oldProductIds[] = $oldProduct['product_id'];
			}
			foreach ($produtos as $produto) {
				$productsIds[] = $produto['product_id'];
			}
	
			$missingId = array_diff($oldProductIds, $productsIds);
	
			if (isset($missingId)) {
				foreach ($oldProducts as $oldProduct) {
					foreach ($missingId as $key => $value) {
						if ($value == $oldProduct['product_id']) {
							$deleteList[] = $oldProduct;
						}
					}
				}
			}

			if (isset($deleteList)) {
				foreach ($deleteList as $item => $itemInfo) {
					$remove = $itemInfo['product_id'];
					$item = $itemInfo['item'];
					$listaid;
			
					if (isset($remove) && isset($listaid) && isset($item)) {
						$this->load->model('listapresente/listapresente');
						$this->model_listapresente_listapresente->removeproduto($remove, $listaid, $item);
					}
				}
			}
			return;
		} elseif (isset($oldProducts)) {
			foreach ($oldProducts as $item => $itemInfo) {
				$remove = $itemInfo['product_id'];
				$item = $itemInfo['item'];
				$listaid;
		
				if (isset($remove) && isset($listaid) && isset($item)) {
					$this->load->model('listapresente/listapresente');
					$this->model_listapresente_listapresente->removeproduto($remove, $listaid, $item);
				}
			}
		}
		return; 
	}

	public function updateprodlista() {
		$this->checkLicence();
		$this->loadLanguage();

		if (!$this->config->get('listapresente_status' )){
			$this->redirect( $this->url->link('common/home', '', 'SSL'));
		}

		$this->load->model('listapresente/listapresente');
		$json_updateProd = [];

		extract($this->request->post);
		if (isset($produtos)) {
			foreach ($produtos as $key => $value) {
				$qtde      = $value['qtde'];
				$item      = $value['item'];
				$this->model_listapresente_listapresente->updateprodlista($item, $listaid, $qtde);
			}
		} 
	}

	// Route: listapresente/listapresente/buscalista
	public function autocomplete() {
		$this->checkLicence();

		if (!$this->config->get( 'listapresente_status' )) {
			$this->redirect( $this->url->link( 'common/home', '', 'SSL' ) );
		}

		$json = array();

		if (isset( $this->request->get['filter'] )) {
			$this->load->model( 'listapresente/listapresente' );
			$results = $this->model_listapresente_listapresente->getListasAutoComplete( $this->request->get['filter'] );
			foreach ($results as $result) {
				$json[] = array( 'lista_id' => $result['id_lista'], 'name' => strip_tags( html_entity_decode( $result['nome_lista'], ENT_QUOTES, 'UTF-8' ) ), 'cliente' => strip_tags( html_entity_decode( $result['firstname'], ENT_QUOTES, 'UTF-8' ) ) );
			}
		}

		$sort_order = array();
		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}

		array_multisort( $sort_order, SORT_ASC, $json );
		$this->response->setOutput( json_encode( $json ) );
	}

	public function buscalista() {
		$this->checkLicence();

		if (!$this->config->get( 'listapresente_status' )) {
			$this->redirect( $this->url->link( 'common/home', '', 'SSL' ) );
		}

		$this->language->load('listapresente/pesquisa');
		$this->load->model('listapresente/listapresente');

		$search = (isset($this->request->get['search_lista']) ? $this->request->get['search_lista'] : ''); 
		$sort = (isset($this->request->get['sort']) ? $this->request->get['sort'] : 'nome_lista');
		$order = (isset($this->request->get['order']) ? $this->request->get['order'] : 'ASC');
		$page = (isset($this->request->get['page']) ? $this->request->get['page'] : 0); 
		$limit = (isset($this->request->get['limit']) ? $this->request->get['limit'] : $this->config->get('config_catalog_limit')); 

		if (isset( $this->request->get['search_lista'] )) {
			$this->document->setTitle( $this->language->get( 'heading_title' ) . ' - ' . $this->request->get['search_lista'] );
		} else {
			$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' ), 'separator' => false );
		$this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);

		$url = '';

		if (isset($this->request->get['search_lista'])) $url .= '&search_lista=' . urlencode(html_entity_decode($this->request->get['search_lista'], 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'];
		

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


		$this->data['heading_title'] = $this->language->get( 'heading_title' );
		$this->data['text_search'] = (isset($this->request->get['search_lista']) ? $this->language->get( 'text_search' ) . ' "' . $this->request->get['search_lista'] . '"' : $this->language->get( 'text_search' ));
		$this->data['text_empty']        = $this->language->get( 'text_empty' );
		$this->data['text_critea']       = $this->language->get( 'text_critea' );
		$this->data['text_keyword']      = $this->language->get( 'text_keyword' );
		$this->data['text_category']     = $this->language->get( 'text_category' );
		$this->data['text_sub_category'] = $this->language->get( 'text_sub_category' );
		$this->data['text_quantity']     = $this->language->get( 'text_quantity' );
		$this->data['text_manufacturer'] = $this->language->get( 'text_manufacturer' );
		$this->data['text_model']        = $this->language->get( 'text_model' );
		$this->data['text_price']        = $this->language->get( 'text_price' );
		$this->data['text_tax']          = $this->language->get( 'text_tax' );
		$this->data['text_points']       = $this->language->get( 'text_points' );
		$this->data['text_compare']      = sprintf( $this->language->get( 'text_compare' ), (isset( $this->session->data['compare'] ) ? count( $this->session->data['compare'] ) : 0) );
		$this->data['text_display']      = $this->language->get( 'text_display' );
		$this->data['text_list']         = $this->language->get( 'text_list' );
		$this->data['text_grid']         = $this->language->get( 'text_grid' );
		$this->data['text_sort']         = $this->language->get( 'text_sort' );
		$this->data['text_limit']        = $this->language->get( 'text_limit' );
		$this->data['entry_search']      = $this->language->get( 'entry_search' );
		$this->data['entry_search_two']  = $this->language->get( 'entry_search_two' );
		$this->data['entry_description'] = $this->language->get( 'entry_description' );
		$this->data['button_search']     = $this->language->get( 'button_search' );
		$this->data['button_cart']       = $this->language->get( 'button_produto' );
		$this->data['button_wishlist']   = $this->language->get( 'button_wishlist' );
		$this->data['button_compare']    = $this->language->get( 'button_compare' );
		$this->data['listas']            = array(  );

		if (( isset( $this->request->get['search_lista'] ) || isset( $this->request->get['filter_tag'] ) )) {
			$options = array( 'sort' => $sort, 'order' => $order, 'page' => $page, 'limit' => $limit, 'data' => date( 'Y-m-d' ) );
			$listas_info = $this->model_listapresente_listapresente->getListasAutoComplete($search, $options);
			foreach ($listas_info as $lista) {
				$this->data['listas'][] = array( 'nome' => $lista['nome_lista'], 'cliente' => $lista['firstname'] . ' ' . $lista['lastname'], 'data' => implode( '/', array_reverse( explode( '-', $lista['data_eve_lista'] ) ) ), 'validade' => implode( '/', array_reverse( explode( '-', $lista['data_valid_lista'] ) ) ), 'href' => $this->url->link( 'listapresente/produtos', 'id_lista=' . $lista['id_lista'] ) );
			}

			$url = '';
			if (isset($this->request->get['search_lista'])) $url .= '&search_lista=' . urlencode( html_entity_decode( $this->request->get['search_lista'], ENT_QUOTES, 'UTF-8' ) );
			if (isset($this->request->get['limit'])) $url .= '&limit=' . $this->request->get['limit'];
			
			$this->data['sorts'] = array(  );
			$this->data['sorts'][] = array( 'text' => $this->language->get( 'text_default' ), 'value' => 'nome_lista-ASC', 'href' => $this->url->link( 'listapresente/listapresente/buscalista', 'sort=nome_lista&order=ASC' . $url ) );
			$this->data['sorts'][] = array( 'text' => $this->language->get( 'text_name_asc' ), 'value' => 'nome_lista-ASC', 'href' => $this->url->link( 'listapresente/listapresente/buscalista', 'sort=nome_lista&order=ASC' . $url ) );
			$this->data['sorts'][] = array( 'text' => $this->language->get( 'text_name_desc' ), 'value' => 'nome_lista-DESC', 'href' => $this->url->link( 'listapresente/listapresente/buscalista', 'sort=nome_lista&order=DESC' . $url ) );
			$this->data['sorts'][] = array( 'text' => $this->language->get( 'text_cliente_asc' ), 'value' => 'firstname-ASC', 'href' => $this->url->link( 'listapresente/listapresente/buscalista', 'sort=firstname&order=ASC' . $url ) );
			$this->data['sorts'][] = array( 'text' => $this->language->get( 'text_cliente_desc' ), 'value' => 'firstname-DESC', 'href' => $this->url->link( 'listapresente/listapresente/buscalista', 'sort=firstname&order=DESC' . $url ) );

			$url = '';
			if (isset($this->request->get['search_lista'])) $url .= '&search_lista=' . urlencode(html_entity_decode($this->request->get['search_lista'], 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'];
			
			$this->data['limits'] = array(  );
			$limits = array_unique( array( $this->config->get( 'config_catalog_limit' ), 25, 50, 75, 100 ) );
			sort( $limits );
			foreach ($limits as $limits) {
				$this->data['limits'][] = array( 'text' => $limits, 'value' => $limits, 'href' => $this->url->link( 'listapresente/listapresente/buscalista', $url . '&limit=' . $limits ) );
			}

			$url = '';
			if (isset($this->request->get['search_lista'])) $url .= '&search_lista=' . urlencode( html_entity_decode( $this->request->get['search_lista'], 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'];
			
			$lista_total              = $this->model_listapresente_listapresente->getTotalListas();
			$pagination               = new Pagination();
			$pagination->total        = $lista_total;
			$pagination->page         = $page;
			$pagination->limit        = $limit;
			$pagination->text         = $this->language->get('text_pagination');
			$pagination->url          = $this->url->link('listapresente/listapresente/buscalista', $url . '&page={page}');
			$this->data['pagination'] = $pagination->render();
		}

		$this->data['search'] = $search;
		$this->data['sort']   = $sort;
		$this->data['order']  = $order;
		$this->data['limit']  = $limit;

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

		$this->data['error_warning'] = ( isset($this->session->data['warning']) ? $this->session->data['warning'] : ''); 
		if (isset($this->session->data['warning'])) unset($this->session->data['warning']);

		if (file_exists( DIR_TEMPLATE . $this->config->get( 'config_template' ) . '/template/listapresente/pesquisa.tpl' )) {
			$this->template = $this->config->get( 'config_template' ) . '/template/listapresente/pesquisa.tpl';
		}else {
			$this->template = 'default/template/listapresente/pesquisa.tpl';
		}

		$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(  ) );
	}

	// Add product on gift list by Product Page 
	public function add() {
		$this->checkLicence();
		$this->loadLanguage();
		$this->load->helper('ftr_geral');

		if (!$this->config->get('listapresente_status')) {
			$this->redirect( $this->url->link('common/home', '', 'SSL'));
		}

		$this->data['futuragrade_status'] = $this->config->get('futuragrade_status');
		$this->load->model('catalog/product');
		$this->load->model('listapresente/listapresente');

		$json = array();
		$lista_info = array();
		$lista_info = $this->model_listapresente_listapresente->getListas(array( 'status_lista' => true ));

		if (!$lista_info) {
			$json['error'] = $this->language->get('error_lista');
		} else {
			$lista_id = $lista_info[0]['id_lista'];
			if ($lista_info[0]['data_valid_lista']<date('Y-m-d')) {
				$json['error']	= $this->language->get('erro_data_validade');
			}
		}

		$product_id = (isset($this->request->post['product_id']) ? $this->request->post['product_id'] : 1);

		$product_info = $this->model_catalog_product->getProduct( $product_id );
		if (($product_info && !$json )) {

			$quantity = (isset($this->request->post['quantity']) ? $this->request->post['quantity'] : 1);
			$option = (isset($this->request->post['option']) ? array_filter($this->request->post['option']) : array());

			$product_options = $this->model_catalog_product->getProductOptions( $this->request->post['product_id'] );
			foreach ($product_options as $product_option) {
				if (($product_option['required'] && empty($option[$product_option['product_option_id']]))) {
					$json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
					continue;
				}
			}

			$produtoLista = $this->model_listapresente_listapresente->GetProdLista($lista_id, array('item_id_produto' => $product_id ));
			if ($produtoLista) $json['error'] =  $this->language->get('error_produto');
			
			if ($this->config->get('futuragrade_status')) {
				$gridhave = $this->model_catalog_product->getGridHave($product_id);

				if ($gridhave['grid_id']) {
					$this->cart->addQtd($gridhave['grid_id'] , $quantity);
				}

				if (!isset($this->request->get['size_id'])) {
					if ($gridhave['have_size']) {
						$json['error']['grid_size'] = 'Por favor, informe um tamanho!';
					}
				}

				if (!isset($this->request->get['specification_id'])) {
					if($gridhave['have_specification']){
						$json['error']['grid_specification'] = 'Por favor, informe uma especificação!';
					}
				}
			}

			if (!$json) {
				$query = $this->model_listapresente_listapresente->addProdLista( $quantity, $product_id, $lista_id );
				foreach ($option as $k => $v) {
					foreach ($product_options as $product_option) {

						if ($product_option['product_option_id'] == $k) {
							if (is_array( $product_option['option_value'])) {
								foreach ($product_option['option_value'] as $opcoes) {

									if ($opcoes['product_option_value_id'] == $v) {
										$array['nome']            = $product_option['name'];
										$array['valor']           = $opcoes['name'];
										$array['lista_id']        = $lista_id;
										$array['produto_id']      = $product_id;
										$array['opcao_id']        = $opcoes['product_option_value_id'];
										$array['item_id']         = $query['id'];
										$array['op_parent_opcao'] = $product_option['product_option_id'];
										$array['op_array']        = 0;
										$this->model_listapresente_listapresente->addOpcaoProduto( $array );
										continue;
									}

									if (is_array( $v )) {
										foreach ($v as $value) {

											if ($opcoes['product_option_value_id'] == $value) {
												$array['nome']            = $product_option['name'];
												$array['valor']           = $opcoes['name'];
												$array['lista_id']        = $lista_id;
												$array['produto_id']      = $product_id;
												$array['opcao_id']        = $value;
												$array['item_id']         = $query['id'];
												$array['op_parent_opcao'] = $product_option['product_option_id'];
												$array['op_array']        = 1;
												$this->model_listapresente_listapresente->addOpcaoProduto( $array );
												continue;
											}
										}
										continue;
									}
								}
								continue;
							}
							$array['nome']            = $product_option['name'];
							$array['valor']           = $v;
							$array['lista_id']        = $lista_id;
							$array['produto_id']      = $product_id;
							$array['opcao_id']        = $product_option['product_option_id'];
							$array['item_id']         = $query['id'];
							$array['op_parent_opcao'] = $product_option['product_option_id'];
							$array['op_array']        = 0;
							$this->model_listapresente_listapresente->addOpcaoProduto( $array );
							continue;
						}
					}
				}

				$json['total_qtd'] = $this->presente->countProductsList();
				$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( 'listapresente/listapresente/edit', 'id_lista=' . $lista_id ) 
				);

			}	else {
				$json['redirect'] = str_replace( '&amp;', '&', $this->url->link( 'product/product', 'product_id=' . $this->request->post['product_id'] ) );
			}
		}
		$this->response->setOutput( json_encode( $json ) );
	}
}