<?php

include("../db.php");


$session = $_REQUEST["session"];
$msg = "Leave application received";//$_REQUEST["msg"];
$set_title = "leave";// $_REQUEST["title"];

// Enabling error reporting
error_reporting(-1);
ini_set('display_errors', 'On');

//require_once  __DIR__.'/firebase/firebase.php';
require_once  __DIR__.'/firebase/push.php';

//$firebase = new Firebase();
$push = new Push();

$tokenlist = $db->getRows("SELECT * from admin WHERE session='$session'");

$result_arr = array();

foreach ($tokenlist as $value) {


    $stu_id =  $value['id'];
    $target_user_name =  $value['name'];
    $fb_token =  $value['fcm_token'];

    if (strlen($fb_token) > 0) {

        // optional payload
        $payload = array();
        $payload['name'] = $target_user_name;
        $payload['msg'] = $msg; // whether to include to image or not
        $payload['admin_id'] = $stu_id;
        $include_image = TRUE;
        $push->setTitle($set_title);
        $push->setMessage($msg);
        if ($include_image) {
            $push->setImage('https://api.androidhive.info/images/minion.jpg');
        } else {
            $push->setImage('');
        }
        $push->setIsBackground(FALSE);
        $push->setPayload($payload);
        $json = '';
        $response = '';
        $json = $push->getPush();




        // $response = $firebase->send($fb_token, $json);

        $fields = array(
            'to' => $fb_token,
            'data' => $json,
        );



        $SERVER_KEY=$db->getVal("select firebase_server_key from tbl_info where id='1'");


        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';

        $headers = array(
            'Authorization: key=' . $SERVER_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        // return $result;







        array_push($result_arr,$stu_id.$result);

    }


}

echo json_encode($result_arr);

?>