<?php

use Hybridauth\Provider\Facebook;
use Hybridauth\Provider\Twitter;
use GuzzleHttp\Client;
use DirkGroenen\Pinterest\Pinterest;

class Auth
{

    private $CI;
    private $response;
    private $isRequest;

    public function __construct($params = [])
    {
        $this->CI = get_instance();
    }

    public function setIsRequest($isRequest)
    {
        $this->isRequest = $isRequest;
        return $this;
    }

    public function getResponse()
    {
        return $this->response;
    }

    public function auth($name = '')
    {
        $this->CI->config->load('social');
        $method = $name ? $name : $this->CI->input->post('auth');
        $method = $method ? $method : 'crossmap';
        $this->$method();
    }

    private function crossmap()
    {
        $this->response = ['code' => 404];
        $query = $this->CI->db->from('cm_user')
            ->where('userName', $this->CI->input->post('userName'))
            ->where('password', md5($this->CI->input->post('userPasswd')))->get();        
        if ($query->num_rows() == 1) {
            $this->CI->load->library('session');
            $user = [
                'userName' => $this->CI->input->post('userName'),
                'userID' => $query->row()->userID
            ];
            $this->CI->session->set_userdata('auth', json_encode($user));
            $this->response = [
                'code' => 200
            ];
        }else if($query->num_rows() > 1){
            log_message('debug', 'duplicated users');
            $this->response = [
                'code' => 400
            ];
        }else {
            $this->response = [
                'code' => 404
            ];
        }
    }

    private function kakao()
    {
        if ($this->isRequest) {
            redirect($this->CI->config->item('kakao_base_uri')
                . '/oauth/authorize?client_id='
                . $this->CI->config->item('kakao_app_key')
                . '&redirect_uri='
                . $this->CI->config->item('kakao_redirect_uri')
                . '&response_type=code');
        } else {
            $code = $this->CI->input->get('code');
            $client = new Client();
            try {
                $response = $client->request('POST', $this->CI->config->item('kakao_base_uri') . '/oauth/token', [
                    'form_params' => [
                        'grant_type' => 'authorization_code',
                        'client_id' => $this->CI->config->item('kakao_app_key'),
                        'redirect_uri' => $this->CI->config->item('kakao_redirect_uri'),
                        'code' => $code
                    ]
                ]);
                $response = json_decode($response->getBody());
                $response = $client->request('POST', $this->CI->config->item('kakao_api_base_uri') . '/v2/user/me', [
                    'headers' => [
                        'Authorization' => 'Bearer ' . $response->access_token
                    ],
                    'form_params' => ['property_keys' => ['kakao_account.email', 'kakao_account.age_range', 'kakao_account.birthday', 'kakao_account.gender']]
                ]);
                $userProfile = $response->getBody();
                log_mesage('info', $userProfile);
                $this->connected('kakao', $userProfile);
            } catch (GuzzleHttp\Exception\ClientException $e) {
                log_message('debug', 'Kakao SNS login :: Oops, we ran into an issue! ClientException');
            } catch (GuzzleHttp\Exception\RequestException $e) {
                log_message('debug', 'Kakao SNS login :: Oops, we ran into an issue! RequestException');
            }
        }
    }

    private function facebook()
    {
        $config = [
            'callback' => $this->CI->config->item('facebook_redirect_uri'),
            'keys' => [
                'id'     => $this->CI->config->item('facebook_app_key'), //Required: your Facebook application id
                'secret' => $this->CI->config->item('facebook_app_secret')  //Required: your Facebook application secret 
            ]
        ];
        if ($this->isRequest) {
            try {
                $adapter = new Facebook($config);
                $adapter->authenticate();
                $isConnected = $adapter->isConnected();
                $userProfile = $adapter->getUserProfile();
                //Disconnect the adapter 
                $adapter->disconnect();
                log_mesage('info', print_r($userProfile, ture));
                $this->connected('facebook', $userProfile);
            } catch (\Exception $e) {
                echo 'Oops, we ran into an issue! ' . $e->getMessage();
            }
        }
    }

    private function twitter()
    {
        $config = [
            'callback' => 'https://local.cmap.co.kr/oauth/twitter',
            'keys' => [
                'key' => $this->CI->config->item('twitter_app_key'),
                'secret' => $this->CI->config->item('twitter_app_secret')
            ]
        ];
        try {
            $adapter = new Twitter($config);
            $adapter->authenticate();
            $accessToken = $adapter->getAccessToken();
            $userProfile = $adapter->getUserProfile();
            $adapter->disconnect();
            // $apiResponse = $twitter->apiRequest('account/settings.json');
            log_mesage('info', print_r($userProfile, ture));
            $this->connected('twitter', $userProfile);
        } catch (\Exception $e) {
            log_message('debug', 'Twitter SNS login :: Oops, we ran into an issue!');
            log_message('debug', $e->getMessage());
        }
    }

    private function pinterest()
    {
        if ($this->isRequest) {
            try {
                $pinterest = new Pinterest($this->CI->config->item('pinterest_app_key'), $this->CI->config->item('pinterest_app_secret'));
                $loginurl = $pinterest->auth->getLoginUrl($this->CI->config->item('pinterest_redirect_uri'), array('read_public'));
                redirect($loginurl);
            } catch (\Exception $e) {
                log_message('debug', 'Pinterest SNS login :: Oops, we ran into an issue!');
                log_message('debug', $e->getMessage());
            }
        } else {
            $userProfile = '';
            $this->connected('pinterest', $userProfile);
        }
    }

    private function naver()
    {
        if ($this->isRequest) {
            $url = 'https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id='
                . $this->CI->config->item('naver_app_key')
                . '&redirect_uri='
                . $this->CI->config->item('naver_redirect_uri')
                . '&state='
                . $this->CI->config->item('naver_app_state');
            redirect($url);
        }
    }

    private function connected($name, $userProfile)
    {
        $this->CI->library('session');
        $username = $this->register($name, $userProfile);
        if ($this->login($username, '')) { }
    }

    private function register($name, $userProfile)
    {
        return 'username';
    }

    public function login($username, $password)
    {
        $query = $this->db->where("userName", $username)->where("password", $password)->get("cm_user");
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $rows) {
                $data = array(
                    'userID' => $rows->userID,
                    'userName' => $rows->userName,
                    'logged_in' => true,
                );
                $this->session->set_userdata($data);
                return true;
            }
        } else {
            return false;
        }
    }
}
