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

require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/Format.php';

use Restserver\Libraries\REST_Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

class Api_main_activity_firebase extends REST_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper(['jwt', 'authorization']);
		$this->methods['index_post']['limit_token_firebase'] = 1;
	}


	public function index_post()
	{
		date_default_timezone_set("Asia/Jakarta");
		$mst_user_kode =  $this->mst_user_kode();
		$mst_user_firebase =  $this->mst_user_firebase();

		//UPDATE USER
		$update = $this->db->query("UPDATE tbl_mst_user set mst_user_firebase='$mst_user_firebase' WHERE mst_user_kode='$mst_user_kode'");

		if ($update) {
			//KIRIM NOTIFIKASI
			$this->firebase_notification($mst_user_firebase);

			$sess["status"] = "001";
			$sess["pesan"] = "Update berhasil";
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
		} else {
			$sess["status"] = "002";
			$sess["pesan"] = "Update Gagal";
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
		}
	}

	private function firebase_notification($mst_user_firebase)
	{
		$fcmUrl = 'https://fcm.googleapis.com/fcm/send';

		$title = "Arifah Pulsa";
		$body =  "Hai, selamat datang di Arifah Pulsa, lebih dari 2.000 produk yang bisa kamu jual ke pelanggan dengan harga lebih murah dan cepat";

		$notification = array(
			'type' => 1,
			'title' => $title,
			'body' => $body,
			'click_action' => 'main_activity',
			'sound' => 'default',
			'icon'  => 'ic_notification',
		);

		$fcmNotification = [
			//'registration_ids' => '', 
			'to'        => $mst_user_firebase,
			'data' => $notification,
			'notification' => $notification,
			'priority' => 'high',
			'apns-priority' => '5'
		];

		$headers = [
			'Authorization: key=' . $this->config->item('firebase_key'),
			'Content-Type: application/json'
		];


		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $fcmUrl);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
		$result = curl_exec($ch);
		curl_close($ch);
	}

	private function mst_user_kode()
	{
		$input = decrypt($this->input->post("mst_user_kode", true), $this->config->item('key'));
		$token = AUTHORIZATION::generateToken($input);
		try {
			$data = AUTHORIZATION::validateToken($token);
			if ($data === false) {
				$sess["status"] = "004";
				$sess["pesan"] = $this->config->item('error_parameter');
				$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
				$sess['data'] = array(
					'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
					'value' =>  encrypt(json_encode(array()), $keytoken)
				);
				echo json_encode($sess);
				exit();
			} else {
				return $data;
			}
		} catch (Exception $e) {
			$sess["status"] = "004";
			$sess["pesan"] = $this->config->item('error_parameter');
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
			exit();
		}
	}

	private function mst_user_firebase()
	{
		$input = decrypt($this->input->post("mst_user_firebase", true), $this->config->item('key'));
		$token = AUTHORIZATION::generateToken($input);
		try {
			$data = AUTHORIZATION::validateToken($token);
			if ($data === false) {
				$sess["status"] = "004";
				$sess["pesan"] = $this->config->item('error_parameter');
				$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
				$sess['data'] = array(
					'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
					'value' =>  encrypt(json_encode(array()), $keytoken)
				);
				echo json_encode($sess);
				exit();
			} else {
				return $data;
			}
		} catch (Exception $e) {
			$sess["status"] = "004";
			$sess["pesan"] = $this->config->item('error_parameter');
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
			exit();
		}
	}
}
