<?php defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-Type: text/html; charset=UTF-8");
/**
 * 인클루드 class
 *
 * cm_controller: 부모 Class(CI_Controller 확장한 custome class)
 */
include_once(APPPATH.'core/web/cm_controller.php');
class share extends cm_Controller {

    #---------------------------------------------------------------------------
    # PURPOSE : 트위터 callback url
    # CREATE  :	2018-04-10
    #---------------------------------------------------------------------------
	function fn_twitter_callback_proc() {

	    # Request
        $type               = trim($this->input->get_post('type', TRUE));
        $oauth_token        = trim($this->input->get_post('oauth_token', TRUE));
        $oauth_verifier     = trim($this->input->get_post('oauth_verifier', TRUE));

        $twitter_oauth_token        = $this->session->userdata('Twitter_Oauth_Token');
        $twitter_oauth_token_secret = $this->session->userdata('Twitter_Oauth_Token_Secret');

        $this->session->unset_userdata('Twitter_Oauth_Token');
        $this->session->unset_userdata('Twitter_Oauth_Token_Secret');

        if ($oauth_token != $twitter_oauth_token) {
            gf_alert('트위터 연동에 실패했습니다.', 'self_close');
            exit;
        }

        if($oauth_verifier=='') {
            gf_alert('트위터 연동에 실패했습니다.', 'self_close');
            exit;
        }

        require_once (APPPATH."/inc/twitter_OAuth.php");
        $tmhOAuth = new tmhOAuth();

        // update with the temporary token and secret
        $tmhOAuth->reconfigure(array_merge($tmhOAuth->config, array('token'  => $twitter_oauth_token, 'secret' => $twitter_oauth_token_secret)));
        $code = $tmhOAuth->user_request(array(
                                                'method' => 'POST',
                                                'url' => $tmhOAuth->url('oauth/access_token', ''),
                                                'params' => array('oauth_verifier' => trim($oauth_verifier))
        ));

        if ($code != 200) {
            gf_alert('트위터 연동에 실패했습니다.', 'self_close');
            exit;
        }

        $oauth_creds = $tmhOAuth->extract_params($tmhOAuth->response['response']);

        $tmhOAuth->reconfigure(array_merge($tmhOAuth->config, array(
          'token' =>    $oauth_creds['oauth_token'],
          'secret' =>   $oauth_creds['oauth_token_secret'],
        )));
        $code = $tmhOAuth->user_request(array(
          'url' => $tmhOAuth->url('1.1/account/verify_credentials')
        ));

        $arr_member_data = json_decode($tmhOAuth->response['response'], true);

        if($type=='comment') {
            $social_id      = (string)$arr_member_data['id'];
            $social_name    = $arr_member_data['name'];

            # 로그
            $req_data = array();
            $req_data['social_id']          = $social_id;
            $req_data['name']               = $social_name;
            $req_data['social_type']        = '2';
            $this->load->model('web/m_comment_social_member_log');
            $this->m_comment_social_member_log->comment_social_member_log_insert($req_data);

            $req_data = array();
            $req_data['member_id']          = $social_id;
            $req_data['member_name']        = $social_name;
            $req_data['sns_type_name']      = 'twitter';

            $this->load->library('comm');
            $this->comm->fn_comment_login_proc($req_data);

            # view
            return $this->load->view('/web/comm/social_login', '', true);


        }

    }

