<?php

namespace App\Library;

use Illuminate\Http\Request;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\AndroidConfig;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Messaging\MulticastSendReport;

class Firebase
{
    protected $serviceAccount;
    
    public function __construct() {
        
        $account = ServiceAccount::fromJsonFile(__DIR__.'/mwasmkpgrisingosari-key.json');
        $this->serviceAccount = (new Factory)->withServiceAccount($account);
    }

    public function push($title, $body, $target)
    {
        $messaging = $this->serviceAccount->createMessaging();
        
        $notification = Notification::create($title, $body);

        $message = CloudMessage::withTarget('token', $target)
            ->withNotification($notification);

        $messaging->send($message);
    }

    // fungsi untuk mengirim notifikasi lebih dari satu device
    // target berdasar id token user orangtua
    public function sendNotification($title, $body, $target, $stateTime, $status){
        $fcm = $this->serviceAccount->createMessaging();

        $devices = explode(", ", $target);

        $data = [
            'title' => $title,
            'message' => $body,
            'waktu' => $stateTime,
            'status' => $status
        ];

        $priority = AndroidConfig::fromArray([
            'ttl' => '0s',
            'priority' => 'high',
            'data' => $data
        ]);

        $message = CloudMessage::new()
            ->withAndroidConfig($priority)
            ->withData($data);
        
        $report = $fcm->sendMulticast($message, $devices);
    }

    public function testConnection(){
        $database = $this->serviceAccount->create()->getDatabase();
        $reference = $database->getReference('dmy_mstrwb');
        $key = $reference->push()->getKey();
        $reference->getChild($key)->set([
            'subject' => 'dadadadaaaa'
        ]);
        
        return response()->json($key);
    }
}