<?php
// public_html/printshop/functions/notification_functions.php

include_once('../includes/db.php');

// Send push notification
function sendPushNotification($userId, $title, $message) {
    // Fetch OneSignal device token from the onesignal_tokens table
    $device = fetchOne("SELECT device_token FROM onesignal_tokens WHERE user_id = ?", [$userId]);

    if ($device && !empty($device['device_token'])) {
        $onesignalPlayerId = $device['device_token'];

        $fields = [
            'app_id' => "YOUR_ONESIGNAL_APP_ID",
            'include_player_ids' => [$onesignalPlayerId], // Use the player's ID to target the user
            'headings' => ["en" => $title],
            'contents' => ["en" => $message],
        ];

        // Send notification via OneSignal API
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'Authorization: Basic YOUR_ONESIGNAL_REST_API_KEY',
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($ch, CURLOPT_POST, true);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    } else {
        return "Error: Device token not found for user.";
    }
}
?>
