<?php

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

    public function index($post = '')
    {

        $this->document->addScriptApp(array(
            'catalog/view/theme/vista/js/jquery/jquery.validate.js',
            'catalog/view/theme/vista/js/jquery/additional-methods.js',
            'catalog/view/theme/vista/js/jquery/jquery.validate.futura-methods.js',
            'catalog/view/theme/vista/js/jquery/localization/messages_pt_BR.js',
        ));

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

        $checkout = false;

        // validação feita para caso o usuario digite a url account/login ele redirecione para a account/register
        if (isset($this->request->get['route']) && ($this->request->get['route'] == 'account/login') && ($this->request->server['REQUEST_METHOD'] == 'GET')) {
            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

        if (!isset($post['checkout'])) {
            if (isset($this->request->get['checkout']) && $this->request->get['checkout']) {
                $checkout = true;
            }
        }

        $this->loadscripts();

        // Login override for admin users
        if (!empty($this->request->get['token'])) {
            $this->customer->logout();
            $this->cart->clear();

            unset($this->session->data['wishlist']);
            unset($this->session->data['shipping_address_id']);
            unset($this->session->data['shipping_country_id']);
            unset($this->session->data['shipping_zone_id']);
            unset($this->session->data['shipping_postcode']);
            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_address_id']);
            unset($this->session->data['payment_country_id']);
            unset($this->session->data['payment_zone_id']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);
            unset($this->session->data['comment']);
            unset($this->session->data['order_id']);
            unset($this->session->data['coupon']);
            unset($this->session->data['reward']);
            unset($this->session->data['voucher']);
            unset($this->session->data['vouchers']);

            $customer_info = $this->model_account_customer->getCustomerByToken($this->request->get['token']);

            if ($customer_info && $this->customer->login($customer_info['email'], '', true)) {
                // Default Addresses
                $this->load->model('account/address');

                $address_info = $this->model_account_address->getAddress($this->customer->getAddressId());

                if ($address_info) {
                    if ($this->config->get('config_tax_customer') == 'shipping') {
                        $this->session->data['shipping_country_id'] = $address_info['country_id'];
                        $this->session->data['shipping_zone_id'] = $address_info['zone_id'];
                        $this->session->data['shipping_postcode'] = $address_info['postcode'];
                    }

                    if ($this->config->get('config_tax_customer') == 'payment') {
                        $this->session->data['payment_country_id'] = $address_info['country_id'];
                        $this->session->data['payment_zone_id'] = $address_info['zone_id'];
                    }
                } else {
                    unset($this->session->data['shipping_country_id']);
                    unset($this->session->data['shipping_zone_id']);
                    unset($this->session->data['shipping_postcode']);
                    unset($this->session->data['payment_country_id']);
                    unset($this->session->data['payment_zone_id']);
                }
                if (!isset($post['checkout'])) {
                    $this->redirect($this->url->link('account/home', '', 'SSL'));
                }
            }
        }

        if ($this->customer->isLogged() && !isset($post['checkout'])) {
            $this->redirect($this->url->link('account/home', '', 'SSL'));
        }

        $this->language->load('account/login');

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && isset($this->request->post['email_login']) && $this->validate()) {
            unset($this->session->data['guest']);

            // Default Shipping Address
            $this->load->model('account/address');

            $address_info = $this->model_account_address->getAddress($this->customer->getAddressId());

            if ($address_info) {
                if ($this->config->get('config_tax_customer') == 'shipping') {
                    $this->session->data['shipping_country_id'] = $address_info['country_id'];
                    $this->session->data['shipping_zone_id'] = $address_info['zone_id'];
                    $this->session->data['shipping_postcode'] = $address_info['postcode'];
                }

                if ($this->config->get('config_tax_customer') == 'payment') {
                    $this->session->data['payment_country_id'] = $address_info['country_id'];
                    $this->session->data['payment_zone_id'] = $address_info['zone_id'];
                }
            } else {
                unset($this->session->data['shipping_country_id']);
                unset($this->session->data['shipping_zone_id']);
                unset($this->session->data['shipping_postcode']);
                unset($this->session->data['payment_country_id']);
                unset($this->session->data['payment_zone_id']);
            }

            // Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
            if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->url->link('', '', 'SSL', false)) !== false)) {
                if (!isset($post['checkout'])) {
                    $this->redirect(str_replace('&amp;', '&', $this->request->post['redirect']));
                }
            } else {
                if (!isset($post['checkout'])) {
                    $this->redirect($this->url->link('account/home', '', 'SSL'));
                }
            }
        }

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

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

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

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }
        $paramentro = ($checkout) ? 'checkout=true' : 'login=1';
        $this->data['action'] = $this->url->link('account/login', $paramentro, 'SSL');
        $this->data['register'] = $this->url->link('account/register', '', 'SSL');
        $this->data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');

        // Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
        if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->url->link('', '', 'SSL', false)) !== false)) {
            if (!isset($post['checkout'])) {
                $this->data['redirect'] = $this->request->post['redirect'];
            }
        } elseif (isset($this->session->data['redirect'])) {
            if (!isset($post['checkout'])) {
                $this->data['redirect'] = $this->session->data['redirect'];
            }

            unset($this->session->data['redirect']);
        } else {
            $this->data['redirect'] = '';
        }

        if (isset($this->session->data['success'])) {
            $this->data['success'] = $this->session->data['success'];

            unset($this->session->data['success']);
        } else {
            $this->data['success'] = '';
        }

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

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

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

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

        $this->data['facebook_enable'] = ($this->config->get('loginredesociais_facebook_status')) ? true : false;
        $this->data['facebook_id'] = $this->config->get('loginredesociais_facebook_id');

        $this->data['google_enable'] = ($this->config->get('loginredesociais_google_status')) ? true : false;
        $this->data['google_id'] = $this->config->get('loginredesociais_google_id');


        if (isset($this->request->get['login']) && $this->request->get['login']) {
            if (!isset($post['checkout'])) {
                if ($this->error['warning']) {
                    $this->session->data['warning'] = $this->error['warning'];
                }
                $this->redirect($this->url->link('account/register', '', 'SSL'));
            }
        } else {
            $this->response->setOutput($this->render('account/login'));
        }
    }

    public function validate()
    {
        $checkout = false;

        if (isset($this->request->get['checkout']) && $this->request->get['checkout']) {
            $checkout = true;
        }

        if ($checkout) {
            $this->language->load('checkout/checkout');

            $json = array();

            if ($this->customer->isLogged()) {
                $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
            }

            if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
                $json['redirect'] = $this->url->link('checkout/cart');
            }

            if (!$json) {
                if ((utf8_strlen($this->request->post['email_login']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email_login']) || !filter_var($this->request->post['email_login'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email_login'])) {
                    $json['error']['email_login'] = $this->language->get('error_email');
                }
                if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
                    $json['error']['password'] = $this->language->get('error_password');
                }


                if (!$this->customer->login($this->request->post['email_login'], $this->request->post['password'])) {
                    $json['error']['warning'] = $this->language->get('error_login');
                }
                $this->load->model('account/customer');

                $customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email_login']);

                if ($customer_info && !$customer_info['approved']) {
                    $json['error']['warning'] = $this->language->get('error_approved');
                }

            }

            if (!$json) {
                unset($this->session->data['guest']);

                // Default Addresses
                $this->load->model('account/address');

                $address_info = $this->model_account_address->getAddress($this->customer->getAddressId());

                if ($address_info) {
                    if ($this->config->get('config_tax_customer') == 'shipping') {
                        $this->session->data['shipping_country_id'] = $address_info['country_id'];
                        $this->session->data['shipping_zone_id'] = $address_info['zone_id'];
                        $this->session->data['shipping_postcode'] = $address_info['postcode'];
                    }

                    if ($this->config->get('config_tax_customer') == 'payment') {
                        $this->session->data['payment_country_id'] = $address_info['country_id'];
                        $this->session->data['payment_zone_id'] = $address_info['zone_id'];
                    }
                } else {
                    unset($this->session->data['shipping_country_id']);
                    unset($this->session->data['shipping_zone_id']);
                    unset($this->session->data['shipping_postcode']);
                    unset($this->session->data['payment_country_id']);
                    unset($this->session->data['payment_zone_id']);
                }

                $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
            }

            $this->response->setOutput(json_encode($json));
        } else {
            $this->load->model('account/customer');

            if (!$this->customer->login($this->request->post['email_login'], $this->request->post['password'])) {
                $this->error['warning'] = $this->language->get('error_login');
            }

            $customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email_login']);

            if ($customer_info && !$customer_info['approved']) {
                $this->error['warning'] = $this->language->get('error_approved');
            }

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

    public function getDatalAccesTokenGoogle($access_token)
    {
        $this->load->helper('ftr_geral');
        try {
            $json = ftr_geral::callJson('https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=' . $access_token);
            return $json;
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    public function getDatalTokenIdGoogle($token_id)
    {
        $this->load->helper('ftr_geral');
        try {
            $json = ftr_geral::callJson('https://oauth2.googleapis.com/tokeninfo?id_token=' . $token_id);
            return $json;
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    public function getDatalAccesTokenFacebook($access_token)
    {
        $this->load->helper('ftr_geral');
        try {
            $json = ftr_geral::callJson('https://graph.facebook.com/v3.0/me?fields=id,name,email&access_token=' . $access_token);
            return $json;
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    public function socialLogin()
    {
        $json = array();
        $this->load->model('account/customer');
        $this->language->load('checkout/checkout');


        if ($this->request->post['origemLogin'] == 'google') {
            if ($this->request->post['tipo_validacao_social'] == 'vincular') {
                $data = $this->getDatalAccesTokenGoogle($this->request->post['tokenloginsocial']);
                if (((isset($data['email'])) && (($data['email']) <> '')) && ((isset($data['user_id'])) && (($data['user_id']) <> ''))) {
                    if (!($this->customer->redeSocialJaVinculada($this->customer->getId(), $data['email'], $data['user_id'], 'google'))) {
                        if ($this->customer->vincularRedeSocial($this->customer->getId(), $data['email'], $data['user_id'], 'google')) {
                            $json['login_vinculado'] = true;
                        } else {
                            $json['login_vinculado'] = false;
                        }
                        $json['warning_login_vinculado'] = false;
                    } else {
                        $json['warning_login_vinculado'] = $this->language->get('error_emailJaVinculado');
                    }
                } else {
                    $json['login_vinculado'] = false;
                    $json['warning_login_vinculado'] = $this->language->get('error_google_permission');
                }
            } else {
                $data = $this->getDatalTokenIdGoogle($this->request->post['jwtIdToken']);
                if ((isset($data['email']) && ($data['email'] <> '')) && (isset($data['sub']) && ($data['sub'] <> ''))
                    && (isset($data['exp']) && ($data['exp'] > 0))) {
                    if (!$this->customer->loginredesocial($data['email'], $data['sub'], false, 'google')) {
                        $json['idRedeSocial'] = $data['sub'];
                        $json['nomeRedeSocial'] = $data['name'];
                        $json['primeiroNomeRedeSocial'] = $data['given_name'];
                        $json['sobrenomeRedeSocial'] = $data['family_name'];
                        $json['emailRedeSocial'] = $data['email'];
                        $json['origemLogin'] = $this->request->post['origemLogin'];
                        $json['login'] = false;
                        $customer_info = $this->model_account_customer->getCustomerByEmail($data['email']);
                        if ($customer_info && !$customer_info['approved']) {
                            $json['warning'] = $this->language->get('error_approved');
                        } else {
                            $json['warning'] = $this->language->get('error_cadastroNaoEncontrado');
                        }
                    } else {
                        $json['login'] = true;
                    }
                } else {
                    $json['login'] = false;
                    $json['warning'] = $this->language->get('error_google_permission');
                }
            }

        } else if ($this->request->post['origemLogin'] == 'facebook') {
            $data = $this->getDatalAccesTokenFacebook($this->request->post['tokenloginsocial']);

            if (array_key_exists('email', $data)) {
                if (((isset($data['email'])) && (($data['email']) <> '')) && ((isset($data['id'])) && (($data['id']) <> ''))) {
                    if ($this->request->post['tipo_validacao_social'] == 'vincular') {
                        if (!($this->customer->redeSocialJaVinculada($this->customer->getId(), $data['email'], $data['id'], 'facebook'))) {
                            if ($this->customer->vincularRedeSocial($this->customer->getId(), $data['email'], $data['id'], 'facebook')) {
                                $json['login_vinculado'] = true;
                            } else {
                                $json['login_vinculado'] = false;
                            }
                            $json['warning_login_vinculado'] = false;
                        } else {
                            $json['warning_login_vinculado'] = $this->language->get('error_emailJaVinculado');
                        }
                    } elseif (!$this->customer->loginredesocial($data['email'], $data['id'], false, 'facebook')) {
                        $json['idRedeSocial'] = $data['id'];
                        $json['nomeRedeSocial'] = $this->request->post['nomeRedeSocial'];
                        $json['primeiroNomeRedeSocial'] = $this->request->post['primeiroNomeRedeSocial'];
                        $json['sobrenomeRedeSocial'] = $this->request->post['sobrenomeRedeSocial'];
                        $json['emailRedeSocial'] = $data['email'];
                        $json['origemLogin'] = $this->request->post['origemLogin'];
                        $json['login'] = false;
                        $customer_info = $this->model_account_customer->getCustomerByEmail($data['email']);
                        if ($customer_info && !$customer_info['approved']) {
                            $json['warning'] = $this->language->get('error_approved');
                        } else {
                            $json['warning'] = $this->language->get('error_cadastroNaoEncontrado');
                        }
                    } else {
                        $json['login'] = true;
                    }
                }
            } else {
                $json['warning'] = $this->language->get('error_cadastroNaoEncontrado');
                $json['login'] = false;
            }
        }

        $this->response->setOutput(json_encode($json));
    }


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

        if ($this->config->get('loginredesociais_facebook_status')) {
            $this->document->addScript('catalog/view/theme/vista/public/js/facebook.js');
            $this->document->addScript('https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v14.0');
        }
        if ($this->config->get('loginredesociais_google_status')) {
            $this->document->addScript('https://accounts.google.com/gsi/client');
        }

    }

}
