<?php

namespace App\Controllers;
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

class Push extends BaseController
{
   public function saveSubscription()
    {
        $json = $this->request->getJSON(true);
    
        $file = WRITEPATH . 'subscription.json';
        $subscriptions = [];
    
        // Jika file sudah ada, baca isinya
        if (file_exists($file)) {
            $subscriptions = json_decode(file_get_contents($file), true);
    
            // Cegah duplikat endpoint
            foreach ($subscriptions as $sub) {
                if ($sub['endpoint'] === $json['endpoint']) {
                    return $this->response->setJSON(['status' => 'already exists']);
                }
            }
        }
    
        // Tambahkan subscription baru
        $subscriptions[] = $json;
    
        file_put_contents($file, json_encode($subscriptions, JSON_PRETTY_PRINT));
    
        return $this->response->setJSON(['status' => 'saved']);
    }


    public function send()
    {
        $data = json_decode(file_get_contents(WRITEPATH . 'subscription.json'), true);
    
        if (!is_array($data)) {
            echo "❌ Tidak ada subscription tersimpan";
            return;
        }
    
        $auth = [
            'VAPID' => [
                'subject' => 'mailto:admin@monitoring-server.com',
                'publicKey' => 'BNn0GXPVfldVgczx0qfHxmqPX7q0hNL5tBzmE4Faj95_d_racBLUDII7vtYKJIGTJw8l3YMvNNU4LT69hXwGQBk',
                'privateKey' => 'l2NAZIhqj1aaOUYm9Fvn-sOVErah6y3QckKV9Bpq0KU',
            ],
        ];
    
        $webPush = new WebPush($auth);
    
        foreach ($data as $sub) {
            $subscription = Subscription::create([
                'endpoint' => $sub['endpoint'],
                'publicKey' => $sub['keys']['p256dh'],
                'authToken' => $sub['keys']['auth'],
                'contentEncoding' => $sub['contentEncoding'] ?? 'aesgcm',
            ]);
    
            $report = $webPush->sendOneNotification($subscription, json_encode([
                'title' => '⚠️ Monitoring Server',
                'body' => 'Server sedang tidak merespon!',
            ]));
    
            if ($report->isSuccess()) {
                echo "✅ Notifikasi berhasil ke: " . $sub['endpoint'] . "<br>";
            } else {
                echo "❌ Gagal ke: " . $sub['endpoint'] . " — " . $report->getReason() . "<br>";
            }
        }
    }

}
