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

class ControllerFidelityIndication extends ControllerBaseBase {

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

    public function index(){
        // Scripts
        $this->document->addScript(array(
            'catalog/view/theme/vista/js/modal-futura.js',
            'catalog/view/theme/vista/js/page.indication.js',
            'catalog/view/theme/vista/public/js/fidelity/indication.js',
            'public/js/menuAccount.js',
        ));

        $this->document->addScriptApp(array(
            'catalog/view/javascript/copyContent.js',
            'catalog/view/theme/vista/js/page.indication.js'
        ));

        // Loads
        $this->load->dmodel('layout_personalizado/custom_layout');

        // Language
        $language = $this->language->load('fidelity/indication');
        $this->data = array_merge($this->data, $language);

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

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

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

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_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('fidelity/indication'),
            'separator' => $this->language->get('text_separator'));

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

        // Layout
        $link = $this->url->link('account/register', 'indication_customer_id=' . $this->customer->getId());
        $layout = $this->dmodel_layout_personalizado_custom_layout->getContents(Type_LayoutPersonalizado::Tp_LayoutIndication);
        if (isset($layout[0]['descricao']) && isset($layout[0]['conteudo_layout']) ) {

            $layout_conteudo = html_entity_decode($layout[0]['conteudo_layout']);

            $find = array('{{ cli_nome }}', '{{ cli_email }}', '{{ loj_indication_link }}', '{{ loj_indication_button }}');
            if($this->ftrgeralregistry->isApp()) {
                $loj_indication_link   = '<span class="ftr-text--s ftr-block ftr-text--grey js-copy-content">' . $link . '</span>' .
                    '<span class="js-copy-action text-medium rel" style="cursor: pointer;"><i class="material-icons">&#xe14d;</i></span>';
                // No app o botao enviar email ficara fixo por ultimo por questao de manter um bom layout, e o funcionamento do swipe-content
                $loj_indication_button = '';
            } else {
                $loj_indication_link   = '<span class="text-small text-dark visible-inline-block top-padding-small js-copy-content">' . $link . '</span>' .
                    '<span class="js-copy-action text-medium rel" style="cursor: pointer;"><i class="far fa-clone left-margin-small" aria-hidden="true" title="Copiar"></i></span>';
                $loj_indication_button = '<a href="' . $this->url->link('fidelity/indication/sendEmail', "", 'SSL') . '"'
                    . 'class="btn-default btn-large js-send-email">' . $language["text_email"] . '</a>';
            }
            $replace = array(
                'cli_nome' => $this->customer->getFirstName().' '.$this->customer->getLastName(),
                'cli_email' => $this->customer->getEmail(),
                'loj_indication_link' => $loj_indication_link,
                'loj_indication_button' => $loj_indication_button
            );

            $layout_conteudo = trim(str_replace($find, $replace, $layout_conteudo));

            $this->data['heading_title'] = $layout[0]['descricao'];
            $this->data['layout'] = $layout_conteudo;
        }

        // Children
        $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');
        }

        // Response
        $this->response->setOutput($this->render('fidelity/indication'));

    }

    public function sendEmailModal()
    {
        $language = $this->language->load('fidelity/indication');
        $this->data = array_merge($this->data, $language);
        $this->load->helper('ftr_geral');

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

        $this->template = 'fidelity/email.twig';

        $this->children = array();
        $this->response->setOutput($this->render('fidelity/email'));
    }

    public function sendEmail()
    {
        $language = $this->language->load('fidelity/indication');
        $this->data = array_merge($this->data, $language);
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');
        $json = array ();

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

            $email_enderecos = str_replace("\n","", $this->request->post['email_enderecos']);
            $email_enderecos    =  explode(";", $email_enderecos);

            foreach ($email_enderecos 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_invalido'] = sprintf($language["text_email_invalid"], $value);
                        break;
                    }
                }
            }

            if (!isset($json['error'])) {
                $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_config'] = sprintf($language["text_email_config"], $this->url->link('setting/setting', 'token=' . $this->session->data['token'], 'SSL'));
                } else {
                    $subject = 'Indicação';
                    $baseLink = $this->url->link('account/register', 'indication_customer_id=' . $this->customer->getId());
                    $indicador = $this->customer->getFirstName() . ' ' . $this->customer->getLastName();

                    // Conteudo
                    $server = $this->url->link('', '', 'SSL', false);

                    if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {
                        $logo = $server . 'image/' . $this->config->get('config_logo');
                    } else {
                        $logo = '';
                    }

                    $logoEmail = ($logo) ? '<img src="' . $logo . '" alt="logo" style="max-width: 100%;">' : '';

                    $conteudo = '
                        <div style="width: 600px; margin: 0 auto">
                            <p style="margin-top: 25px; margin-bottom: 15px">' . $logoEmail . '</p>

                            <p style="font: normal bold 30px Arial,Helvetica,sans-serif; color: #000; margin: 0">Olá,</p>

                            <p style="font: normal normal 16px Arial,Helvetica,sans-serif; color: #666; margin-top: 0; margin-bottom: 15px">Você recebeu uma indicação de ' . $indicador . ' para se cadastrar em nossa loja.</p>

                            <p><a style="display: inline-block; padding: 15px 20px; border-radius: 4px; text-transform: uppercase; background: #ffffff; color: #15156e; text-decoration: none; font: normal normal 14px Arial,Helvetica,sans-serif; margin-bottom: 10px" href="' . $baseLink . '" target="_blank" rel="noreferrer">Cadastre-se</a></p>

                            <p style="font: normal normal 12px Arial,Helvetica,sans-serif; color: #666; margin-bottom: 40px">Não conseguiu acessar pelo botão? Copie e cole o link abaixo no seu navegador. <a href="' . $baseLink . '">' . $baseLink . '</a></p>

                            <p style="font: normal normal 16px Arial,Helvetica,sans-serif; color: #000">Atenciosamente,<br>
                            <span style="font-weight: bold">' . $this->config->get('config_name') . '</span></p>
                        </div>';

                    $this->EnviaEmail($email_enderecos, $subject, $conteudo, '');
                    $json['success'] = $language["text_email_success"];
                }
            }
        }else{
            $json['error']['email_branco'] = $language["text_email_blank"];
        }
        $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();
            }
        }
    }
}
