<?php
require_once '../base/common.php';
// webpush
require_once 'webpush/WebPush.php';
require_once 'webpush/VAPID.php';
require_once 'webpush/Notification.php';
require_once 'webpush/Encryption.php';
require_once 'webpush/Utils.php';
require_once 'webpush/Subscription.php';
require_once 'webpush/MessageSentReport.php';
// guzzlehttp
require_once 'vendor/autoload.php';
// jwt
require_once 'jwt/include.php';
// Base64url
require_once
 'base64url/Base64Url.php';

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

Global $serverUtil;

$pemKeyFile = $serverUtil->getProjectDir() . '/settings/webpush/private_key.pem';
error_log($pemKeyFile);

$auth = [
    //'GCM' => 'MY_GCM_API_KEY',
    'VAPID' => [
        'subject' => 'mailto:notification@server.su',
        'publicKey' => "BJcaiYLh7t488Kmi9I7g7-cpvADwvOkEzepXcSavT8czcfiVDgTJzWSRaLsPbYwvVhZU72HcjlrONjwYZxmqR5c",
        'privateKey' => "IDV7VIMQC8NLT1rfp5LoHXGL9LwCOn71gkg95vmNI0U",
    ],
];

$webpush = new WebPush();
$defaultOptions = [
    'TTL' => 300, // defaults to 4 weeks
    'urgency' => 'normal', // protocol defaults to "normal"
    'topic' => 'new_event', // not defined by default,
    'batchSize' => 200, // defaults to 1000
];
$webpush->setDefaultOptions($defaultOptions);

$endpoint =  $serverUtil->getURL();
error_log($endpoint);

$subscription =Subscription::create([
    'endpoint' => $endpoint,
    'publicKey' => "BJcaiYLh7t488Kmi9I7g7-cpvADwvOkEzepXcSavT8czcfiVDgTJzWSRaLsPbYwvVhZU72HcjlrONjwYZxmqR5c",
    'authToken' => "IDV7VIMQC8NLT1rfp5LoHXGL9LwCOn71gkg95vmNI0U",
    'contentEncoding' => 'aesgcm',
]);
error_log($subscription->getContentEncoding());

$message="aaaaa";
$payload = [
    'title' => 'aaaaa',
    'message' => $message,
    'url' => 'https://hoge.com/user/'
];

$res = $webpush->sendNotification(
    $subscription,
    json_encode( $payload )
);

/**
 * Check sent results
 * @var MessageSentReport $report
 */
foreach ($webpush->flush() as $report) {
    $endpoint = $report->getRequest()->getUri()->__toString();

    if ($report->isSuccess()) {
        echo "[v] Message sent successfully for subscription {$endpoint}.";
    } else {
        echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
    }
}
?>
