<?php
require_once("/home/fundbridge/crons.ballng.com/db.php");

function getTokens($uid){
    global $conn;
    $user = mysqli_query($conn, "select id from users where uid = '$uid' limit 1");
    $tokens = array();
    if(mysqli_num_rows($user) > 0){
        $tokens = array_values(array_unique(array_map(function($token){
                return $token["token"];
            } ,$conn->query("SELECT token FROM `devices` where uid = '$uid' and status = 1")->fetch_all(MYSQLI_ASSOC))));
    }
    return $tokens;
}

function sendNotice($uid,$data){
    if($uid == ""){
        // send to all
        $data = array('title' => $data["data"]["title"], "message"=>$data["data"]["message"], "image"=>$data["data"]["image"], "all"=>"ALL","tag"=>"messaging","data"=>json_encode($data),"link"=>"https://ballng.com");
    }else{
        $devices = is_array($uid) ? $uid : (strlen($uid) == 6 ? getTokens($uid) : array($uid));
        $devices = json_encode($devices);
        $data = array('title' =>  $data["data"]["title"], "message"=>$data["data"]["message"], "image"=>$data["data"]["image"], "users"=>$devices,"tag"=>"messaging","data"=>json_encode($data),"link"=>"");
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://crons.ballng.com/notifications.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    print_r($res);
    curl_close ($ch);
}

$notifications = mysqli_query($conn, "select * from app where status = 1 limit 1");
while($notice = mysqli_fetch_assoc($notifications)){
    $rcp = intval($notice['type']);
    $data = array("type"=>"NOTIFY", "data"=> array("title"=>$notice["title"],"message"=>$notice["message"],"image"=>$notice["photo"],"payload"=> json_encode(array("data_type"=>"LINK", "id"=>"https://ballng.com"))));
    
    if($rcp == 0){
        //specific user
        if($notice["recipients"] != ""){
            $devices = array();
            $rcps = json_decode($notice["recipients"], true);
            foreach($rcps as $n){
                $devices = array_unique(array_merge($devices,getTokens($n)), SORT_REGULAR);
            }
            sendNotice($devices,$data);
        }
    }else{
        //all users
        sendNotice("",$data);
    }
    mysqli_query($conn, "update app set status = 2 where id = '".$notice['id']."'");
}
$conn->close();
?>