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

    public function index()
    {
        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = $this->url->link('account/return', '', 'SSL');

            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

        $language = $this->language->load('account/return');
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($this->language->get('heading_title'));
        $this->document->addScript('catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');
        $this->document->addStyle('catalog/view/javascript/jquery/colorbox/colorbox.css');

        $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('text_account'),
            'href' => $this->url->link('account/account', '', 'SSL'),
            'separator' => $this->language->get('text_separator')
        );

        $url = '';

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

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

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

        $this->data['back'] = $this->url->link('account/account', '', 'SSL');
        $this->data['new_devolution'] = $this->url->link('account/return/insert', '', 'SSL');

        $this->load->model('account/return');

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

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

        $return_total = $this->model_account_return->getTotalReturns();

        $results = $this->model_account_return->getReturns(($page - 1) * 10, 10);

        foreach ($results as $result) {
            $this->data['returns'][] = array(
                'return_id' => $result['return_id'],
                'order_id' => $result['order_id'],
                'name' => $result['firstname'] . ' ' . $result['lastname'],
                'status' => $result['status'],
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'href' => $this->url->link('account/return/info', 'return_id=' . $result['return_id'] . $url, 'SSL')
            );
        }

        $pagination = new Pagination();
        $pagination->total = $return_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_catalog_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('account/return', 'page={page}', 'SSL');

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

        $this->data['continue'] = $this->url->link('account/account', '', 'SSL');

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

        $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->document->addScript([
            'catalog/view/theme/vista/public/js/account/return_list.js',
        ]);


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

    public function info()
    {
        $language = $this->language->load('account/return');
        $this->data = array_merge($this->data, $language);

        $this->loadscripts();

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

        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = $this->url->link('account/return/info', 'return_id=' . $return_id, 'SSL');

            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

        $this->load->model('account/return');

        $return_info = $this->model_account_return->getReturn($return_id);

        if ($return_info) {
            $this->document->setTitle($this->language->get('text_return'));

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

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

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

            $url = '';

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

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

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_return'),
                'href' => $this->url->link('account/return/info', 'return_id=' . $this->request->get['return_id'] . $url, 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

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

            $this->data['heading_title'] = $this->language->get('text_return');
            $this->data['back'] = $this->url->link('account/return', '', 'SSL');
            $this->data['return_id'] = $return_info['return_id'];
            $this->data['order_id'] = $return_info['order_id'];
            $this->data['date_ordered'] = date($this->language->get('date_format_short'), strtotime($return_info['date_ordered']));
            $this->data['date_added'] = date($this->language->get('date_format_short'), strtotime($return_info['date_added']));
            $this->data['firstname'] = $return_info['firstname'];
            $this->data['lastname'] = $return_info['lastname'];
            $this->data['email'] = $return_info['email'];
            $this->data['telephone'] = $return_info['telephone'];
            $this->data['product'] = $return_info['product'];
            $this->data['model'] = $return_info['model'];
            $this->data['quantity'] = $return_info['quantity'];
            $this->data['reason'] = $return_info['reason'];
            $this->data['opened'] = $return_info['opened'] ? $this->language->get('text_yes') : $this->language->get('text_no');
            $this->data['comment'] = nl2br($return_info['comment']);
            $this->data['action'] = $return_info['action'];

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

            $results = $this->model_account_return->getReturnHistories($this->request->get['return_id']);

            foreach ($results as $result) {
                $this->data['histories'][] = array(
                    'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                    'status' => $result['status'],
                    'comment' => nl2br($result['comment'])
                );
            }

            $this->data['continue'] = $this->url->link('account/return', $url, 'SSL');

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

            $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());
        } else {
            $this->document->setTitle($this->language->get('text_return'));

            $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('text_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('account/return', '', 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

            $url = '';

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

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_return'),
                'href' => $this->url->link('account/return/info', 'return_id=' . $return_id . $url, 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

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

            $this->data['heading_title'] = $this->language->get('text_return');
            $this->data['text_error'] = $this->language->get('text_error');
            $this->data['button_continue'] = $this->language->get('button_continue');
            $this->data['continue'] = $this->url->link('account/return', '', 'SSL');

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

            $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->document->addScript([
                'catalog/view/theme/vista/public/js/account/return_info.js',
            ]);


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

    public function insert()
    {

        $this->app();

        $this->loadscripts();

        $language = $this->language->load('account/return');
        $this->data = array_merge($this->data, $language);

        $this->document->addScript([
            'catalog/view/theme/vista/public/js/account/return_form.js',
        ]);

        $this->data['languageForJS'] = array(
            'account/return' => $language
        );

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

            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

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

        $this->document->addTypesForJs(array(
            Type_PedidoStatus::getTypeForJs(),
        ));

        $this->load->model('localisation/return_reason');
        $this->load->model('catalog/information');
        $this->load->model('catalog/product');
        $this->load->model('account/order');
        $this->load->dmodel('catalog/product');
        $this->load->dmodel('account/order');

        $this->data['return_reasons'] = $this->model_localisation_return_reason->getReturnReasons();

        //aqui ele pega o id do pedido se vem da url ou se vem do POST (nao sei se vai ser assim 4eva)
        if (isset($this->request->get['order_id'])) {
            $order_info = $this->model_account_order->getOrder($this->request->get['order_id']);
        } elseif (($this->request->server['REQUEST_METHOD'] == 'POST') && isset($this->request->post['order_id'])) {
            $order_info = $this->model_account_order->getOrder($this->request->post['order_id']);
        }

        //Aqui ele pega os dois ultimos pedidos do cliente
        $filters = array(
            'not_origem_pedido'      => Type_OrigemSistema::Tp_Marketplace,
            'not_status_futuraserver' => Type_PedidoStatus::TpPSt_Cancelado,
        );
        $last_five_orders = $this->model_account_order->getOrders(0,2, $filters);
        foreach ($last_five_orders as $last_order){

            $last_order_products = $this->dmodel_account_order->getOrderProducts($last_order['order_id'], true);
            $last_order_products_vouchers = $this->model_account_order->getTotalOrderVouchersByOrderId($last_order['order_id']);
            $last_order_products_count = count($last_order_products);

            $aux = null;
            $images = [];
            foreach ($last_order_products as $key => $product){
                $aux = $this->handleProductImage($product);
                $last_order_products[$key]['thumb'] = $aux;
                $images[] = $aux;

                $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
                switch ($type) {
                    case Type_ListCodProduct::Tp_CodReferencia:
                        $modelValue = $product['model'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdEcommerce:
                        $modelValue = $product['product_id'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdFuturaServer:
                        $modelValue = $product['id_futura'];
                        break;
                    case Type_ListCodProduct::Tp_CodBarras:
                        $modelValue = $product['codigo_barra'];
                        break;
                    default:
                        $modelValue = $product['model'];
                }

                $last_order_products[$key]['model_value_on_screen'] = $modelValue;
            }

            $this->data['last_orders'][] = [
                'order_id' => $last_order['order_id'],
                'products' => $last_order_products,
                'images' => array_slice($images, 0, 3),
                'products_count' => (($last_order_products_count + $last_order_products_vouchers) - count(array_slice($images, 0, 3)))
            ];
        }

        //Se o cliente selecionou um produto e deu enviar Devolucao ele vai pegar aqui o ID
        if (isset($this->request->post['product_radio_id'])){
            if (!is_null($this->request->post['product_radio_id'])){
                $this->data['product_id'] = $this->request->post['product_radio_id'];

                if (isset($this->request->post['quantity_'.$this->request->post['product_radio_id']])) {
                    $this->data['quantity'] = $this->request->post['quantity_'.$this->request->post['product_radio_id']];
                } else {
                    $this->data['quantity'] = 1;
                }

            }
        }

        //se ele selecionou fazer a devolucao da tela de pedidos ele pega pelo get da url senao ele pega as infos
        // pela data que vem teoricamente da selecao tratada no bloco acima
        if (isset($this->request->get['product_id'])) {
            $product_info = $this->model_catalog_product->getProductReturn($this->request->get['product_id']);
            $this->data['product_id'] = $this->request->get['product_id'];
        } elseif (isset($this->data['product_id'])){
            $product_info = $this->model_catalog_product->getProductReturn($this->data['product_id']);
        }

        if (isset($this->request->post['order_id'])) {
            $this->data['order_id'] = $this->request->post['order_id'];
        } elseif (!empty($order_info)) {
            $this->data['order_id'] = $order_info['order_id'];
        } else {
            $this->data['order_id'] = '';
        }

        if (isset($this->request->post['product'])) {
            $this->data['product'] = $this->request->post['product'];
        } elseif (!empty($product_info)) {
            $this->data['product'] = $product_info['name'];
        } else {
            $this->data['product'] = '';
        }

        if (!empty($product_info)) {
            $this->data['model'] = strtoupper($product_info['model']);
        } else {
            $this->data['model'] = '';
        }

        //Informacoes do cliente logado sao passadas aqui, mas tenta pegar do pedido antes.
        if (!empty($order_info)) {
            $this->data['firstname'] = $order_info['firstname'];
        } else {
            $this->data['firstname'] = $this->customer->getFirstName();
        }

        if (!empty($order_info)) {
            $this->data['lastname'] = $order_info['lastname'];
        } else {
            $this->data['lastname'] = $this->customer->getLastName();
        }

        if (!empty($order_info)) {
            $this->data['email'] = $order_info['email'];
        } else {
            $this->data['email'] = $this->customer->getEmail();
        }

        if (!empty($order_info)) {
            $this->data['telephone'] = $this->setPhoneMask($order_info['telephone']);
        } else {
            $this->data['telephone'] = $this->setPhoneMask($this->customer->getTelephone());
        }

        if (!empty($order_info)) {
            $this->data['date_ordered'] = implode("/", array_reverse(explode("-", date('Y-m-d', strtotime($order_info['date_added'])))));
        } else {
            $this->data['date_ordered'] = '';
        }

        if (isset($this->request->post['opened'])) {
            $this->data['opened'] = $this->request->post['opened'];
        } else {
            $this->data['opened'] = false;
        }

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

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

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

        if ($this->config->get('config_return_id')) {

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_return_id'));

            if ($information_info) {
                $this->data['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information', 'information_id=' . $this->config->get('config_return_id'), 'SSL'), $information_info['title'], $information_info['title']);
                $this->data['agree_link'] = $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_return_id'), 'SSL');
            } else {
                $this->data['text_agree'] = '';
            }

        } else {
            $this->data['text_agree'] = '';
        }

        if (isset($this->request->post['agree'])) {
            $this->data['agree'] = $this->request->post['agree'];
        } else {
            $this->data['agree'] = false;
        }


        $this->load->model('account/return');
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {

            $this->model_account_return->addReturn($this->data);

            $this->redirect($this->url->link('account/return/success', '', 'SSL'));
        }

        $this->data['site_key'] = $this->config->get('google_recaptcha_site_key');
        $this->data['google_captcha'] = ($this->data['site_key'] && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status')) ? 1 : 0;

        $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('text_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('account/return/insert', '', 'SSL'),
            'separator' => $this->language->get('text_separator')
        );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $this->data['url_search_order'] = $this->url->link('account/return/searchOrders', '', 'SSL');

        $this->data['action'] = $this->url->link('account/return/insert', '', 'SSL');

        $this->data['back'] = $this->url->link('account/return', '', 'SSL');

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

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

    public function setPhoneMask($phone){
        if (strlen($phone) == 10){
            $phone_aux = '(' . substr($phone,0,2) . ') ' . substr($phone,2,4) . '-' . substr($phone,6,4) ;
        } elseif (strlen($phone) <= 11) {
            $phone_aux = '(' . substr($phone,0,2) . ') ' . substr($phone,2,5) . '-' . substr($phone,7,4) ;
        } else {
            $phone_aux = $phone;
        }

        return $phone_aux;
    }

    public function handleProductImage($product){
        $this->load->dmodel('tool/image');

        if ($product['image']) {
            $image = $this->dmodel_tool_image->resizeProductImageWebp(
                $product['image'],
                Type_MiniatureMedium::Tp_width,
                Type_MiniatureMedium::Tp_height
            );

            if (isset($product['original_image']) && is_null($image)) {
                $image = $this->dmodel_tool_image->resizeProductImageWebp(
                    $product['original_image'],
                    Type_MiniatureMedium::Tp_width,
                    Type_MiniatureMedium::Tp_height
                );
            }


            if(!is_null($image)) {
                $image = array_map(function($array) use ($product){

                    $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();

                    return $array.'?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                }, $image);
            } else {
                $image = $this->dmodel_tool_image->resizeWebp(
                    'data/sem-imagem.png',
                    Type_MiniatureMedium::Tp_width,
                    Type_MiniatureMedium::Tp_height
                );
            }
        } else {
            $image = $this->dmodel_tool_image->resizeWebp(
                'data/sem-imagem.png',
                Type_MiniatureMedium::Tp_width,
                Type_MiniatureMedium::Tp_height
            );
        }

        return $image;
    }

    public function searchOrders(){
        $this->load->model('account/order');
        $this->load->dmodel('account/order');

        $searchValue = $this->request->get['search'];
        $order = $this->model_account_order->getOrder($searchValue);


        if (isset($order)){
            $order_products = $this->dmodel_account_order->getOrderProducts($searchValue);
            $order_products_vouchers = $this->model_account_order->getTotalOrderVouchersByOrderId($searchValue);
            $order_products_count = count($order_products);

            $listProducts = [];

            $aux = null;
            $images = [];
            $controlKit = array(); //Como id do kit está no item, controla para não gerar duplicidades;
            foreach ($order_products as $key => $product) {
                if (in_array($product['product_kit_id'], $controlKit)) {
                    continue;
                }

                $currentProduct = $product;

                if ($currentProduct['product_kit_id']) {
                    $currentProduct = $this->dmodel_account_order->getOrdertKit($searchValue, $product['product_kit_id']);
                    $controlKit[] = $product['product_kit_id'];
                }

                $aux = $this->handleProductImage($currentProduct);
                $currentProduct['thumb'] = $aux;
                $images[] = $aux;

                $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
                switch ($type) {
                    case Type_ListCodProduct::Tp_CodReferencia:
                        $modelValue = $product['model'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdEcommerce:
                        $modelValue = $product['product_id'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdFuturaServer:
                        $modelValue = $product['id_futura'];
                        break;
                    case Type_ListCodProduct::Tp_CodBarras:
                        $modelValue = $product['codigo_barra'];
                        break;
                    default:
                        $modelValue = $product['model'];
                }

                $currentProduct['model_value_on_screen'] = $modelValue;

                $listProducts[] = $currentProduct;
            }
        }

        $jsonReturn = [
            'order' => $order,
            'orderProducts' => $listProducts,
            'images' => array_slice($images, 0, 3),
            'products_count' => (($order_products_count + $order_products_vouchers) - count(array_slice($images, 0, 3)))
        ];

        $this->response->setOutputJson($jsonReturn);
    }

    public function success()
    {
        $language = $this->language->load('account/return');
        $this->data = array_merge($this->data, $language);

        $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('account/return', '', 'SSL'),
            'separator' => $this->language->get('text_separator')
        );

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

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

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/success.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/common/success.tpl';
        } else {
            $this->template = 'default/template/common/success.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('common/success'));
    }

    //alguns pegam a validaçao pelo "$This->data" por conta de nao ter os campos na tela, sao passados direto
    protected function validate()
    {
        if (!$this->request->post['order_id']) {
            $this->error['order_id'] = $this->language->get('error_order_id');
        }

        if ((utf8_strlen($this->data['firstname']) < 1) || (utf8_strlen($this->data['firstname']) > 32)) {
            $this->error['firstname'] = $this->language->get('error_firstname');
        }

        if ((utf8_strlen($this->data['lastname']) < 1) || (utf8_strlen($this->data['lastname']) > 32)) {
            $this->error['lastname'] = $this->language->get('error_lastname');
        }

        if ((utf8_strlen($this->data['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->data['email']) || !filter_var($this->data['email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->data['email'])) {
            $this->error['email'] = $this->language->get('error_email');
        }

        if (isset($this->data['product_id'])){
            if (isset($this->data['quantity'])) {
                $quantity = $this->data['quantity'];
                $max_quantity = 0;
                $order_products = $this->dmodel_account_order->getOrderProducts($this->request->post['order_id']);

                $listProducts = $order_products;
                $controlKit = array(); //Como id do kit está no item, controla para não gerar duplicidades;
                foreach ($order_products as $key => $product) {
                    if (in_array($product['product_kit_id'], $controlKit)) {
                        continue;
                    }

                    if ($product['product_kit_id']) {
                        $productKit = $this->dmodel_account_order->getOrdertKit($this->request->post['order_id'], $product['product_kit_id']);
                        $productKit['product_id'] = $productKit['id'];
                        $listProducts[] = $productKit;
                        $controlKit[] = $product['product_kit_id'];
                    }
                }

                foreach ($listProducts as $product){
                    if ($product['product_id'] == $this->data['product_id']){
                        $max_quantity = $product['quantity'];
                        break;
                    }
                }

                if ($quantity > $max_quantity){
                    $this->error['quantity'] = $this->language->get('error_max_quantity');
                }

                if ($quantity <= 0){
                    $this->error['quantity'] = $this->language->get('error_min_quantity');
                }
            }
        } else {
            $this->error['product_not_selected'] = $this->language->get('error_product_not_selected');
        }

        if ((utf8_strlen($this->data['model']) < 1) || (utf8_strlen($this->data['model']) > 64)) {
            $this->error['model'] = $this->language->get('error_model');
        }

        if (empty($this->request->post['return_reason_id'])) {
            $this->error['reason'] = $this->language->get('error_reason');
        }

        if ($this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status')) {
            $recaptcha = $this->ftrgeralregistry->validateGoogleCaptha($this->config->get('google_recaptcha_secret_key'), isset($this->request->post['g-recaptcha-response']) ? $this->request->post['g-recaptcha-response'] : '', $this->request->server['REMOTE_ADDR']);

            if (!$recaptcha["success"]) {
                $this->error['google_captcha'] = 'Erro de validação no reCaptcha! Efetue a validação para continuar';
            }
        }

        if (!$this->config->get('google_recaptcha_site_key') || !$this->config->get('google_recaptcha_secret_key') || !$this->config->get('wg24_google_recaptcha_status')) {
            if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
                $this->error['captcha'] = $this->language->get('error_captcha');
            }
        }

        if ($this->config->get('config_return_id')) {
            $this->load->model('catalog/information');

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_return_id'));

            if ($information_info && !isset($this->request->post['agree'])) {
                $this->error['agree'] = sprintf($this->language->get('error_agree'), $information_info['title']);
            }
        }

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

    public function captcha()
    {
        $this->load->library('captcha');

        $captcha = new Captcha();

        $this->session->data['captcha'] = $captcha->getCode();

        $captcha->showImage();
    }

    public function loadscripts()
    {

        // Adiciona o Plugin que mostra o qualidade da senha - por Henrique R. Pohl
        $this->document->addScript('catalog/view/theme/vista/public/js/medidor-de-senha.js');
    }


    public function app()
    {
        if ($this->ftrgeralregistry->isApp()) {
            $this->document->addScriptApp(array(
                'catalog/view/theme/appmobile/public/js/mainheaderform.js',
                'public/js/account/return_form.js'
            ));

            $languageApp = $this->language->load('account/return');
            $this->data['languageApp'] = json_encode($languageApp);
        }
    }

}
