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

if ( ! function_exists('onesignal_api'))
{
    function onesignal_api($in)
    {
        $OneSignalUrl = "https://onesignal.com/api/v1/notifications";
        $OneSignalApp = "13755f98-ec69-45fd-a2f1-d2166afcaa51";
        $OneSignalKey = "Mjk1OGNiM2ItZWU0ZC00NGJhLTg3YTMtOWMwNzZmZWEwMzBj";

        $out = array();
        $out['status'] = 'Unhandled error';
        $out['result'] = -1;
        $out['data'] = null;
        
        // https://documentation.onesignal.com/reference/create-notification
        $fields = array(
           'app_id' => $OneSignalApp,
           'included_segments' => array($in["included_segments"]), // "Subscribed Users",
           /* 'data' => array("foo" => "bar"), */
           'contents' => array(
                "en" => $in["message"]
            )
        );

        $fields = json_encode($fields);
        //print("\nJSON sent:\n");
        //print($fields);

        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $OneSignalUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'Authorization: Basic "'.$OneSignalKey."'"));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $response = curl_exec($ch);
        curl_close($ch);

        //echo "<pre>${response}</pre>";

        if ($response != "") {
            $data = json_decode($response,true);
            if (is_array($data) && count($data)>0) {
                $out["data"] = $data;
                if (array_key_exists("recipients",$data) && $data["recipients"] > 0 
                && (!array_key_exists("errors",$data) || count($data["errors"]) < 1)) {
                    $out["status"] = "Sent to ".$data["recipients"]." recipeint(s)";
                    $out["result"] = 1;
                } else {
                    $out["status"] = "errors: ".
                    (array_key_exists("errors",$data)?json_encode($data["errors"]):"unknown error");
                }
            } else {
                $out["status"] = "Invalid OneSignal API response: ".$response;
            }
        } else {
            $out["status"] = "Missing OneSignal API response";
        }
        return $out;
    }
}
