<?php
declare(strict_types=1);

// Dependencies are shipped with the app: production needs no Composer or worker.
function pushKeys(): array {
    static $keys;
    if ($keys!==null) return $keys;
    require_once __DIR__.'/push/vendor/autoload.php';
    $path=dirname(__DIR__).'/data/push-keys.json';
    $lock=fopen(dirname(__DIR__).'/data/push-keys.lock','c');
    if (!$lock) throw new RuntimeException('Unable to initialize notifications.');
    try {
        if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock notification keys.');
        if (!file_exists($path)) {
            $generated=Minishlink\WebPush\VAPID::createVapidKeys();
            $json=json_encode($generated,JSON_THROW_ON_ERROR);
            if (file_put_contents($path,$json)!==strlen($json)) throw new RuntimeException('Unable to save notification keys.');
            chmod($path,0600);
        }
        return $keys=json_decode(file_get_contents($path),true,8,JSON_THROW_ON_ERROR);
    } finally {flock($lock,LOCK_UN);fclose($lock);}
}
function pushEndpoint(mixed $endpoint): string {
    if (!is_string($endpoint) || strlen($endpoint)>2048) throw new DomainException('Invalid push subscription.');
    $url=parse_url($endpoint);
    $host=strtolower($url['host']??'');
    // Only browser-operated push services. Never let a subscription turn this server into an HTTP proxy.
    $allowed=in_array($host,['fcm.googleapis.com','updates.push.services.mozilla.com','web.push.apple.com'],true)
        || str_ends_with($host,'.push.apple.com') || str_ends_with($host,'.notify.windows.com');
    if (!$allowed || ($url['scheme']??'')!=='https' || isset($url['user']) || isset($url['port']) || isset($url['fragment']) || empty($url['path'])) throw new DomainException('Unsupported push service.');
    return $endpoint;
}
function pushSubscribe(string $user,array $in): void {
    $s=$in['subscription']??null;
    if (!is_array($s)) throw new DomainException('Invalid push subscription.');
    $endpoint=pushEndpoint($s['endpoint']??null);
    foreach (['p256dh'=>65,'auth'=>16] as $key=>$length) {
        $value=$s['keys'][$key]??null;
        if (!is_string($value) || strlen($value)>100 || !preg_match('/^[A-Za-z0-9_-]+={0,2}$/D',$value)) throw new DomainException('Invalid push keys.');
        $decoded=base64_decode(strtr($value,'-_','+/'),true);
        if ($decoded===false || strlen($decoded)!==$length || ($key==='p256dh' && $decoded[0]!=="\x04")) throw new DomainException('Invalid push keys.');
    }
    $point=base64_decode(strtr($s['keys']['p256dh'],'-_','+/'),true);
    $pem="-----BEGIN PUBLIC KEY-----\n".chunk_split(base64_encode(hex2bin('3059301306072a8648ce3d020106082a8648ce3d030107034200').$point),64,"\n")."-----END PUBLIC KEY-----\n";
    if (!@openssl_pkey_get_public($pem)) throw new DomainException('Invalid push public key.');
    pushKeys();
    if (!query('SELECT 1 FROM push_subscriptions WHERE endpoint=? AND user_id=?',[$endpoint,$user])->fetchColumn()
        && (int)query('SELECT COUNT(*) FROM push_subscriptions WHERE user_id=?',[$user])->fetchColumn()>=10) throw new DomainException('Notification device limit reached. Disable notifications on another device first.');
    query('INSERT INTO push_subscriptions(endpoint,user_id,p256dh,auth,updated) VALUES(?,?,?,?,?) ON CONFLICT(endpoint) DO UPDATE SET user_id=excluded.user_id,p256dh=excluded.p256dh,auth=excluded.auth,updated=excluded.updated',[$endpoint,$user,$s['keys']['p256dh'],$s['keys']['auth'],time()]);
}
function pushUnsubscribe(string $user,mixed $endpoint): void {
    if (!is_string($endpoint)) throw new DomainException('Invalid push subscription.');
    query('DELETE FROM push_subscriptions WHERE endpoint=? AND user_id=?',[$endpoint,$user]);
}
function pushGame(int $id,string $kind='turn',?string $recipient=null): void {
    $g=query('SELECT * FROM games WHERE id=?',[$id])->fetch();
    if (!$g) return;
    if ($kind==='turn') {
        if ($g['status']!=='active') return;
        $s=json_decode($g['state'],true);
        $recipient=$s['turn']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a']);
    }
    if (!$recipient) return;
    $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind];
}
function pushAfterCommit(): void {
    $events=$GLOBALS['push_events']??[];
    $GLOBALS['push_events']=[];
    if (!$events) return;
    // Only committed events reach shutdown. HTTP failures cannot change the API result.
    register_shutdown_function(static function() use ($events): void {
        session_write_close();
        ignore_user_abort(true);
        if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
        try {pushDeliver($events);} catch (Throwable $e) {error_log('Push delivery failed ('.get_class($e).').');}
    });
}
function pushDeliver(array $events,?Minishlink\WebPush\WebPush $push=null): void {
    $jobs=[];
    foreach ($events as $event) {
        $g=query('SELECT * FROM games WHERE id=?',[$event['game']])->fetch();
        if (!$g || (int)$g['version']!==$event['version']) continue;
        foreach (query('SELECT * FROM push_subscriptions WHERE user_id=?',[$event['user']])->fetchAll() as $s) $jobs[]=[$event,$g,$s];
    }
    if (!$jobs) return;
    $keys=pushKeys();
    $push??=new Minishlink\WebPush\WebPush(['VAPID'=>['subject'=>baseUrl(),'publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],['TTL'=>3600,'urgency'=>'normal'],5,['connect_timeout'=>2,'allow_redirects'=>false]);
    $push->setReuseVAPIDHeaders(true);
    foreach ($jobs as [$event,$g,$s]) {
        $opponent=profile($g['a']===$event['user']?$g['b']:$g['a'])['name'];
        $body=match($event['kind']) {'challenge'=>$opponent.' invited you to play.','rematch'=>$opponent.' wants a rematch.',default=>'Your turn against '.$opponent.'.'};
        $push->queueNotification(Minishlink\WebPush\Subscription::create(['endpoint'=>$s['endpoint'],'contentEncoding'=>'aes128gcm','keys'=>['p256dh'=>$s['p256dh'],'auth'=>$s['auth']]]),json_encode(['title'=>'Microchess','body'=>$body,'game'=>$event['game']],JSON_THROW_ON_ERROR),['topic'=>'game-'.$event['game']]);
    }
    foreach ($push->flush() as $report) {
        if ($report->isSubscriptionExpired()) query('DELETE FROM push_subscriptions WHERE endpoint=?',[(string)$report->getRequest()->getUri()]);
        elseif (!$report->isSuccess()) error_log('Push service did not accept a notification.');
    }
}
