<?php
/**
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 * We offer the best and most useful modules PrestaShop and modifications for your online store.
 *
 * @author    knowband.com <support@knowband.com>
 * @copyright 2017 Knowband
 * @license   see file: LICENSE.txt
 * @category  PrestaShop Module
 */

include_once(_PS_MODULE_DIR_ . 'socialloginizer/libraries/http.php');
include_once(_PS_MODULE_DIR_ . 'socialloginizer/libraries/oauth_client.php');
include_once(_PS_MODULE_DIR_ . 'socialloginizer/libraries/sendinBlue/Mailin.php');

class SocialLoginizerGithubModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        parent::initContent();
        $platform = Tools::getValue('type');
        $platform = trim($platform);

        if ($platform == 'github') {
            $user_data = $this->githubLogin();
        }

        if (empty($user_data)) {
            $user_data = $this->githubLogin();
        }
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        // changes by rishabh jain if email does not received
        if (Tools::isSubmit('login_email')) {
            $email = Tools::getValue('login_email');
            if (Customer::customerExists($email)) {
                $errormsg = $this->module->l('Email already exist please choose another one');
                $this->context->smarty->assign('errormsg', $errormsg);
                if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
                    $custom_ssl_var = 1;
                }
                if ((bool) Configuration::get('PS_SSL_ENABLED') && $custom_ssl_var == 1) {
                    $module_dir = _PS_BASE_URL_SSL_ . __PS_BASE_URI__ . str_replace(_PS_ROOT_DIR_ . '/', '', _PS_MODULE_DIR_);
                } else {
                    $module_dir = _PS_BASE_URL_ . __PS_BASE_URI__ . str_replace(_PS_ROOT_DIR_ . '/', '', _PS_MODULE_DIR_);
                }
                $this->context->smarty->assign('modulepath', $module_dir);
                $this->setTemplate('module:socialloginizer/views/templates/front/github-email.tpl');
            } else {
                $user_data = $this->githubLogin();
                if (!empty($user_data)) {
                    $unique_id = $user_data->id;
                    $sql = 'insert into ' . _DB_PREFIX_ . 'socialloginizer_mapping (email,unique_id) values ("' . pSQL($email) . '","' . pSQL($unique_id) . '")';
                    Db::getInstance()->execute($sql);
                    $user_data->login = preg_replace('#[0-9 ]*#', '', $user_data->login);
                    $social_data = array();
                    $social_data['first_name'] = $user_data->login;
                    $social_data['last_name'] = $user_data->login;
                    $social_data['email'] = $email;
                    $social_data['gender'] = 0;
                    $social_data['username'] = $user_data->login;
                    $this->addEmailToList($user_data->login, $email);
                    $this->addEmailToListKlaviyo($email, $user_data->login);
                    $this->addEmailToListSendinBlue($email, $user_data->login);
                    $obj = new SocialLoginizer();

                    $result = $obj->addUser($social_data, 'Github');
                    if ($result == 1) {
                        if ($loginizer_data['show_popup'] == 1) {
                            echo '<script> window.opener.location.reload(true);
                            window.close();</script>';
                            die;
                        } else {
                            if (isset($loginizer_data['redirect_url']) && $loginizer_data['redirect_url'] != '') {
                                if (!filter_var($loginizer_data['redirect_url'], FILTER_VALIDATE_URL) === false) {
                                    Tools::redirect($loginizer_data['redirect_url']);
                                } else {
                                    Tools::redirect('index.php');
                                }
                            } else {
                                Tools::redirect('index.php');
                            }
                        }
                    } else {
                        $error_controller = $this->context->link->getModuleLink('socialloginizer', 'error', array(), Configuration::get('PS_SSL_ENABLED'));
                        if ($loginizer_data['show_popup'] == 1) {
                            echo '<script> window.opener.document.location.href = "'.$error_controller.'";
                                        window.close();</script>';
                            die;
                        } else {
                            Tools::redirect($error_controller);
                        }
                    }
                }
            }
        } elseif (count($user_data) > 0) {
            if (isset($user_data->email) && $user_data->email != '') {
            } else {
                $email_data = $this->githubLogin(true);
                if (!empty($email_data[0]->email)) {
                    $email = $email_data[0]->email;
                    $user_data->email = $email;
                    unset($email_data);
                }
            }
            if (isset($user_data->email) && $user_data->email != '') {
//                $unique_id = $user_data->id;
//                $sql = 'insert into ' . _DB_PREFIX_ . 'socialloginizer_mapping (email,unique_id) values ("' . pSQL($user_data->email) . '","' . pSQL($unique_id) . '")';
//                Db::getInstance()->execute($sql);
                $social_data = array();
                $user_data->login = preg_replace('#[0-9 ]*#', '', $user_data->login);
                $social_data['first_name'] = $user_data->login;
                $social_data['last_name'] = $user_data->login;
                $social_data['email'] = $user_data->email;
                $social_data['gender'] = 0;
                $social_data['username'] = $user_data->login;
                $this->addEmailToList($user_data->login, $user_data->email);
                $this->addEmailToListKlaviyo($user_data->email, $user_data->login);
                $this->addEmailToListSendinBlue($user_data->email, $user_data->login);
                $obj = new SocialLoginizer();

                $result = $obj->addUser($social_data, 'Github');
                if ($result == 1) {
                    if ($loginizer_data['show_popup'] == 1) {
                        echo '<script> window.opener.location.reload(true);
                        window.close();</script>';
                        die;
                    } else {
                        if (isset($loginizer_data['redirect_url']) && $loginizer_data['redirect_url'] != '') {
                            if (!filter_var($loginizer_data['redirect_url'], FILTER_VALIDATE_URL) === false) {
                                Tools::redirect($loginizer_data['redirect_url']);
                            } else {
                                Tools::redirect('index.php');
                            }
                        } else {
                            Tools::redirect('index.php');
                        }
                    }
                } else {
                    $error_controller = $this->context->link->getModuleLink('socialloginizer', 'error', array(), Configuration::get('PS_SSL_ENABLED'));
                    if ($loginizer_data['show_popup'] == 1) {
                        echo '<script> window.opener.document.location.href = "'.$error_controller.'";
                                    window.close();</script>';
                        die;
                    } else {
                        Tools::redirect($error_controller);
                    }
                }
            } else {
                $query = 'select email from ' . _DB_PREFIX_ . 'socialloginizer_mapping where unique_id="' . pSQL($user_data->id) . '"';
                $result = Db::getInstance()->executeS($query);
                if (count($result) == 0) {
                    $flag = 1;
                }
                if ((int)$flag == 0) {
                    $social_data = array();
                    $user_data->login = preg_replace('#[0-9 ]*#', '', $user_data->login);
                    $social_data['first_name'] = $user_data->login;
                    $social_data['last_name'] = $user_data->login;
                    $social_data['email'] = $result[0]['email'];
                    $social_data['gender'] = 0;
                    $social_data['username'] = $user_data->login;
                    $this->addEmailToList($user_data->login, $result[0]['email']);
                    $this->addEmailToListKlaviyo($result[0]['email'], $user_data->login);
                    $this->addEmailToListSendinBlue($result[0]['email'], $user_data->login);
                    $obj = new SocialLoginizer();

                    $result = $obj->addUser($social_data, 'Github');
                    if ($result == 1) {
                        if ($loginizer_data['show_popup'] == 1) {
                            echo '<script> window.opener.location.reload(true);
                            window.close();</script>';
                            die;
                        } else {
                            if (isset($loginizer_data['redirect_url']) && $loginizer_data['redirect_url'] != '') {
                                if (!filter_var($loginizer_data['redirect_url'], FILTER_VALIDATE_URL) === false) {
                                    Tools::redirect($loginizer_data['redirect_url']);
                                } else {
                                    Tools::redirect('index.php');
                                }
                            } else {
                                Tools::redirect('index.php');
                            }
                        }
                    } else {
                        $error_controller = $this->context->link->getModuleLink('socialloginizer', 'error', array(), Configuration::get('PS_SSL_ENABLED'));
                        if ($loginizer_data['show_popup'] == 1) {
                            echo '<script> window.opener.document.location.href = "'.$error_controller.'";
                                        window.close();</script>';
                            die;
                        } else {
                            Tools::redirect($error_controller);
                        }
                    }
                } else {
                    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
                        $custom_ssl_var = 1;
                    }
                    if ((bool) Configuration::get('PS_SSL_ENABLED') && $custom_ssl_var == 1) {
                        $module_dir = _PS_BASE_URL_SSL_ . __PS_BASE_URI__ . str_replace(_PS_ROOT_DIR_ . '/', '', _PS_MODULE_DIR_);
                    } else {
                        $module_dir = _PS_BASE_URL_ . __PS_BASE_URI__ . str_replace(_PS_ROOT_DIR_ . '/', '', _PS_MODULE_DIR_);
                    }
                    $this->context->smarty->assign('modulepath', $module_dir);
                    $this->setTemplate('module:socialloginizer/views/templates/front/github-email.tpl');
                }
            }
        } else {
            $error_controller = $this->context->link->getModuleLink('socialloginizer', 'error', array(), Configuration::get('PS_SSL_ENABLED'));
            if ($loginizer_data['show_popup'] == 1) {
                echo '<script> window.opener.document.location.href = "'.$error_controller.'";
                            window.close();</script>';
                die;
            } else {
                Tools::redirect($error_controller);
            }
        }
    }

    public function githubLogin($request_url = false)
    {
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        $user = '';
        $client = new oauth_client_class;
        $client->server = 'github';

        $client->offline = true;

        $client->debug = false;
        $client->debug_http = true;
        $client->redirect_uri = $this->context->link->getModuleLink('socialloginizer', 'github', array(), Configuration::get('PS_SSL_ENABLED'));

        $lang_str = '&id_lang=' . $this->context->language->id;
        $client->redirect_uri = str_replace($lang_str, '', $client->redirect_uri);

        $lang_str = '/' . $this->context->language->iso_code . '/';
        $client->redirect_uri = str_replace($lang_str, '/', $client->redirect_uri);

        $client->client_id = $loginizer_data['github']['client_id'];
        $client->client_secret = $loginizer_data['github']['client_secret'];

        if (Tools::strlen($client->client_id) == 0 || Tools::strlen($client->client_secret) == 0) {
            Tools::redirect($this->context->link->getModuleLink('socialloginizer', 'credentials', array(), Configuration::get('PS_SSL_ENABLED')));
        }

        $client->scope = 'user:email';
        if (($success = $client->Initialize())) {
            if (($success = $client->Process())) {
                if (Tools::strlen($client->authorization_error)) {
                    $client->error = $client->authorization_error;
                    $success = false;
                } elseif (Tools::strlen($client->access_token)) {
                    if ($request_url) {
                        $success = $client->CallAPI(
                            'https://api.github.com/user/emails',
                            'GET',
                            array(),
                            array('FailOnAccessError' => true),
                            $user
                        );
                        return $user;
                    } else {
                        $success = $client->CallAPI(
                            'https://api.github.com/user',
                            'GET',
                            array(),
                            array('FailOnAccessError' => true),
                            $user
                        );
                        return $user;
                    }
                }
            }
            $success = $client->Finalize($success);
        }
        if ($client->exit) {
            exit;
        }
    }

    public function addEmailToList($fname, $email)
    {
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        $apikey = $loginizer_data['github']['mailchimp_api'];
        $mailchimp = new MailChimpKbSL($apikey);
        $listid = $loginizer_data['github']['mailchimp_list'];
        try {
            $mailchimp->call('lists/subscribe', array(
                'id' => $listid,
                'email' => array('email' => $email),
                'merge_vars' => array('FNAME' => $fname),
                'double_optin' => false, // use true if you want to send confirmation mail to customer like, click here to confirm your subscription.
                'update_existing' => false,
                'replace_interests' => false,
                'send_welcome' => false, // use true to send subscription success mail to customer on subscription
            ));
        } catch (Exception $e) {
            return;
        }
    }
    
    public function addEmailToListKlaviyo($email, $first_name = null, $last_name = null)
    {
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        $api_key = $loginizer_data['github']['klaviyo_api'];
        $list_id = $loginizer_data['github']['klaviyo_list'];
        
        $properties = array();
        if ($first_name) {
            $properties['$first_name'] = $first_name;
        }
        if ($last_name) {
            $properties['$last_name'] = $last_name;
        }
        $properties_val = count($properties) ? urlencode(json_encode($properties)) : '{}';
        $fields = array(
            'api_key=' . $api_key,
            'email=' . urlencode($email),
            'confirm_optin=false',
            'properties=' . $properties_val,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://a.klaviyo.com/api/v1/list/' . $list_id . '/members');
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, join('&', $fields));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch);
        curl_close($ch);
    }
    
    public function addEmailToListSendinBlue($email, $first_name = null, $last_name = null)
    {
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        $apikey = $loginizer_data['github']['sendinblue_api'];
        $listid = $loginizer_data['github']['sendinblue_list'];
        $mailin = new Mailin('https://api.sendinblue.com/v2.0', $apikey);

        $data_arr = array("email" => $email,
            "listid" => array($listid),
            "attributes" => array("FIRSTNAME" => $first_name, "LASTNAME" => $last_name)
        );

        $mailin->create_update_user($data_arr); //calling function to add user
    }
}
