<?php

namespace Shm\ShmIntegrations\PWA;

use Minishlink\WebPush\WebPush;

use Minishlink\WebPush\Subscription;
use Shm\ShmDB\mDB;

class PWAPushMsg
{

    private $webPush;

    private $appKey;


    private $ownerID;

    private $ownerCollection;

    public function __construct($appKey)
    {

        $keys = mDB::collection("_pwaPushApps")->findOne([
            'appKey' => $appKey,
        ]);

        if (!$keys) {
            return;
        }

        $this->appKey = $appKey;



        $this->webPush = new WebPush([
            'VAPID' => [
                'subject' => 'mailto:hi@antonseagull.com',
                'publicKey' => $keys['publicKey'],
                'privateKey' => $keys['privateKey'],
            ],
        ], [
            // guzzlehttp/psr7 2.11+ requires string header values; web-push defaults TTL to int
            'TTL' => '2419200',
        ]);
    }

    public function owner($ownerID, $ownerCollection)
    {
        $this->ownerID = $ownerID;
        $this->ownerCollection = $ownerCollection;
        return $this;
    }

    public function send($title, $body)
    {
        if (!$this->webPush) {
            return;
        }

        if ($this->ownerID && $this->ownerCollection) {
            $subscriptions = mDB::collection("_pwaPushSubscriptions")->find([
                'owner' => $this->ownerID,
                'ownerCollection' => $this->ownerCollection,
                'appKey' => $this->appKey,
            ]);
        } else {
            $subscriptions = mDB::collection("_pwaPushSubscriptions")->find([
                'appKey' => $this->appKey,
            ]);
        }


        foreach ($subscriptions as $row) {
            $pushSubscription = Subscription::create([
                'endpoint' => $row['endpoint'],
                'keys' => [
                    'p256dh' => $row['keys']['p256dh'],
                    'auth' => $row['keys']['auth'],
                ],
            ]);

            $this->webPush->queueNotification(
                $pushSubscription,
                json_encode(['title' => $title, 'body' => $body])
            );
        }

        if ($this->webPush instanceof WebPush) {

            $reports = $this->webPush->flush();
            foreach ($reports as $report) {

                $endpoint = $report->getRequest()->getUri()->__toString();

                if ($report->isSuccess()) {
                } else {

                    mDB::_collection("_pwaPushSubscriptions")->deleteOne([
                        'endpoint' => $endpoint,
                    ]);
                }
            }
        }
    }
}
