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

class Api_digiflazzcallback extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(['jwt', 'authorization']);
    }

    public function index()
    {
        $reqHeaders = $this->input->request_headers();
        $xBodyResponse = file_get_contents('php://input');
        $xIncomingCallbackTokenHeader = $reqHeaders['X-Hub-Signature'];
        $xDigiflazzSignature = 'sha1=' . hash_hmac('sha1', $xBodyResponse, '2sackmg10BW1ffSe3VSYI3tW4cVW7msU3jBr6sizS65qmxu0N');

        if ($xIncomingCallbackTokenHeader == $xDigiflazzSignature) {
            $jsonEncoded = file_get_contents('php://input');
            $json = urldecode($jsonEncoded);
            $obj = json_decode($json, TRUE);
            $data = $obj['data'];
            $status = $data['status'];

            $fcmUrl = 'https://fcm.googleapis.com/fcm/send';
            $pesan =  $data;

            $notification = array(
                'type' => 1,
                'body' => $pesan,
                'title' => 'Callback Digiflazz',
                'click_action' => 'mainactivity',
                'sound' => 'default',
                'icon'  => 'ic_notification',
            );


            $fcmNotification = [
                //'registration_ids' => '', //multple pasca array
                'to'        => 'f1RhJni3QN25Qmtv26-QfE:APA91bGkYYNMZHYXT6IUPXTVvUa38RA7xjRu-qkQZfelE72DHRJUm8kzSxjDnBYMZQYhtevlqCgAh5buCDIyTtdcd-TcK8iUyOd0ZhjxHr9YuPMNUyB0qd8BuQDXQ3yzp9qj1WxzkYoc', //single pasca
                'data' => $notification,
                'notification' => $notification,
                'priority' => 'high',
                'apns-priority' => '5'
            ];



            $headers = [
                'Authorization: key=AAAAnka-4YI:APA91bEnBViu7sdvkHdZLeX3NRP1Ty-tx16WeVGP86aKlq6oCmMw5llwhFQev1xgAPROC2vaTL4f_pqok4J4-bVDyUYOUrm4ce7IXSCuZlyiq5J4Mnnbry49AzJsalCoFcdDUbhusnj7',
                '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);
        } else {
            $sess["status"] = "400";
            $sess["pesan"] = "Token salah";
            $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);
        }
    }

    public function encrypt($input, $key)
    {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = $this->pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = base64_encode($data);
        $data = str_replace("+", "-", $data);
        return $data;
    }

    public function decrypt($sStr, $sKey)
    {
        $sStr = str_replace("-", "+", $sStr);
        $decrypted = mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $sKey,
            base64_decode($sStr),
            MCRYPT_MODE_ECB
        );
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s - 1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }

    private static function pkcs5_pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
}
