<?php

class ControllerAccountSocialconnect extends Controller {

    private $error = array();

    public function index() {

        if ($this->customer->isLogged()) {
            if (isset($this->session->data['redirect'])) {
                $this->response->redirect($this->session->data['redirect']);
            } else {
                $this->response->redirect($this->url->link('account/account', '', 'SSL'));
            }
        }

        $this->language->load('module/socialconnect');

        if (!isset($this->socialconnect)) {
            require_once(DIR_SYSTEM . 'vendor/facebook-sdk/autoload.php');

            $this->socialconnect = new Facebook\Facebook([
                'app_id' => $this->config->get('socialconnect_apikey'),
                'app_secret' => $this->config->get('socialconnect_apisecret'),
                'default_graph_version' => 'v2.4',
            ]);
        }

        $_SERVER_CLEANED = $_SERVER;
        $_SERVER = $this->clean_decode($_SERVER);

        $helper = $this->socialconnect->getRedirectLoginHelper($this->url->link('account/socialconnect', '', 'SSL'));

        try {
            $accessToken = $helper->getAccessToken();
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error  
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {

            // When validation fails or other local issues  
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        if (!isset($accessToken)) {
            if ($helper->getError()) {
                header('HTTP/1.0 401 Unauthorized');
                echo "Error: " . $helper->getError() . "\n";
                echo "Error Code: " . $helper->getErrorCode() . "\n";
                echo "Error Reason: " . $helper->getErrorReason() . "\n";
                echo "Error Description: " . $helper->getErrorDescription() . "\n";
            } else {
                header('HTTP/1.0 400 Bad Request');
                $this->response->redirect($this->url->link('account/account', '', 'SSL'));
            }
            exit;
        }

        // The OAuth 2.0 client handler helps us manage access tokens  
        $oAuth2Client = $this->socialconnect->getOAuth2Client();

        // Get the access token metadata from /debug_token  
        $tokenMetadata = $oAuth2Client->debugToken($accessToken);

        // If you know the user ID this access token belongs to, you can validate it here  
        // $tokenMetadata->validateUserId('123');  
        $tokenMetadata->validateExpiration();

        $this->session->data['fb_access_token'] = (string) $accessToken;

        try {
            // Returns a `Facebook\FacebookResponse` object
            $response = $this->socialconnect->get('/me?fields=id,name,email', $accessToken);
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        $fbuser_profile = $response->getGraphUser();

        $_SERVER = $_SERVER_CLEANED;


        if (isset($fbuser_profile['id']) && isset($fbuser_profile['email']) && isset($fbuser_profile['name'])) {
            $this->load->model('account/customer');
			$this->load->model('account/uyekayit');

            $email = $fbuser_profile['email'];
            $password = $this->get_password($fbuser_profile['id'], $email);

            if ($this->customer->login($email, $password)) {
                if (isset($this->session->data['redirect'])) {
                    $this->response->redirect($this->session->data['redirect']);
                } else {
                    $this->response->redirect($this->url->link('account/account', '', 'SSL'));
                }
            }

            $email_query = $this->db->query("SELECT `email` FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(strtolower($email)) . "'");

            if ($email_query->num_rows) {
                $this->model_account_customer->editPassword($email, $password);
                if ($this->customer->login($email, $password)) {
                    if (isset($this->session->data['redirect'])) {
                        $this->response->redirect($this->session->data['redirect']);
                    } else {
                        $this->response->redirect($this->url->link('account/account', '', 'SSL'));
                    }
                }
            } else {
                $config_customer_approval = $this->config->get('config_customer_approval');
                $this->config->set('config_customer_approval', 0);

                $this->request->post['email'] = $email;

                $add_data = array();
                $add_data['email'] = $fbuser_profile['email'];
                $add_data['password'] = $password;
                $add_data['firstname'] = isset($fbuser_profile['name']) ? $fbuser_profile['name'] : '';
                $add_data['lastname'] = '';
                $add_data['fax'] = '';
                $add_data['telephone'] = '';
                $add_data['company'] = '';
                $add_data['address_1'] = '';
                $add_data['address_2'] = '';
                $add_data['city'] = '';
                $add_data['postcode'] = '';
                $add_data['country_id'] = 0;
                $add_data['zone_id'] = 0;
                $add_data['nationality'] = '';
                $add_data['income'] = '';

                $this->model_account_uyekayit->addCustomer($add_data);
                $this->config->set('config_customer_approval', $config_customer_approval);

                if ($this->customer->login($email, $password)) {
                    unset($this->session->data['guest']);
                    $this->response->redirect($this->url->link('account/success'));
                }
            }
        }

        if (isset($this->session->data['redirect'])) {
            $this->response->redirect($this->session->data['redirect']);
        } else {
            $this->response->redirect($this->url->link('account/account', '', 'SSL'));
        }
    }

    public function google() {

        if ($this->customer->isLogged()) {
            if (isset($this->session->data['redirect'])) {
                $this->response->redirect($this->session->data['redirect']);
            } else {
                $this->response->redirect($this->url->link('account/account', '', 'SSL'));
            }
        }

        $google_client_id = $this->config->get('socialconnect_client_id');
        $google_client_secret = $this->config->get('socialconnect_client_secret');
        $google_redirect_url = $this->url->link('account/socialconnect/google', '', 'SSL'); //path to your script
        $google_developer_key = $this->config->get('socialconnect_developer_key');

        require_once(DIR_SYSTEM . 'vendor/google/Google_Client.php');
        require_once(DIR_SYSTEM . 'vendor/google/contrib/Google_Oauth2Service.php');
        $gClient = new Google_Client();

        $gClient->setApplicationName('Login to Quick Mazad');
        $gClient->setClientId($google_client_id);
        $gClient->setClientSecret($google_client_secret);
        $gClient->setRedirectUri($google_redirect_url);
        $gClient->setDeveloperKey($google_developer_key);

        $google_oauthV2 = new Google_Oauth2Service($gClient);

        if (isset($this->request->get['code'])) {
            $gClient->authenticate($this->request->get['code']);
            $this->session->data['token'] = $gClient->getAccessToken();


            if (isset($this->session->data['token'])) {
                $gClient->setAccessToken($this->session->data['token']);
            }

            if ($gClient->getAccessToken()) {
                $this->load->model('account/customer');
				$this->load->model('account/uyekayit');

                $user = $google_oauthV2->userinfo->get();
                $user_id = $user['id'];
                $user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
                $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);

                $password = $this->get_password($user_id, $email);

                if ($this->customer->login($email, $password)) {
                    if (isset($this->session->data['redirect'])) {
                        $this->response->redirect($this->session->data['redirect']);
                    } else {
                        $this->response->redirect($this->url->link('account/account', '', 'SSL'));
                    }
                }

                $email_query = $this->db->query("SELECT `email` FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(strtolower($email)) . "'");

                if ($email_query->num_rows) {
                    $this->model_account_customer->editPassword($email, $password);
                    if ($this->customer->login($email, $password)) {
                        if (isset($this->session->data['redirect'])) {
                            $this->response->redirect($this->session->data['redirect']);
                        } else {
                            $this->response->redirect($this->url->link('account/account', '', 'SSL'));
                        }
                    }
                } else {
                    $config_customer_approval = $this->config->get('config_customer_approval');
                    $this->config->set('config_customer_approval', 0);

                    $add_data = array();
                    $add_data['email'] = $email;
                    $add_data['password'] = $password;
                    $add_data['firstname'] = isset($user_name) ? $user_name : '';
                    $add_data['lastname'] = '';
                    $add_data['fax'] = '';
                    $add_data['telephone'] = '';
                    $add_data['company'] = '';
                    $add_data['address_1'] = '';
                    $add_data['address_2'] = '';
                    $add_data['city'] = '';
                    $add_data['postcode'] = '';
                    $add_data['country_id'] = 0;
                    $add_data['zone_id'] = 0;
                    $add_data['nationality'] = '';
                    $add_data['income'] = '';

                    $this->model_account_customer->addCustomer($add_data);
                    $this->config->set('config_customer_approval', $config_customer_approval);

                    if ($this->customer->login($email, $password)) {
                        unset($this->session->data['guest']);
                        $this->response->redirect($this->url->link('account/success'));
                    }
                }

                $this->session->data['token'] = $gClient->getAccessToken();
            }
        } else {
            if (isset($this->session->data['redirect'])) {
                $this->response->redirect($this->session->data['redirect']);
            } else {
                $this->response->redirect($this->url->link('account/account', '', 'SSL'));
            }
        }
    }

    private function get_password($str, $email) {
        $password = $this->config->get('socialconnect_pwdsecret') ? $this->config->get('socialconnect_pwdsecret') : 'fb';
        $password.=substr($email, 0, 3) . substr($str, 0, 3) . substr($email, -3) . substr($str, -3);
        return strtolower($password);
    }

    private function clean_decode($data) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                unset($data[$key]);
                $data[$this->clean_decode($key)] = $this->clean_decode($value);
            }
        } else {
            $data = htmlspecialchars_decode($data, ENT_COMPAT);
        }

        return $data;
    }

}

?>