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

$session = $_REQUEST["session"];
$msg = $_REQUEST["msg"];
//$class = $_REQUEST["class"];
$set_title = $_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';

$allowed = get_notification_status($set_title, $db);

$aryData = array("content" => $msg, "type" => $set_title, "session" => $session, "allowed" => $allowed);
$insert_resp = $db->insertAry("tbl_notification", $aryData);

$firebase = new Firebase();
$push = new Push();
$tokenlist=$db->getRows("SELECT idno,name,fcm_token from student where  session='$session' and status='1' ");
//echo $ss="SELECT name,fcm_token from student where class='$class' and session='$session' and status='1' ";


if($allowed == 0) {
    foreach ($tokenlist as $value) {
        //$sql = "SELECT name,fcm_token FROM TABLE WHERE id = '$value'";

        //$tokenlist = mysql_query("SELECT name,fcm_token from student where class='$x_value' and session='$session' and status='1' ");

        // $retval = mysqli_query($con,$sql);


        //if($tokenlist){

        $stu_id = $value['idno'];
        $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['stu_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);
        }


        //}

    }
}

function get_notification_status($title, $db){

    $notification_controls = $db->getRow("SELECT * FROM notification_control WHERE id = '1' ");

    if ($notification_controls != ""){

        switch ($title) {
            case "Gallery" : return (isset($notification_controls['gallery']) ? $notification_controls['gallery'] : 0);
            //case "blue":return 3;
            default: return 0;
        }

    }else{
        return 0;
    }

}