    #---------------------------------------------------------------------------
    # PURPOSE : 카카오 callback url
    # CREATE  :	2018-04-10
    #---------------------------------------------------------------------------
	function fn_kakao_callback_proc() {

        # Request
        $code       = trim($this->input->get_post('code', TRUE));
        $state      = trim($this->input->get_post('state', TRUE));

        $SES_RANDOM_STATE          = $this->session->userdata('RANDOM_STATE');
        if($state!=$SES_RANDOM_STATE) {
            gf_alert('카카오계정 연동에 실패했습니다.1', 'self_close');
            exit;
        }

        $CLIENT_ID     = "d9d530edc95295682137fdd37dddc55f";
        $REDIRECT_URI  = WWW_CROSSMAP."/web/share/kakao_callback_proc";
        $TOKEN_API_URL = "https://kauth.kakao.com/oauth/token";

        $params = sprintf( 'grant_type=authorization_code&client_id=%s&redirect_uri=%s&code=%s', $CLIENT_ID, $REDIRECT_URI, $code);
        $opts = array(
            CURLOPT_URL => $TOKEN_API_URL,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSLVERSION => 1, // TLS
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false
         );
        $curlSession = curl_init();
        curl_setopt_array($curlSession, $opts);
        $accessTokenJson = curl_exec($curlSession);
        $status_code = curl_getinfo($curlSession, CURLINFO_HTTP_CODE);
        curl_close($curlSession);

        if($status_code != 200) {
            gf_alert('카카오계정 연동에 실패했습니다.2', 'self_close');
            exit;
        }
        $arr_data = json_decode($accessTokenJson, true);
        $token_expires_date = date("Y-m-d H:i:s", time()+$arr_data['expires_in']);

        $header = "Bearer ".$arr_data['access_token']; // Bearer 다음에 공백 추가
        $url = "https://kapi.kakao.com/v1/user/me";
        $is_post = false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $headers = array();
        $headers[] = "Authorization: ".$header;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec ($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close ($ch);
        if($status_code != 200) {
            gf_alert('카카오계정 연동에 실패했습니다.3', 'self_close');
            exit;
        }


        $arr_member_data = json_decode($response, true);
        if(isset($arr_member_data['id'])==true){

            $social_id      = (string)$arr_member_data['id'];
            $social_name    = $arr_member_data['properties']['nickname'];

            # 로그
            $req_data = array();
            $req_data['social_id']          = $social_id;
            $req_data['name']               = $social_name;
            $req_data['social_type']        = '3';
            $this->load->model('web/m_comment_social_member_log');
            $this->m_comment_social_member_log->comment_social_member_log_insert($req_data);

            $req_data = array();
            $req_data['member_id']          = $social_id;
            $req_data['member_name']        = $social_name;
            $req_data['sns_type_name']      = 'kakao';

            $this->load->library('comm');
            $this->comm->fn_comment_login_proc($req_data);

            # view
            return $this->load->view('/web/comm/social_login', '', true);

        }


    }


    #---------------------------------------------------------------------------
    # PURPOSE : 네이버 callback url
    # CREATE  :	2018-04-10
    #---------------------------------------------------------------------------
	function fn_naver_callback_proc() {

        # Request
        $code       = trim($this->input->get_post('code', TRUE));
        $state      = trim($this->input->get_post('state', TRUE));
        $error      = trim($this->input->get_post('error', TRUE));

        if($error!='') {
            gf_alert('네이버계정 연동에 실패했습니다.1', 'self_close');
            exit;
        }

        $SES_RANDOM_STATE          = $this->session->userdata('RANDOM_STATE');
        if($state!=$SES_RANDOM_STATE) {
            gf_alert('네이버계정 연동에 실패했습니다.2', 'self_close');
            exit;
        }

        $client_id = "cNiinVHYsygxVKF4FOtw";
        $client_secret = "nrTOCTFNUq";

        $redirectURI = urlencode(WWW_CROSSMAP."/web/share/naver_callback_proc");
        $url = "https://nid.naver.com/oauth2.0/token?grant_type=authorization_code&client_id=".$client_id."&client_secret=".$client_secret."&redirect_uri=".$redirectURI."&code=".$code."&state=".$state;
        $is_post = false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec ($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close ($ch);
        if($status_code != 200) {
            gf_alert('네이버계정 연동에 실패했습니다.3', 'self_close');
            exit;
        }
        $arr_data = json_decode($response, true);
        $token_expires_date = date("Y-m-d H:i:s", time()+$arr_data['expires_in']);


        $header = "Bearer ".$arr_data['access_token']; // Bearer 다음에 공백 추가
        $url = "https://openapi.naver.com/v1/nid/me";
        $is_post = false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $headers = array();
        $headers[] = "Authorization: ".$header;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec ($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close ($ch);
        if($status_code != 200) {
            gf_alert('네이버계정 연동에 실패했습니다.', 'self_close');
            exit;
        }


        $arr_member_data = json_decode($response, true);
        if($arr_member_data['resultcode'] == '00'){
            
            if(!$arr_member_data['response']['name']) {
                gf_alert('네이버계정 연동에 실패했습니다.(필수항목 : 이름)', 'self_close');
                exit;
            }

            $social_id      = $arr_member_data['response']['id'];
            $social_name    = $arr_member_data['response']['name'];

            # 로그
            $req_data = array();
            $req_data['social_id']          = $social_id;
            $req_data['name']               = $social_name;
            $req_data['social_type']        = '4';
            $this->load->model('web/m_comment_social_member_log');
            $this->m_comment_social_member_log->comment_social_member_log_insert($req_data);

            $req_data = array();
            $req_data['member_id']          = $social_id;
            $req_data['member_name']        = $social_name;
            $req_data['sns_type_name']      = 'naver';

            $this->load->library('comm');
            $this->comm->fn_comment_login_proc($req_data);

            $this->session->unset_userdata('RANDOM_STATE');

            # view
            return $this->load->view('/web/comm/social_login', '', true);


        }

    }

    #---------------------------------------------------------------------------
    # PURPOSE : 페이스북 로그인 url
    # CREATE  :	2018-04-10
    #---------------------------------------------------------------------------
	function fn_ajax_facebook_login_proc() {
        # Request
        $id       = trim($this->input->get_post('id', TRUE));
        $name     = trim($this->input->get_post('name', TRUE));

        $return_data['result'] = array('code' => '9999');
        if($id!='') {

            $social_id      = $id;
            $social_name    = $name;

            # 로그
            $req_data = array();
            $req_data['social_id']          = $social_id;
            $req_data['name']               = $social_name;
            $req_data['social_type']        = '1';
            $this->load->model('web/m_comment_social_member_log');
            $this->m_comment_social_member_log->comment_social_member_log_insert($req_data);

            $req_data = array();
            $req_data['member_id']          = $social_id;
            $req_data['member_name']        = $social_name;
            $req_data['sns_type_name']      = 'facebook';

            $this->load->library('comm');
            $this->comm->fn_comment_login_proc($req_data);

            $return_data['result'] = array('code' => '0000');

        }

        # view
        return $this->load->view('/web/comm/result_json', $return_data);


    }




}



?>