/**
  * Access LoginRadius API server by fsockopen method
  *
  * @param type $request_url
  * @param type $options
  * @return type
  */
 private function fsockopenApiMethod($request_url, $options = array())
 {
     $ssl_verify = isset($options['ssl_verify']) ? $options['ssl_verify'] : false;
     $method = isset($options['method']) ? strtolower($options['method']) : 'get';
     $data = isset($options['post_data']) ? $options['post_data'] : array();
     $content_type = isset($options['content_type']) ? $options['content_type'] : 'form_params';
     if (!empty($data)) {
         $options = array('http' => array('method' => strtoupper($method), 'timeout' => 50, 'header' => 'Content-type :application/' . $content_type, 'content' => $content_type == 'json' ? json_encode($data) : LoginRadiusSDK\LoginRadius::queryBuild($data)), "ssl" => array("verify_peer" => $ssl_verify));
         $context = stream_context_create($options);
     } else {
         $context = NULL;
     }
     $json_response = @file_get_contents($request_url, false, $context);
     if (!$json_response) {
         throw new LoginRadiusSDK\LoginRadiusException('file_get_contents error');
     }
     return $json_response;
 }
 public function admin_customer_save_before($observer)
 {
     require_once Mage::getModuleDir('', 'Loginradius_Sociallogin') . DS . 'Helper' . DS . 'SDKClient.php';
     global $apiClient_class;
     $apiClient_class = 'Loginradius_Sociallogin_Helper_SDKClient';
     $activationBlockObj = Mage::getBlockSingleton('activation/activation');
     $userAPI = new LoginRadiusSDK\CustomerRegistration\UserAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
     $postData = Mage::app()->getRequest()->getPost();
     $formattedDate = '';
     if (isset($postData['account']['dob']) && !empty($postData['account']['dob'])) {
         $dateString = strtotime($postData['account']['dob']);
         $formattedDate = date('m-d-Y', $dateString);
     }
     /**
      * Creating user on RAAS
      */
     if (!isset($postData['customer_id'])) {
         if ($postData['account']['website_id'] != 0) {
             $params = array('EmailId' => $postData['account']['email'], 'firstname' => $postData['account']['firstname'], 'lastname' => $postData['account']['lastname'], 'birthdate' => $formattedDate, 'password' => $postData['account']['password']);
             if (isset($postData['account']['gender'])) {
                 if ($postData['account']['gender'] == '1') {
                     $params['gender'] = 'M';
                 } elseif ($postData['account']['gender'] == '0') {
                     $params['gender'] = 'F';
                 }
             }
             if ($postData['account']['password'] == 'auto') {
                 $charsPass = "******";
                 $autoGenratedPassParams = array('EmailId' => $postData['account']['email'], 'firstname' => $postData['account']['firstname'], 'lastname' => $postData['account']['lastname'], 'birthdate' => $formattedDate, 'password' => substr(str_shuffle($charsPass), 0, 8));
                 try {
                     $response = $userAPI->create($params);
                     $_POST['lr_raas_resonse'] = $response;
                     $forgotPassDomain = Mage::getBaseUrl() . 'customerregistration/index/verification/';
                     try {
                         $rsetPasswordUrl = 'https://api.loginradius.com/raas/client/password/forgot?apikey=' . $activationBlockObj->apiKey() . '&emailid=' . $postData['account']['email'] . '&resetpasswordurl=' . $forgotPassDomain;
                     } catch (LoginRadiusSDK\LoginRadiusException $e) {
                         Mage::throwException($e->getErrorResponse()->description);
                     }
                     $result = LoginRadiusSDK\LoginRadius::apiClient($rsetPasswordUrl, FALSE, array('output_format' => 'json'));
                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                     Mage::throwException($e->getErrorResponse()->description);
                 }
             } else {
                 try {
                     $response = $userAPI->create($params);
                     $_POST['lr_raas_resonse'] = $response;
                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                     Mage::throwException($e->getErrorResponse()->description);
                 }
             }
         }
     } else {
         // Updating user profile
         $params = array('EmailId' => $postData['account']['email'], 'firstname' => $postData['account']['firstname'], 'lastname' => $postData['account']['lastname'], 'birthdate' => $formattedDate);
         if (isset($postData['account']['gender'])) {
             if ($postData['account']['gender'] == '1') {
                 $params['gender'] = 'M';
             } elseif ($postData['account']['gender'] == '0') {
                 $params['gender'] = 'F';
             }
         }
         $connection = Mage::getSingleton('core/resource');
         $readConnection = $connection->getConnection('core_read');
         $tableName = $connection->getTableName('lr_sociallogin');
         $query = "select sociallogin_id, uid from {$tableName} where entity_id= '" . $postData['customer_id'] . "'";
         $result = $readConnection->query($query)->fetch();
         if (isset($result['sociallogin_id']) && !empty($result['sociallogin_id'])) {
             //Code for password changing
             if (isset($postData['account']['new_password']) && !empty($postData['account']['new_password'])) {
                 $accountAPI = new LoginRadiusSDK\CustomerRegistration\AccountAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
                 $getRaasProfile = $accountAPI->getAccounts($result['uid']);
                 $checkProviderStatus = '';
                 foreach ($getRaasProfile as $key => $value) {
                     if ($value->Provider == 'RAAS') {
                         $checkProviderStatus = 'true';
                     }
                 }
                 if ($checkProviderStatus == 'true') {
                     if ($postData['account']['new_password'] == 'auto') {
                         $forgotPassDomain = Mage::getBaseUrl() . 'customerregistration/index/verification/';
                         try {
                             $rsetPasswordUrl = 'https://api.loginradius.com/raas/client/password/forgot?apikey=' . $activationBlockObj->apiKey() . '&emailid=' . $postData['account']['email'] . '&resetpasswordurl=' . $forgotPassDomain;
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                         $result = LoginRadiusSDK\LoginRadius::apiClient($rsetPasswordUrl, FALSE, array('output_format' => 'json'));
                     } else {
                         try {
                             $accountAPI->setPassword(trim($result['uid']), trim($postData['account']['new_password']));
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                     }
                 } else {
                     if ($postData['account']['new_password'] == 'auto') {
                         $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_-=?";
                         try {
                             $data = array('accountid' => trim($result['uid']), 'emailid' => trim($postData['account']['email']), 'password' => substr(str_shuffle($chars), 0, 8));
                             $res = $accountAPI->createUserRegistrationProfile($data);
                             try {
                                 $forgotPassDomain = Mage::getBaseUrl() . 'customerregistration/index/verification/';
                                 try {
                                     $rsetPasswordUrl = 'https://api.loginradius.com/raas/client/password/forgot?apikey=' . $activationBlockObj->apiKey() . '&emailid=' . $postData['account']['email'] . '&resetpasswordurl=' . $forgotPassDomain;
                                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                                     Mage::throwException($e->getErrorResponse()->description);
                                 }
                                 $result = LoginRadiusSDK\LoginRadius::apiClient($rsetPasswordUrl, FALSE, array('output_format' => 'json'));
                             } catch (LoginRadiusSDK\LoginRadiusException $e) {
                                 Mage::throwException($e->getErrorResponse()->description);
                             }
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                     } else {
                         try {
                             $data = array('accountid' => trim($result['uid']), 'emailid' => trim($postData['account']['email']), 'password' => trim($postData['account']['new_password']));
                             $res = $accountAPI->createUserRegistrationProfile($data);
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                     }
                 }
             }
             $connectionDb = Mage::getSingleton('core/resource');
             $readConnectionDb = $connection->getConnection('core_read');
             $tableNameCustomer = $connection->getTableName('customer_entity');
             $queryCustomer = "select email from {$tableNameCustomer} where entity_id= '" . $postData['customer_id'] . "'";
             $resultCustomer = $readConnectionDb->query($queryCustomer)->fetch();
             if ($postData['account']['email'] != $resultCustomer["email"]) {
                 $accountAPI = new LoginRadiusSDK\CustomerRegistration\AccountAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
                 /* Adding New Email by Add/Remove Email Api */
                 $addEmailData = array('EmailId' => $postData['account']['email'], 'EmailType' => 'Primary');
                 try {
                     $addEmail = $accountAPI->userAdditionalEmail($result['uid'], 'add', $addEmailData);
                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                     if (isset($e->getErrorResponse()->description)) {
                         /* Getting Raas Profile By User Profile by UID Api */
                         $getRaasProfile = $accountAPI->getAccounts($result['uid']);
                         $providerStatus = '';
                         foreach ($getRaasProfile as $key => $value) {
                             if ($value->Provider == 'RAAS') {
                                 $providerStatus = 'true';
                             }
                         }
                         if ($providerStatus == 'true') {
                             $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                             Mage::throwException($errorDescription);
                         } else {
                             Mage::throwException('Please Set Password then change the email id.');
                         }
                     }
                     return;
                 }
                 if (isset($addEmail->isPosted) && $addEmail->isPosted == 'true') {
                     /* Removing Old Email by Add/Remove Email Api */
                     $removeEmailData = array('EmailId' => $resultCustomer["email"], 'EmailType' => 'Primary');
                     try {
                         $removeEmail = $accountAPI->userAdditionalEmail($result['uid'], 'remove', $removeEmailData);
                     } catch (LoginRadiusSDK\LoginRadiusException $e) {
                         Mage::throwException($e->getErrorResponse()->description);
                         return;
                     }
                 }
             }
             //                if(empty($postData['account']['new_password']) || $postData['account']['new_password'] != 'auto'){
             //
             //
             //                    try {
             //                        $customer = Mage::getSingleton("customer/session")->getCustomer();
             //
             //
             //                   $userAPI->edit($result['sociallogin_id'], $params);
             //
             //                } catch (LoginRadiusSDK\LoginRadiusException $e) {
             //
             //                    Mage::throwException($e->getErrorResponse()->description);
             //                    return;
             //                }
             //                }
         }
     }
 }