<?php
class ControllerCatalogReview extends Controller {
	private $error = array();

	public function index() {
		$this->language->load('catalog/review');

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

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

		$this->document->addScript('view/javascript/template/catalog/review_list.js');

		$this->getList();
	}

	public function update() {
		$this->language->load('catalog/review');

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

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

		if (isset($this->request->get['selected']) && isset($this->request->get['status'])) {

			$this->model_catalog_review->updateStatusReview($this->request->get['selected'], $this->request->get['status']);

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

			$url = $this->getLinkUrl($this->request->get);

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

			$this->redirect($this->url->link('catalog/review', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
		$this->language->load('catalog/review');

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

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

		if (isset($this->request->get['selected']) && $this->validateDelete()) {

			$this->model_catalog_review->deleteReview($this->request->get['selected']);

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

			$url = $this->getLinkUrl($this->request->get);

			$this->redirect($this->url->link('catalog/review', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}


	public function ReviewHome() {

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

		$this->language->load('catalog/review');

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

		$json = array();

		if(isset($this->request->get['action']) && ($this->request->get['action']=='delete') ){
			if (isset($this->request->get['selected'])) {
				$this->model_catalog_review->deleteReview($this->request->get['selected']);
				$json['success_delete'] = $this->language->get('text_success_delete');
			}
		}

		if(isset($this->request->get['action']) && ($this->request->get['action']=='update') ){
			if (isset($this->request->get['selected']) && isset($this->request->get['status'])) {
				$type_status = $this->request->get['status'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
				$this->model_catalog_review->updateStatusNotificationReview($this->request->get['selected'], $type_status );
				$json['success_update'] = $this->language->get('text_success');
			}
		}


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


	protected function getList() {

		$this->load->type('tipocomum');
		$this->load->helper('ftr_geral');
		$this->load->model('catalog/product');
		$this->load->dmodel('tool/image');
		$language = $this->language->load('catalog/review');

        if (isset($this->request->get['filter_product_content'])) {
            $filter_product_content = $this->request->get['filter_product_content'];
        } else {
            $filter_product_content = Type_FilterContent::Tp_Contendo;
        }

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

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

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

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

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

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

        $sort_filter = array(
            $this->language->get('text_date_sort_asc'),
            $this->language->get('text_date_sort_desc'),
            $this->language->get('text_rating_sort_asc'),
            $this->language->get('text_rating_sort_desc'));

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

        $sort_opt = $this->getSortOptions($selected_sort);
        $sort = $sort_opt['sort'];
        $order = $sort_opt['order'];

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

		$url = $this->getLinkUrl($this->request->get);
		$sort_url = $selected_sort ? '&selected_sort=' . $selected_sort : '';

        $this->data['remove_filter'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . $sort_url, 'SSL');

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

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

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . $url, 'SSL'),
			'separator' => ' :: '
		);

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

		$data = array(
            'product_content'  => $filter_product_content,
            'product'          => $filter_product,
            'description'      => $filter_description,
		    'author'           => $filter_author,
		    'status'           => $filter_status,
			'date_start'       => $filter_date_start,
			'date_end'         => $filter_date_end,
			'sort'             => $sort,
			'order'            => $order,
			'start'            => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit'            => $this->config->get('config_admin_limit')
		);

		$review_total = $this->model_catalog_review->getTotalReviews($data);

		$results = $this->model_catalog_review->getReviews($data);

    foreach ($results as $result) {
			$action = array(
				'delete'      => $this->url->link('catalog/review/delete', 'token=' . $this->session->data['token'].'&selected='.$result['review_id'].$url, 'SSL'),
				'habilitar'   => $this->url->link('catalog/review/update', 'token=' . $this->session->data['token'].'&selected='.$result['review_id'].'&status='.Type_Status::Tp_Habilitado.$url, 'SSL'),
				'desabilitar' => $this->url->link('catalog/review/update', 'token=' . $this->session->data['token'].'&selected='.$result['review_id'].'&status='.Type_Status::Tp_Desabilitado.$url, 'SSL')
			);

			$this->data['reviews'][] = array(
				'review_id'  => $result['review_id'],
				'name'       => $result['name'],
                'product_id' => $result['product_id'],
				'author'     => $result['author'],
				'text'       => $result['text'],
				'rating'     => $result['rating'],
				'status'     => Type_Status::getNickFromConstValue($result['status']),
				'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
				'action'		 => $action
			);
		}

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

		$this->data['column_product'] = $this->language->get('column_product');
		$this->data['column_author'] = $this->language->get('column_author');
		$this->data['column_rating'] = $this->language->get('column_rating');
		$this->data['column_status'] = $this->language->get('column_status');
		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_action'] = $this->language->get('column_action');

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

		$this->data['text_enabled'] = Type_Status::getNickFromValue(Type_Status::Tp_Habilitado);
        $this->data['text_disabled'] = Type_Status::getNickFromValue(Type_Status::Tp_Desabilitado);

        $contentTotalStr = Type_FilterContent::getEnumList();
        foreach ($contentTotalStr as $key => $value) {
            $this->data['content_name'][] = array(
                'id' => $key,
                'name' => $value,
                'status' => ftr_geral::isSelected($key, $filter_product_content, Type_FilterContent::Tp_Contendo)
            );
        }

 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

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

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

		$url = $this->getLinkUrl($this->request->get, ['sort', 'order']);

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		$this->data['sort_product'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . '&sort=pd.name' . $url, 'SSL');
		$this->data['sort_author'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . '&sort=r.author' . $url, 'SSL');
		$this->data['sort_rating'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . '&sort=r.rating' . $url, 'SSL');
		$this->data['sort_status'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . '&sort=r.status' . $url, 'SSL');
		$this->data['sort_date_added'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . '&sort=r.date_added' . $url, 'SSL');


		$url = $this->getLinkUrl($this->request->get, ['page']);

		$pagination = new Pagination();
		$pagination->total = $review_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;
		$this->data['sort_filter'] = $sort_filter;
		$this->data['selected_sort'] = $selected_sort;
        $this->data['filter_count'] = count(explode('&', $this->getLinkUrl($this->request->get, ['page', 'sort', 'order', 'selected_sort']))) - 1;
        $this->data['filter_product_content'] = $filter_product_content;
        $this->data['filter_product'] = $filter_product;
        $this->data['filter_description'] = $filter_description;
        $this->data['filter_author'] = $filter_author;
		$this->data['filter_status'] = $filter_status;
        $this->data['filter_date_start'] = ftr_geral::formatDate($filter_date_start, 'br');
        $this->data['filter_date_end'] = ftr_geral::formatDate($filter_date_end, 'br');

		$this->data = array_merge($this->data, $language);

		$this->children = array(
			'common/header',
			'common/footer'
		);

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

    public function getLinkUrl($request, $remove = array())
    {
        $url = '';

        foreach ($remove as $key => $value) {
            unset($request[$value]);
        }

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

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

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

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

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

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

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

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

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

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

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

        return $url;
    }

    public function getSortOptions($opt = 0) {
        $sort_opt = array(array("sort" => "r.date_added", "order" => "ASC"),
            array("sort" => "r.date_added", "order" => "DESC"),
            array("sort" => "r.rating", "order" => "ASC"),
            array("sort" => "r.rating", "order" => "DESC"));

        if (array_key_exists($opt, $sort_opt)) {
            return $sort_opt[$opt];
        } else {
            return $sort_opt[0];
        }
    }

    public function autocomplete(){

	    $json = array();

        $this->load->type('tipocomum');
        $this->language->load('catalog/review');
        $this->load->model('catalog/review');
        $this->load->dmodel('tool/image');

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

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

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

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

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

        $data = array(
            'product_name' => $filter_product,
            'product_content_name' => $filter_content_name,
            'start'        => ($page - 1) * $limit,
            'limit'        => $limit,
            'sort'         => $sort
        );

        $results = $this->model_catalog_review->getRatedProducts($data);

        foreach ($results as $result) {

            if ($result['image'] && file_exists(DIR_IMAGE . $result['image'])) {
                $image = $result['image'];
            } else {
                $image = 'no_image.jpg';
            }

            $json[] = array(
                'product_id' => $result['product_id'],
                'name' => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                'image' => $result['image'],
                'thumb' => $this->dmodel_tool_image->resize($image, Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height)
            );
        }

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

    }

    public function validateFilters() {

        $this->language->load('catalog/review');

	    $remove = array();
	    $json = array();
	    $error = array();
	    $message = '';

	    if (isset($this->request->get['filter_product']) && $this->request->get['filter_product'] == '') {
	        $remove[] = 'filter_product';
            $remove[] = 'filter_product_content';
        }

        if (isset($this->request->get['filter_product_content']) && !in_array($this->request->get['filter_product_content'], Type_FilterContent::getEnumListConst())) {
            if (!array_search('filter_product', $remove)) {
                $remove[] = 'filter_product';
            }

            if (!array_search('filter_product_content', $remove)) {
                $remove[] = 'filter_product_content';
            }
        }

        if (isset($this->request->get['filter_description']) && $this->request->get['filter_description'] == '') {
            $remove[] = 'filter_description';
        }

        if (isset($this->request->get['filter_author']) && $this->request->get['filter_author'] == '') {
            $remove[] = 'filter_author';
        }

	    if (isset($this->request->get['filter_status']) && $this->request->get['filter_status'] == '' ||
            !in_array($this->request->get['filter_status'], [Type_Status::Tp_Habilitado, Type_Status::Tp_Desabilitado])) {
	        $remove[] = 'filter_status';
	        if ($this->request->get['filter_status'] != '*') {
	            $error[] = 'filter_status';
            }
        }

	    $date_start = $this->request->get['filter_date_start'];
	    $date_end = $this->request->get['filter_date_end'];
	    if (isset($date_start) && isset($date_end) && ($date_start != '' || $date_end != '')) {
            if (ftr_geral::validaDate($date_start) && ftr_geral::validaDate($date_end)){
                if (ftr_geral::compareDate($date_start, $date_end, 'maior')) {
                    $message = $this->language->get('error_date');
                    $remove[] = 'filter_date_start';
                    $remove[] = 'filter_date_end';
                    $error[] = 'filter_date_end';
                    $error[] = 'filter_date_start';
                }
            } else {
                $remove[] = 'filter_date_start';
                $remove[] = 'filter_date_end';

                if (ftr_geral::validaDate($date_start)) {
                    $message = $this->language->get('error_date_empty');
                    $error[] = 'filter_date_end';
                } elseif (ftr_geral::validaDate($date_end)) {
                    $message = $this->language->get('error_date_empty');
                    $error[] = 'filter_date_start';
                } else {
                    $error[] = 'filter_date_end';
                    $error[] = 'filter_date_start';
                }
            }
        } else {
            $remove[] = 'filter_date_start';
            $remove[] = 'filter_date_end';
        }

        if ($error) {
            $json['error'] = array();
            $json['error']['fields'] = $error;
            if ($message != '') {
                $json['error']['message'] = $message;
            } else {
                $json['error']['message'] = $this->language->get('error_filters');
            }
        } else {
            $json['success'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . $this->getLinkUrl($this->request->get, $remove), 'SSL');
        }

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

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'catalog/review')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}
}
