<?php

$loader = $this->registry->get('load');
$loader->controller('base/base');
class ControllerAccountReturn extends ControllerBaseBase
{
    private $error = array();
    protected $referencePathFile = 'account/return';

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

        $return_total = 0;

        if ($this->ftrgeralregistry->isApp()) {
            $this->data['returns'] = array();

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

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

            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')
                );
            }
        } else {
            $returns = $this->model_account_return->getHistoryReturn();

            foreach ($returns as $index => $return) {
                foreach ($return as $key => $item) {
                    $returns[$index][$key]['image'] = $this->handleProductImage($item);
                    $returns[$index][$key]['href'] = $this->url->link('product/product', 'product_id=' . $item['product_id'] . $url, 'SSL');
                    $returns[$index][$key]['date_added'] = date('d/m/Y', strtotime($item['date_added']));
                    $returns[$index][$key]['date_ordered'] = date('d/m/Y', strtotime($item['date_ordered']));
                    $returns[$index][$key]['return_reason_id'] = TypeDevolutionReason::getNickFromValue($item['return_reason_id']);
                    $returns[$index][$key]['return_status_id'] = TypeDevolutionStatus::getNickFromValue($item['return_status_id']);
                }
            }

            $this->dataVue['returns'] = $returns;

            $return_total = count($returns);

            if (count($returns) > 0) {
                $this->data['show_return'] = true;
            } else {
                $this->data['show_return'] = false;
            }
        }

        $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',
            'public/js/menuAccount.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',
            'public/js/menuAccount.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->dataVue['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);

        $last_five_orders = $this->model_account_order->getOrders();

        if (count($last_five_orders) > 0) {
            $this->data['show_last_orders'] = true;

            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->dataVue['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'])) {
                foreach ($this->request->post['product_radio_id'] as $key => $productId) {
                    $this->data['product_id'][$key] = $productId;
                    $this->dataVue['product_id'][$key] = $productId;
                }
            }
        }


        if (count($last_five_orders) == 0) {
            $this->data['show_last_orders'] = false;
        }

        if (isset($this->request->post['quantity'])) {
            if (!is_null($this->request->post['quantity'])) {
                foreach ($this->request->post['quantity'] as $key => $quantity) {
                    $this->data['quantity'][$key] = $quantity;
                    $this->dataVue['quantity'][$key] = $quantity;
                }
            }
        }


        if (isset($this->request->post['showKit'])) {
            if (!is_null($this->request->post['showKit'])) {
                foreach ($this->request->post['showKit'] as $key => $showKit) {
                    $this->data['showKit'][$key] = $showKit;
                    $this->dataVue['showKit'][$key] = $showKit;
                }
            }
        } else {
            $this->data['showKit'] = [];
            $this->dataVue['showKit'] = [];
        }

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


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

        //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'])) {
            foreach ($this->data['product_id'] as $key => $product) {
                if (is_array($product)) {
                    foreach ($product as $item) {
                        $product_info[$key][] = $this->model_catalog_product->getProductReturn($item);
                    }
                } else {
                    $product_info[$key] = $this->model_catalog_product->getProductReturn($product);
                }
            }
        }

        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)) {
            foreach ($product_info as $index => $product) {
                if (isset($product['name'])) {
                    $this->data['product'][$index] = $product['name'];
                } else {
                    foreach ($product as $key => $item) {
                        $this->data['product'][$index][$key] = $item['name'];
                    }
                }
            }
        } else {
            $this->data['product'] = [];
        }


        if (!empty($product_info)) {
            foreach ($product_info as $index => $product) {
                if (isset($product['model'])) {
                    $this->data['model'][$index] = strtoupper($product['model']);
                } else {
                    foreach ($product as $key => $item) {
                        $this->data['model'][$index][$key] = $item['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['return_reason_id'])) {
            $this->data['return_reason_id'] = $this->request->post['return_reason_id'];
            $this->dataVue['return_reason_id'] = $this->request->post['return_reason_id'];
        } else {
            $this->data['return_reason_id'] = '';
            $this->dataVue['return_reason_id'] = '';
        }

        if (isset($this->request->post['comment'])) {
            $this->data['comment'] = $this->request->post['comment'];
            $this->dataVue['comment'] = $this->request->post['comment'];
        } else {
            $this->data['comment'] = '';
            $this->dataVue['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->dataVue['agree'] = $this->request->post['agree'];
        } else {
            $this->dataVue['agree'] = false;
        }

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $product = [];
            $productIndex = [];

            if (isset($this->data['product_id'])) {
                $productIndex = array_keys($this->data['product_id']);
            }

            foreach ($productIndex as $key) {
                $product[$key]['product_id'] = $this->data['product_id'][$key];
                $product[$key]['quantity'] = $this->data['quantity'][$key];
                $product[$key]['product'] = $this->data['product'][$key];
                $product[$key]['opened'] = $this->data['opened'][$key];
                $product[$key]['model'] = $this->data['model'][$key];
                $product[$key]['order_id'] = $this->data['order_id'];
                $product[$key]['firstname'] = $this->data['firstname'];
                $product[$key]['lastname'] = $this->data['lastname'];
                $product[$key]['email'] = $this->data['email'];
                $product[$key]['telephone'] = $this->data['telephone'];
                $product[$key]['date_ordered'] = $this->data['date_ordered'];
                $product[$key]['return_reason_id'] = $this->data['return_reason_id'];
                $product[$key]['comment'] = $this->data['comment'];
                $product[$key]['date_added'] = date('Y-m-d h:i:s', time());
            }


            foreach ($product as $key => $item) {
                if (is_array($item['product_id'])) {
                    $data = [];

                    $index = array_keys($item['product_id']);

                    foreach ($index as $key => $value) {

                        $product_id = $item['product_id'][$key];
                        $data['product_id'] = $product_id;
                        $data['quantity'] = $item['quantity'][$product_id];
                        $data['product'] = $item['product'][$key];
                        $data['opened'] = $item['opened'][$product_id];
                        $data['model'] = $item['model'][$key];
                        $data['order_id'] = $item['order_id'];
                        $data['firstname'] = $item['firstname'];
                        $data['lastname'] = $item['lastname'];
                        $data['email'] = $item['email'];
                        $data['telephone'] = $item['telephone'];
                        $data['date_ordered'] = $item['date_ordered'];
                        $data['return_reason_id'] = $item['return_reason_id'];
                        $data['comment'] = $item['comment'];
                        $data['date_added'] = date('Y-m-d h:i:s', time());

                        $this->model_account_return->addReturn($data);
                    }
                } else {
                    $item['opened'] = $item['opened'][$item['product_id']];
                    $item['quantity'] = $item['quantity'][$item['product_id']];
                    $this->model_account_return->addReturn($item);
                }
            }

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

        $this->dataVue['site_key'] = $this->config->get('google_recaptcha_site_key');
        $this->dataVue['google_captcha'] = ($this->dataVue['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->dataVue['error']['error_warning'] = $this->error['warning'];
        } else {
            $this->dataVue['error']['error_warning'] = '';
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $this->dataVue['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);
            $this->response->setOutputJson($order_products);
            $order_products_vouchers = $this->model_account_order->getTotalOrderVouchersByOrderId($searchValue);
            $order_products_count = count($order_products);

            $products = [];

            $controlUniqueProduct = array();

            foreach ($order_products as $index => $product) {
                if (in_array($product['product_id'], $controlUniqueProduct)) {
                    $key = array_search($product['product_id'], $controlUniqueProduct);
                    $products[$key]['quantity'] = $products[$key]['quantity'] + $product['quantity'];
                    continue;
                }

                $products[] = $product;
                $controlUniqueProduct[] = $product['product_id'];
            }

            $listProducts = [];

            $aux = null;
            $images = [];
            $controlKit = array(); //Como id do kit está no item, controla para não gerar duplicidades;

            foreach ($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'];
                $product_id = $this->data['product_id'];
                $order_products = $this->dmodel_account_order->getOrderProducts($this->request->post['order_id']);

                $products = [];

                $controlUniqueProduct = array();

                foreach ($order_products as $index => $product) {
                    if (in_array($product['product_id'], $controlUniqueProduct)) {
                        $key = array_search($product['product_id'], $controlUniqueProduct);
                        $products[$key]['quantity'] = $products[$key]['quantity'] + $product['quantity'];
                        continue;
                    }

                    $products[] = $product;
                    $controlUniqueProduct[] = $product['product_id'];
                }


                $listProducts = $products;
                $controlKit = array(); //Como id do kit está no item, controla para não gerar duplicidades;

                foreach ($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 $key => $product) {
                    foreach ($product_id as $index => $item) {
                        if (is_array($item)) {
                            foreach ($item as $i => $value) {
                                if ($product['product_id'] == $value) {
                                    if ($quantity[$index][$value] > $product['quantity']) {
                                        $this->error['quantity'][$index][$value] = $this->language->get('error_max_quantity');
                                    } else if ($quantity[$index][$value] <= 0) {
                                        $this->error['quantity'][$index][$value] = $this->language->get('error_min_quantity');
                                    }
                                }
                            }
                        } else {
                            if ($product['product_id'] == $item) {
                                if ($quantity[$index][$product['product_id']] > $product['quantity']) {
                                    $this->error['quantity'][$index][$product['product_id']] = $this->language->get('error_max_quantity');
                                } else if ($quantity[$index][$product['product_id']] <= 0) {
                                    $this->error['quantity'][$index][$product['product_id']] = $this->language->get('error_min_quantity');
                                }
                            }
                        }
                    }
                }
            }
        } else {
            $this->error['product_not_selected'] = $this->language->get('error_product_not_selected');
        }

        foreach ($this->data['model'] as $key => $model) {
            if (is_array($model)) {
                foreach ($model as $index => $item) {
                    if ((utf8_strlen($item) < 1) || (utf8_strlen($item) > 64)) {
                        $this->error['model'][$key][$index] = $this->language->get('error_model');
                    }
                }
            } else {
                if ((utf8_strlen($model) < 1) || (utf8_strlen($model) > 64)) {
                    $this->error['model'][$key] = $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);
        }
    }

}