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

$url = "https://fcm.googleapis.com/fcm/send";
$title = "Classroom";

$topicName = $_REQUEST['topic'];
$message = $_REQUEST['message'];
$hasSection = $_REQUEST['has_section'];
$section = $_REQUEST['section'];

$senderId = $_REQUEST['sender_id'];

$sectionArray = json_decode($section, true);
$topicArray = json_decode($topicName, true);

$allowed = 0;
$notification_controls = $db->getRow("SELECT * FROM notification_control WHERE id = '1' ");
if ($notification_controls != "" && isset($notification_controls['chat'])){
    $allowed = $notification_controls['chat'];
}

if ($allowed == 0) {

    $SERVER_KEY = $db->getVal("select firebase_server_key from tbl_info where id='1'");
    if (!empty($SERVER_KEY)) {
        foreach ($topicArray as $item) {
            sendNotification('/topics/' . $item, $SERVER_KEY, $message, $sectionArray, $hasSection, $senderId);
        }
    }

}

//send to single user with token

// $user_fcm_token = $db->getVal("SELECT fcm_token FROM staff WHERE idno='$user_id'");
// sendNotification($user_fcm_token,$SERVER_KEY, "message_meta data passed from server");

function sendNotification($token, $serverKey, $body, $sectionArray, $hasSection, $senderId)
{
    global $url;
    global $title;

    $time_mili = round(microtime(true) * 1000);

    //$payload = array('title' =>$title , 'message' => $body , 'time_stamp'=>$time_mili, 'is_group_message' => "1", "has_section"=>$hasSection, "section_list"=>$sectionArray, "sender_id"=>$senderId);

    $payload = array();
    $payload['data']['title'] = $title;
    $payload['data']['message'] = $body;
    $payload['data']['time_stamp'] = $time_mili;

    $payload['data']['is_group_message'] = "1";
    $payload['data']['has_section'] = $hasSection;
    $payload['data']['section_list'] = $sectionArray;
    $payload['data']['sender_id'] = $senderId;

    $arrayToSend = array('to' => $token, 'data' => $payload, 'priority' => 'high');
    $json = json_encode($arrayToSend);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key=' . $serverKey;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    //Send the request
    $response = curl_exec($ch);
    //Close request
    if ($response === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
}