<?php

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

    public function index($post = '')
    {
        $checkout = false;

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

        // 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_new' || $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->data['checkout'] = true;
            }
        }

        // 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']);
                }
                $this->redirect($this->url->link('account/home', '', 'SSL'));
            }
        }

        if ($this->customer->isLogged()) {
            if (isset($post['checkout'])) {
                return $this->response->setOutputJson(['redirect' => $this->url->link('checkout/checkout', '', 'SSL')]);
            } else {
                return $this->response->setOutputJson(['redirect' => $this->url->link('account/home', '', 'SSL')]);
            }
        }

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

        if ($this->request->server['REQUEST_METHOD'] == 'POST' && isset($this->request->post['email_login'])) {
            $this->validate();
            if ($this->error) {
                $this->data['captcha'] = true;
                return $this->response->setOutputJson([
                    'errors' => $this->error,
                    'session_captcha' => $this->session->data['gcapcha'] ?? false,
                    'google_captcha' => $this->config->get('google_recaptcha_site_key')
                        && $this->config->get('google_recaptcha_secret_key')
                        && $this->config->get('wg24_google_recaptcha_status')]);
            }

            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->response->setOutputJson(['redirect' => $this->url->link('checkout/checkout', '', 'SSL')]);
                }
            }
        }

        $language = $this->load->language('account/login_new');
        $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_new', $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'] = '';
        }

        $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');
        $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');
        $this->data['default_captcha'] = false;
        $this->data['session_captcha'] = $this->session->data['gcapcha'] ?? false;
        $this->data['show_captcha'] = (isset($this->session->data['customer_login_trys']) && $this->session->data['customer_login_trys'] > 0) ;

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

    public function validate()
    {
        $this->load->model('account/customer');

        // Tem que validar o captcha primeiro, senão ele loga direto
        if (isset($this->session->data['customer_login_trys']) && $this->session->data['customer_login_trys'] > 0) {
            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['warning'] = 'Erro de validação no reCaptcha! Efetue a validação para continuar';
                }
            } else if (empty($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
                $this->error['warning'] = 'O código de verificação não coincide com a imagem!';
            }
        }

        if($this->config->get('email_validation_status') > 0){
            $customer = $this->model_account_customer->getCustomerByEmail($this->request->post['email_login']);

            if($customer && $customer['valided'] == 0){
                $this->error['warning'] = 'O seu email ainda não foi validado, verifique a caixa de mensagem do seu email de cadastro!';
            }

            if (!$this->error) {
                if (!$this->customer->login($this->request->post['email_login'], $this->request->post['password'])) {
    
                    if($this->customer->getCustomerLock()){
                        $text = $this->customer->getTime_unlock()? $this->customer->getTime_unlock(). "<br>": '';
                        $this->error['warning'] = $text .$this->language->get('error_lock'). ' e-mail: '. $this->config->get('safety_limiter_mail');
                    }else{
                        $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');
                }
            }
        }else{
            if (!$this->error) {
                if (!$this->customer->login($this->request->post['email_login'], $this->request->post['password'])) {
    
                    if($this->customer->getCustomerLock()){
                        $text = $this->customer->getTime_unlock()? $this->customer->getTime_unlock(). "<br>": '';
                        $this->error['warning'] = $text .$this->language->get('error_lock'). ' e-mail: '. $this->config->get('safety_limiter_mail');
                    }else{
                        $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 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') {
            $data = $this->getDatalAccesTokenGoogle($this->request->post['tokenloginsocial']);
            if ((array_key_exists('expires_in', $data)) && ($data['expires_in'] > 0)) {
                if (((isset($data['email'])) && (($data['email']) <> '')) && ((isset($data['user_id'])) && (($data['user_id']) <> ''))) {
                    if ($this->request->post['tipo_validacao_social'] == 'vincular') {
                        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');
                        }
                    } elseif (!$this->customer->loginredesocial($data['email'], $data['user_id'], false, 'google')) {
                        $json['idRedeSocial'] = $data['user_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;
            }
        } elseif ($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 captcha()
    {
        $this->load->library('captcha');

        $captcha = new Captcha();

        $this->session->data['captcha'] = $captcha->getCode();

        $captcha->showImage();
    }
}
