<?php
require __DIR__ . '/../vendor/autoload.php';
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Utils;
use Minishlink\WebPush\VAPID;
// here I'll get the subscription endpoint in the POST parameters
// but in reality, you'll get this information in your database
// because you already stored it (cf. push_subscription.php)
define('YES_PUSH_VAPID_KEYS_FILE',__DIR__.'/yes_push_vapid_keys.vapid');
if(!is_file(YES_PUSH_VAPID_KEYS_FILE)){
	$vapid = VAPID::createVapidKeys();
	file_put_contents(YES_PUSH_VAPID_KEYS_FILE,json_encode($vapid));
	chmod(YES_PUSH_VAPID_KEYS_FILE,0400);
	header('Location: '.basename(__FILE__));
}
$auth = json_decode(file_get_contents(YES_PUSH_VAPID_KEYS_FILE));
ini_set('auto_detect_line_endings',TRUE);
define('YES_PUSH_SUBCRIBERS_FILE',__DIR__.'/subscriber.csv');
if(!is_file(YES_PUSH_SUBCRIBERS_FILE)){
	touch(YES_PUSH_SUBCRIBERS_FILE);
}
$subscription_raw = file_get_contents(YES_PUSH_SUBCRIBERS_FILE);
$sub_array = array();
foreach(explode("\r\n",$subscription_raw) as $row){
	$row = explode("\t",$row);
	if(sizeOf($row) < 2){
		continue;
	}
	$sub_array[] = array(
		'endpoint'=>trim($row[0]),
		'key'=>trim($row[1]),
		'token'=>trim($row[2])
	);
}

//$subscription = json_decode(file_get_contents('php://input'), true);
$auth = array(
    'VAPID' => array(
        'subject' => 'https://agri.abcde.biz/yes/login.php',
        'publicKey' => $auth->publicKey,
        'privateKey' => $auth->privateKey,
    ),
);
$webPush = new WebPush($auth);
foreach($sub_array as $nr=>$subscription){
	$res = $webPush->sendNotification(
	    $subscription['endpoint'],
	    json_encode(array(
		'message'=>'da bin ich - Schoen wie eh und je',
		'push_target_link'=>'/yes/admin/orders.php'
	    )),
	    $subscription['key'],
	    $subscription['token']
	);
	if($res != '1' or (isset($res['success']) and $res['success'] !== True)){
		print_r($res);
		printf('<br /><b>Fehlermeldung:</b><br /><i>%s</i>',$res['message']);
	}
}
$webPush->flush();
echo '<p>Done</p>';
// handle eventual errors here, and remove the subscription from your server if it is expired
