<?php

class ControllerDesignLayoutPersonalizado extends Controller
{
    private $error = array();

    public function index()
    {
        $language = $this->language->load('design/layout_personalizado');
        $this->data = array_merge($this->data, $language);

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

        $this->load->model('design/layout_personalizado');

        $this->getList();
    }

    public function insert()
    {
        $this->language->load('design/layout_personalizado');

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

        $this->load->model('design/layout_personalizado');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
            $this->model_design_layout_personalizado->addLayoutPersonalizado($this->request->post);

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

            $url = '';

            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('design/layout_personalizado', 'token=' . $this->session->data['token'] . $url, 'SSL'));
        }

        $this->getForm();
    }

    public function update()
    {
        $this->language->load('design/layout_personalizado');
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        $this->document->addScript([
            "view/javascript/ckeditor/ckeditor.js",
            "admin/public/js/design/layout_personalizado_form.js"
        ]);

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

        $this->load->model('design/layout_personalizado');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
            if (isset($this->request->post['conteudo_layout']) && $this->request->post['tipo_layout'] == Type_LayoutPersonalizado::Tp_LayoutEmailMercadoLivre) {
                $this->request->post['conteudo_layout'] = ftr_geral::formatText($this->request->post['conteudo_layout']);
            }

            $this->model_design_layout_personalizado->editLayoutPersonalizado($this->request->get['design_layout_personalizado_id'], $this->request->post);

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

            $url = '';

            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('design/layout_personalizado', 'token=' . $this->session->data['token'] . $url, 'SSL'));
        }

        $this->getForm();
    }

    public function delete()
    {
        $language = $this->language->load('design/layout_personalizado');
        $this->data = array_merge($this->data, $language);


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

        $this->load->model('design/layout_personalizado');

        if (isset($this->request->post['selected']) && $this->validateDelete()) {
            foreach ($this->request->post['selected'] as $design_layout_personalizado_id) {
                $this->model_design_layout_personalizado->deleteLayoutPersonalizado($design_layout_personalizado_id);
            }

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

            $url = '';

            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('design/layout_personalizado', 'token=' . $this->session->data['token'] . $url, 'SSL'));
        }

        $this->getList();
    }

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

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

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

        $url = '';

        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->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('design/layout_personalizado', 'token=' . $this->session->data['token'] . $url, 'SSL'),
            'separator' => ' :: '
        );

        $this->data['insert'] = $this->url->link('design/layout_personalizado/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
        $this->data['delete'] = $this->url->link('design/layout_personalizado/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

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

        $data = array(
            'sort' => $sort,
            'order' => $order,
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit')
        );

        $email_total = $this->model_design_layout_personalizado->getTotalLayoutPersonalizados();

        $results = $this->model_design_layout_personalizado->getLayoutPersonalizados($data);

        foreach ($results as $result) {
            //verificando se a config de marketplace esta ativa para mostrar coisas referentes a marketplace
            if (!$this->config->get('config_sistema_marketplace') && $result['tipo_layout'] == Type_LayoutPersonalizado::Tp_LayoutEmailMercadoLivre) {
                continue;
            }

            $action = array();
            $action[] = array(
                'text' => $this->language->get('text_edit'),
                'href' => $this->url->link('design/layout_personalizado/update', 'token=' . $this->session->data['token'] . '&design_layout_personalizado_id=' . $result['design_layout_personalizado_id'] . $url, 'SSL')
            );

            $this->data['layouts'][] = array(
                'design_layout_personalizado_id' => $result['design_layout_personalizado_id'],
                'descricao' => Type_LayoutPersonalizado::getNickFromConstValue($result['tipo_layout']),
                'tipo_layout' => $result['tipo_layout'],
                'selected' => isset($this->request->post['selected']) && in_array($result['design_layout_personalizado_id'], $this->request->post['selected']),
                'action' => $action
            );
        }

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

        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 = '';

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

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

        $this->data['sort_descricao'] = $this->url->link('design/layout_personalizado', 'token=' . $this->session->data['token'] . '&sort=descricao' . $url, 'SSL');

        $url = '';

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

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

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

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

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

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

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

    protected function getForm()
    {
        $language = $this->language->load('design/layout_personalizado');
        $this->data = array_merge($this->data, $language);


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

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

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

        $url = '';

        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->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('design/layout_personalizado', 'token=' . $this->session->data['token'] . $url, 'SSL'),
            'separator' => ' :: '
        );

        if (!isset($this->request->get['design_layout_personalizado_id'])) {
            $this->data['action'] = $this->url->link('design/layout_personalizado/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
        } else {
            $this->data['action'] = $this->url->link('design/layout_personalizado/update', 'token=' . $this->session->data['token'] . '&design_layout_personalizado_id=' . $this->request->get['design_layout_personalizado_id'] . $url, 'SSL');
        }

        $this->data['cancel'] = $this->url->link('design/layout_personalizado', 'token=' . $this->session->data['token'] . $url, 'SSL');

        if (isset($this->request->get['design_layout_personalizado_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $layout_info = $this->model_design_layout_personalizado->getLayoutPersonalizado($this->request->get['design_layout_personalizado_id']);
        }

        $this->data['token'] = $this->session->data['token'];

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

        if (isset($this->request->post['tipo_layout'])) {
            $this->data['tipo_layout'] = $this->request->post['tipo_layout'];
        } elseif (!empty($layout_info)) {
            $this->data['tipo_layout'] = $layout_info['tipo_layout'];
        } else {
            $this->data['tipo_layout'] = '';
        }
        $this->data['descricao_layout'] = Type_LayoutPersonalizado::getNickFromConstValue($this->data['tipo_layout']);

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

        $arrayRemoveVarButton = array();

        $this->data['ckeditor_active'] = true;
        $this->data['test_email_active'] = true;
        $this->data['editor_maxlength_active'] = false;
        $this->data['editor_maxlength'] = 0;
        $this->data['editor_description_active'] = false;

        switch ($this->data['tipo_layout']) {
            case Type_LayoutPersonalizado::Tp_LayoutCliente :
                $arrayRemoveVarButton = array(
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojindicationlink),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojindicationbutton)
                );
                $this->data['Type_LayoutPersonalizadoVarButtons'] = array_diff(Type_LayoutPersonalizadoVarButton::getEnumList(), $arrayRemoveVarButton);
                break;
            case Type_LayoutPersonalizado::Tp_LayoutEmailMercadoLivre :
                $arrayRemoveVarButton = array(
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojlogo),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojbotaoacessar),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojindicationlink),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojindicationbutton),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojlink),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink)
                );
                $this->data['Type_LayoutPersonalizadoVarButtons'] = array_diff(Type_LayoutPersonalizadoVarButton::getEnumList(), $arrayRemoveVarButton);
                $this->data['ckeditor_active'] = false;
                $this->data['editor_maxlength_active'] = true;
                $this->data['editor_maxlength'] = 300;
                $this->data['editor_description_active'] = true;
                break;
            case Type_LayoutPersonalizado::Tp_LayoutSuccess :
                $arrayRemoveVarButton = array(
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojlogo),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojbotaoacessar),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojindicationlink),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojindicationbutton)
                );
                $this->data['Type_LayoutPersonalizadoVarButtons'] = array_diff(Type_LayoutPersonalizadoVarButton::getEnumList(), $arrayRemoveVarButton);
                $this->data['ckeditor_active'] = false;
                $this->data['test_email_active'] = false;
                $this->data['entry_descricao'] = $this->language->get('entry_titulo');
                break;
            case Type_LayoutPersonalizado::Tp_LayoutIndication :
                $arrayRemoveVarButton = array(
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojlogo),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojbotaoacessar),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_PedidoID),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojnome),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojlink),
                    Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink)
                );
                $this->data['Type_LayoutPersonalizadoVarButtons'] = array_diff(Type_LayoutPersonalizadoVarButton::getEnumList(), $arrayRemoveVarButton);
                $this->data['ckeditor_active'] = true;
                $this->data['test_email_active'] = false;
                $this->data['entry_descricao'] = $this->language->get('entry_titulo');
                break;
            case Type_LayoutPersonalizado::Tp_LayoutMaintenance :
                $this->data['ckeditor_active'] = true;
                $this->data['test_email_active'] = false;
                $this->data['entry_descricao'] = $this->language->get('entry_titulo');
                break;
            default :
                $this->data['Type_LayoutPersonalizadoVarButtons'] = Type_LayoutPersonalizadoVarButton::getEnumList();
        }


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

        $this->data['languages'] = $this->model_localisation_language->getLanguages();

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

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

    public function emailTeste()
    {

        $json = array();
        $this->language->load('design/layout_personalizado');
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        if (isset($this->request->post['email_teste']) && ($this->request->post['email_teste']) != "") {

            $email_teste = explode(";", $this->request->post['email_teste']);
            $conteudo_layout = html_entity_decode($this->request->post['conteudo_layout']);

            foreach ($email_teste as $key => $value) {
                $value = trim($value);
                if ($value != "") {
                    if ((utf8_strlen($value) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $value) || !filter_var($value, FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $value)) {
                        $json['error']['email_teste'] = sprintf($this->language->get('error_email_teste_invalido'), $value);
                        break;
                    }
                }
            }

            $ConfigEmail = array(
                'config_mail_protocol' => $this->config->get('config_mail_protocol'),
                'config_smtp_host' => $this->config->get('config_smtp_host'),
                'config_smtp_username' => $this->config->get('config_smtp_username'),
                'config_smtp_password' => $this->config->get('config_smtp_password'),
                'config_smtp_port' => $this->config->get('config_smtp_port'),
                'config_smtp_timeout' => $this->config->get('config_smtp_timeout')
            );

            if (count(array_filter($ConfigEmail)) < count($ConfigEmail)) {
                $json['error']['email_teste'] = sprintf($this->language->get('error_email_teste_configuracao'), $this->url->link('setting/setting', 'token=' . $this->session->data['token'], 'SSL'));
            }


            $sql = 'select * from ' . DB_PREFIX . 'customer limit 1';

            $customerinfo = $this->db->query($sql);

            if ($customerinfo->rows) {
                $template = new Template();
                $template->data['content'] = $conteudo_layout;
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Clinome] = $customerinfo->row['firstname'] . ' ' . $customerinfo->row['lastname'];
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Cliemail] = $customerinfo->row['email'];
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Lojnome] = $this->config->get('config_name');
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Lojlink] = $this->linkLoja();
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink] = '<a href="' . $this->urlloja->link('account/register', '', 'SSL') . '">' . $this->urlloja->link('account/register', '', 'SSL') . '</a>';
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Lojbotaoacessar] = '<a style="display: inline-block; padding: 15px 20px; border-radius: 4px; text-transform: uppercase; background: ' . $this->config->get('wg24_mm_bgcol') . '; color: ' . $this->config->get('wg24_menum_lcolor') . '; text-decoration: none; font: normal normal 14px Arial, Helvetica, sans-serif; margin-bottom: 10px;" href="' . $this->urlloja->link('account/register', '', 'SSL') . '">Acessar minha conta</a>';
                $template->data[Type_LayoutPersonalizadoVarButton::Tp_Lojlogo] = $this->logoLoja();

                $subject = sprintf($this->language->get('text_subject'), $template->data[Type_LayoutPersonalizadoVarButton::Tp_Clinome]);

                $html = $this->ftrgeralregistry->twigToString(DIR_TEMPLATE . 'mail/customer_register.twig', $template->data['content'], $template->data);

                $this->EnviaEmail($email_teste, $subject, $html, '');

                $json['success'] = $this->language->get('success_email_teste');
            } else {
                $json['error']['warning'] = $this->language->get('error_email_teste_customer');
            }

        } else {
            $json['error']['email_teste'] = $this->language->get('error_email_teste_branco');
        }
        $this->response->setOutputJson($json);
    }

    protected function EnviaEmail($setTos, $subject, $html, $message)
    {
        $mail = new Mail();
        $mail->protocol = $this->config->get('config_mail_protocol');
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->hostname = $this->config->get('config_smtp_host');
        $mail->username = $this->config->get('config_smtp_username');
        $mail->password = $this->config->get('config_smtp_password');
        $mail->port = $this->config->get('config_smtp_port');
        $mail->timeout = $this->config->get('config_smtp_timeout');
        $mail->setFrom($this->config->get('config_email'));
        $mail->setSender($this->config->get('config_name'));
        $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
        $mail->setHtml($html);
        $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
        foreach ($setTos as $setTo) {
            if ($setTo && preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $setTo)) {
                $mail->setTo($setTo);
                $mail->send();
            }
        }
    }

    protected function linkLoja()
    {

        return $this->urlloja->link('', '', 'SSL', false);;
    }

    protected function logoLoja()
    {
        $server = $this->urlloja->link('', '', 'SSL', false);

        if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {
            $loj_logo = $server . 'image/' . $this->config->get('config_logo');
        } else {
            $loj_logo = '';
        }
        return '<img src="' . $loj_logo . '" alt="logo" style="max-width: 100%;" />';

    }

    protected function validateForm()
    {
        if (!$this->user->hasPermission('modify', 'design/layout_personalizado')) {
            $this->error['warning'] = $this->language->get('text_error_permission');
        }

        if ((utf8_strlen($this->request->post['descricao']) < 3) || (utf8_strlen($this->request->post['descricao']) > 64)) {
            $this->error['descricao'] = $this->language->get('text_error_descricao');
        }

        if (isset($this->request->post['tipo_layout']) && ($this->request->post['tipo_layout'] == Type_LayoutPersonalizado::Tp_LayoutEmailMercadoLivre)) {

            if (isset($this->request->post['conteudo_layout']) and (utf8_strlen($this->request->post['conteudo_layout']) > 0)) {
                $conteudo_layout = $this->request->post['conteudo_layout'];

                $conteudo_layout = str_replace("\r\n", "\n", $conteudo_layout);
                $conteudo_layout = str_replace("\r", "\n", $conteudo_layout);

                if (utf8_strlen($conteudo_layout) > 300) {
                    $this->error['conteudo_layout'] = $this->language->get('text_error_conteudo_layout_email');
                }
            }
        }

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

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

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