<?php
// CORRECTED PATH: Use a more direct path from the server root.
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/web-push/src/WebPush.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/web-push/src/Subscription.php';

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

function sendPushNotification($conn, $title, $body, $url) {
    $settings_result = $conn->query("SELECT * FROM site_settings WHERE setting_name IN ('contact_email', 'vapid_public_key', 'vapid_private_key')");
    $site_settings = [];
    while($row = $settings_result->fetch_assoc()){
        $site_settings[$row['setting_name']] = $row['setting_value'];
    }

    if(empty($site_settings['vapid_public_key']) || empty($site_settings['vapid_private_key'])) {
        return; // VAPID keys not set, so we can't send.
    }

    $auth = [
        'VAPID' => [
            'subject' => 'mailto:' . ($site_settings['contact_email'] ?? 'support@example.com'),
            'publicKey' => $site_settings['vapid_public_key'],
            'privateKey' => $site_settings['vapid_private_key'],
        ],
    ];

    $webPush = new WebPush($auth);
    $subscriptions = $conn->query("SELECT * FROM push_subscriptions JOIN users ON push_subscriptions.user_id = users.id WHERE users.role='admin'");
    
    $payload = json_encode([
        'title' => $title,
        'body' => $body,
        'url' => $url
    ]);

    while ($sub = $subscriptions->fetch_assoc()) {
        $subscription = Subscription::create([
            'endpoint' => $sub['endpoint'],
            'publicKey' => $sub['p256dh'],
            'authToken' => $sub['auth'],
        ]);
        $webPush->queueNotification($subscription, $payload);
    }

    foreach ($webPush->flush() as $report) {
        // You can log errors here if needed for debugging
    }
}
?>
