<?php
// send_notification.php
require 'vendor/autoload.php'; // You MUST have the library installed
require 'config.php';

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

// --- 1. SETUP KEYS ---
$auth = [
    'VAPID' => [
        'subject' => 'mailto:shaifful@smkpg.net',
        'publicKey' => 'BIZZQipCJ4o2UoOaVODLLtLWovXvKBizoWArB7VUdUD8JdLn_m8TYo179fezUbCawXiq0H7uMi56fRrsVpw6rFA',
        'privateKey' => 'sD9YtodtIQ7crR68qTz2zxs3hmbGwwx4GIeTnqb9324', 
    ],
];

// --- 2. PREPARE THE MESSAGE ---
$payload = json_encode([
    'title' => 'School Attendance',
    'body'  => 'Don\'t forget to clock in today!',
    'url'   => '/dashboard.php'
]);

// --- 3. GET USERS FROM DB ---
// Example: Send to ALL users
$stmt = $pdo->query("SELECT * FROM push_subscriptions");
$subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

$webPush = new WebPush($auth);

// --- 4. SEND ---
foreach ($subscriptions as $sub) {
    $webPush->queueNotification(
        Subscription::create([
            'endpoint' => $sub['endpoint'],
            'publicKey' => $sub['p256dh'],
            'authToken' => $sub['auth'],
        ]),
        $payload
    );
}

// Check results
foreach ($webPush->flush() as $report) {
    if ($report->isSuccess()) {
        echo "Message sent successfully!\n";
    } else {
        echo "Message failed: {$report->getReason()}\n";
        // Optional: Delete invalid subscription from DB here
    }
}
?>