<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Fcm_library {
	function __construct() {
		$this->ci = & get_instance();
        $this->ci->load->config('fcm');
	}
	
    function send($sendto='topic', $topic='all', $user_id, $token, $title, $body) {
        if($sendto=='token' && !$token) return false;
		if(!$title || !$body) return false;

        //토큰값 가져오기
        $google_api_key = $this->ci->config->item('fcm_api_key');

        //전송하기
        $url = 'https://fcm.googleapis.com/fcm/send';
        $fields = array(
            'priority'          => 'high',
            'data'              => json_decode($body,true),//array로 넘겨야 함
            'content_available' => true
        );

        //iOS용 notification을 추가. 백그라운드 상태에서 보이기위함
        $fields['notification'] = array(
            'title'             => $title,
            'body'              => $body,
            'content_available' => true
        );

		//전송대상
		if($sendto=='topic') {
			$fields['to'] = "/topics/".$topic;
		} else {
			$fields['to'] = $token;
		}


        $headers = array(
            'Authorization:key=' . $google_api_key,
            'Content-Type: application/json'
        );
        //print_r($fields);

        //CURL 로 전송
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $response = curl_exec($ch);
		
        if ($response === false) {
            $response = curl_error($ch);
        }

        curl_close($ch);

		//echo $response;

		$this->log(
			$sendto
			, $topic
			, $user_id
			, $token
			, $title
			, $body
			, $response
			);
		
        return $response;
    }

	function log($sendto, $topic, $user_id, $user_token, $title, $message, $response) {
		
		//응답값 처리
		$response_arr = json_decode($response, true);

		//응답값 받아서 DB에 넣기
		$updatedate = array(
			'sendto'		=>	$sendto,
			'topic'			=>	$topic,
			'user_id'		=>	$user_id,
			'user_token'	=>	$user_token,
			'title'			=>	$title,
			'message'		=>	$message,
			'message_id'	=>	(element('multicast_id',$response_arr)) ? element('multicast_id',$response_arr) : element('message_id',$response_arr),
			'success'		=>	element('success', $response_arr),
			'failure'		=>	element('failure', $response_arr),
			'response'		=>	$response,
			'regdate'		=>	date('Y-m-d H:i:s')
		);
		$this->ci->db->insert('fcm_result', $updatedate);
	}

	//회원에 토큰등록
	function update_token($user_id, $user_fcm_token) {
		if(!$user_id)	return false;
		if(!$user_fcm_token)	return false;

		//기존 토큰 등록된 아이디는 없애기
		$updatedata = array('user_fcm_token'=>'');
		$this->ci->db->update('user', $updatedata, array('user_fcm_token'=>$user_fcm_token));

		//토큰 등록
		$updatedata = array('user_fcm_token'=>$user_fcm_token);
		$this->ci->db->update('user', $updatedata, array('user_id'=>$user_id));

		return true;
	}

}