<?php

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

    public function index()
    {
        $this->loadscripts();

        $this->language->load('information/contact');

        $this->document->addScriptApp(array(
            'catalog/view/theme/appmobile/public/js/mainheaderform.js',
            'catalog/view/theme/appmobile/js/page.contact.js'
        ));

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

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            try {
                $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->setTo($this->config->get('config_email'));
                $mail->setFrom($this->config->get('config_email'));
                $mail->setSender($this->request->post['name']);
                $mail->setSubject(html_entity_decode(sprintf($this->language->get('email_subject'), $this->request->post['name']), ENT_QUOTES, 'UTF-8'));
                $name = $this->request->post['name'];
                $email = $this->request->post['email'];
                $telephone_form = $this->request->post['telephone_form'];
                $enquiry = $this->request->post['enquiry'];
                $mail->setText(strip_tags(html_entity_decode(chr(13) . "Nome: $name" . chr(13) . "E-Mail: $email" . chr(13) . "Telefone: $telephone_form" . chr(13) . "Mensagem: $enquiry", ENT_QUOTES, 'UTF-8')));
                $mail->send(true);
                $this->redirect($this->url->link('information/contact/success'));
            } catch (Exception $e) {
                $this->error['warning'] = 'Erro ao enviar contato tente novamente mais tarde!';
                if ($this->config->get('config_error_log')) {
                    $this->log->write('Error ao Enviar contato: ' . $e);
                }
            }
        }

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

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

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

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

        $this->data['text_location'] = $this->language->get('text_location');
        $this->data['text_contact'] = $this->language->get('text_contact');
        $this->data['text_address'] = $this->language->get('text_address');
        $this->data['text_telephone'] = $this->language->get('text_telephone');
        $this->data['text_fax'] = $this->language->get('text_fax');
        $this->data['exibe_endereco'] = $this->config->get('wg24_exibe_contact');
        $this->data['config_exibe_map'] = $this->config->get('config_exibe_map');
        $this->data['config_contact_googlemaps'] = $this->config->get('config_contact_googlemaps');
        $this->data['config_contact_googlemaps_decode'] = html_entity_decode($this->config->get('config_contact_googlemaps'));
        $config_telephone = $this->config->get('config_telephone');
        if($config_telephone){
            $config = array();
            foreach (array_reverse($config_telephone) as $telefone){
                if($telefone['display']){
                    $config[$telefone['type']][] = $telefone['numero'];
                }
            }
            $config_telephone = $config;
        }

        $this->data['config_telephone'] = $config_telephone;

        $this->data['entry_name'] = $this->language->get('entry_name');
        $this->data['entry_name_placeholder'] = $this->language->get('entry_name_placeholder');
        $this->data['entry_telephone'] = $this->language->get('entry_telephone');
        $this->data['entry_telephone_form'] = $this->language->get('entry_telephone_form');
        $this->data['entry_telephone_form_placeholder'] = $this->language->get('entry_telephone_form_placeholder');
        $this->data['entry_email'] = $this->language->get('entry_email');
        $this->data['entry_email_placeholder'] = $this->language->get('entry_email_placeholder');
        $this->data['entry_enquiry'] = $this->language->get('entry_enquiry');
        $this->data['entry_enquiry_placeholder'] = $this->language->get('entry_enquiry_placeholder');
        $this->data['entry_captcha'] = $this->language->get('entry_captcha');
        $this->data['entry_captcha_placeholder'] = $this->language->get('entry_captcha_placeholder');

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

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

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

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


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

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

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

        $this->data['action'] = $this->url->link('information/contact');
        $this->data['store'] = $this->config->get('config_name');
        $this->data['address'] = nl2br($this->config->get('config_address'));
        $this->data['telephone'] = $this->config->get('config_telephone');

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

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

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

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

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

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

        $this->children = array(
            'common/breadcrumbs',
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/content_app',
            'common/footer',
            'common/header'
        );

        $this->response->setOutput($this->render('information/contact'));
    }

    public function success()
    {
        $this->language->load('information/contact');

        $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('information/contact'),
            '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'));
    }

    protected function validate()
    {
        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 ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 32)) {
            $this->error['name'] = $this->language->get('error_name');
        }

        // INICIO - Validação de Telefone e Celular - por Henrique R. Pohl
        $obtem_telefone_sem_mascara = preg_replace('/([^0-9])/i', '', $this->request->post['telephone_form']);
        if ((utf8_strlen($obtem_telefone_sem_mascara) > 0) && (utf8_strlen($obtem_telefone_sem_mascara) < 10)) {
            $this->error['telephone_form'] = $this->language->get('error_telephone_form');
        }
        // FIM - Validação de Telefone e Celular - por Henrique R. Pohl

        if (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email'])) {
            $this->error['email'] = $this->language->get('error_email');
        }

        if ((utf8_strlen($this->request->post['enquiry']) < 10) || (utf8_strlen($this->request->post['enquiry']) > 3000)) {
            $this->error['enquiry'] = $this->language->get('error_enquiry');
        }

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

}
