<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../includes/Database.php';

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

// 1. Initialize WebPush with your VAPID keys
$auth = [
    'VAPID' => [
        'subject' => VAPID_SUBJECT,
        'publicKey' => VAPID_PUBLIC_KEY,
        'privateKey' => VAPID_PRIVATE_KEY,
    ],
];

$webPush = new WebPush($auth);

// 2. Fetch a subscription from the database (Example for user 1)
$db = new Database();
$stmt = $db->query("SELECT subscription FROM push_subscriptions WHERE user_id = ? LIMIT 1", [1]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    $subscriptionData = json_decode($row['subscription'], true);
    
    // Create Subscription object from saved JSON
    $subscription = Subscription::create($subscriptionData);

    // 3. Queue the notification
    $webPush->queueNotification(
        $subscription,
        json_encode(['title' => 'Mabanga Express', 'body' => 'You have a new delivery request!'])
    );

    // 4. Send it
    foreach ($webPush->flush() as $report) {
        $endpoint = $report->getRequest()->getUri()->__toString();
        echo $report->isSuccess() ? "Message sent successfully to {$endpoint}\n" : "Message failed: {$report->getReason()}\n";
    }
} else {
    echo "No subscription found for this user.";
}