<?php
declare(strict_types=1);

namespace App\Helpers;

use GuzzleHttp\Client;

class OneSignal
{
    private $appId;
    private $restApiKey;
    private $banner;
    private $logo;
    private $favicon;

    public function __construct($appId, $restApiKey, array $options = [])
    {
        $this->appId = $appId;
        $this->restApiKey = $restApiKey;
        $this->banner = $options['banner'] ?? '';
        $this->logo = $options['logo'] ?? '';
        $this->favicon = $options['favicon'] ?? '';
    }

    public function sendNotificationToAll($title, $message, $target)
    {
        $fields = [
            'app_id' => $this->appId,
            'included_segments' => ['All'],
            'data' => ['foo' => 'bar'],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'url' => $target
        ];

        return $this->sendNotification($fields);
    }

    public function sendNotificationToPlayers($title, $message, $target, array $playerIds)
    {
        $fields = [
            'app_id' => $this->appId,
            'include_player_ids' => $playerIds,
            'data' => ['foo' => 'bar'],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'url' => $target
        ];

        return $this->sendNotification($fields);
    }

    public function scheduleNotification($title, $message, $target, $sendAfter)
    {
        $fields = [
            'app_id' => $this->appId,
            'included_segments' => ['All'],
            'data' => ['foo' => 'bar'],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'url' => $target,
            'send_after' => $sendAfter
        ];

        return $this->sendNotification($fields);
    }

    private function sendNotification(array $fields)
    {
        if ($this->banner) {
            $fields['chrome_web_image'] = $this->banner;
        }

        if ($this->logo) {
            $fields['chrome_web_icon'] = $this->logo;
        }

        if ($this->favicon) {
            $fields['chrome_web_icon'] = $this->favicon;
        }

        $client = new Client();
        $response = $client->request('POST', 'https://onesignal.com/api/v1/notifications', [
            'headers' => [
                "Content-Type" => "application/json; charset=utf-8",
                'Authorization' => "Basic {$this->restApiKey}",
            ],
            'body' => json_encode($fields), 
            'verify' => false,  // this is important to disable SSL verification
        ]);

        return $response;
    }

}
