<?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 SocialLoginizerPaypalModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        parent::initContent();
        $platform = Tools::getValue('type');

        $platform = trim($platform);

        if ($platform == 'pay') {
            $this->paypalLogin();
        }
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        $code = Tools::getValue('code');

        $c_id = $loginizer_data['pay']['client_id'];
        $c_sec = $loginizer_data['pay']['client_secret'];

        if (isset($code) && $code != '') {
            $header = array();
            /* We have used base64_encode to encode the client Id and Client Secret according to the Paypal API , we cannot remove it for the validator */
            $header[] = 'Authorization: BASIC '. base64_encode($c_id.":".$c_sec);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://api.paypal.com/v1/oauth2/token');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials&&code=".$code);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result1 = curl_exec($ch);
            curl_close($ch);
            $token = Tools::jsonDecode($result1);
            if (isset($token->access_token) && $token->access_token != '') {
                $pay_link2 = 'https://api.paypal.com/v1/identity/oauth2/userinfo?schema=openid&access_token=';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $pay_link2 . $token->access_token);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $result2 = curl_exec($ch);
                curl_close($ch);
                $data = Tools::jsonDecode($result2);
            } 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);
                }
            }

            if (count($data) > 0) {
                if (isset($data->email) && $data->email != '') {
                    $social_data = array();
                    $full_name_arr = preg_split('#\s+#', $data->name, 2);
                    $social_data['first_name'] = $full_name_arr[0];
                    $social_data['last_name'] = isset($full_name_arr[1]) ? $full_name_arr[1] : '';
                    $social_data['email'] = $data->email;
                    $social_data['gender'] = 0;
                    $social_data['username'] = $full_name_arr[0];
                    $this->addEmailToList($full_name_arr[0], $data->email);
                    $this->addEmailToListKlaviyo($data->email, $full_name_arr[0], $full_name_arr[1]);
                    $this->addEmailToListSendinBlue($data->email, $full_name_arr[0], $full_name_arr[1]);
                    $obj = new SocialLoginizer();

                    $result = $obj->addUser($social_data, 'Paypal');
                    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 {
                    $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 {
                $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);
                }
            }
        }
        /*
         * BOC SANAND Added this code to resolve paypal error page issue when Show Popup is disabled
         */
        if (Tools::getValue('error_uri')) {
                Tools::redirect('index.php');
        } elseif ($loginizer_data['show_popup'] == 1) {
            $error_controller = $this->context->link->getModuleLink('socialloginizer', 'error', array(), Configuration::get('PS_SSL_ENABLED'));
            echo '<script> window.opener.document.location.href = "'.$error_controller.'";
                        window.close();</script>';
            die;
        } else {
            die;
        }
//        } 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);
//            }
//        }
        /*
         * EOC SANAND Added this code to resolve paypal error page issue when Show Popup is disabled
         */
    }

    public function paypalLogin()
    {
        $settings = Configuration::get('VELOCITY_SOCIAL_LOGINIZER');
        $loginizer_data = unserialize($settings);
        $user = '';
        $client = new oauth_client_class;
        $client->debug = true;
        $client->debug_http = true;
        $client->server = 'Paypal';
        $client->redirect_uri = $this->context->link->getModuleLink('socialloginizer', 'paypal', array(), Configuration::get('PS_SSL_ENABLED'));
        $client->scope = 'profile email';
        $client->client_id = $loginizer_data['pay']['client_id'];
        $client->client_secret = $loginizer_data['pay']['client_secret'];

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

        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')));
        } else {
            if (($success = $client->Initialize())) {
                $success1 = $client->Process();
                if ($success1) {
                    if (Tools::strlen($client->access_token)) {
                        $success = $client->CallAPI('https://api.paypal.com/v1/identity/oauth2/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
                        return $user;
                    } else {
                        return $client->authorization_error;
                    }
                } else {
                    return $client->error;
                }

                $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['pay']['mailchimp_api'];
        $mailchimp = new MailChimpKbSL($apikey);
        $listid = $loginizer_data['pay']['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['pay']['klaviyo_api'];
        $list_id = $loginizer_data['pay']['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['pay']['sendinblue_api'];
        $listid = $loginizer_data['pay']['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
    }
}
