<?php
require __DIR__ . '/vendor/autoload.php'; // Autoload Composer

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

// function sendFCMNotification($productName, $productId)
// {
//     include 'connexion.php';
//     $messaging = getMessaging();

//     $query = "SELECT token FROM user_tokens WHERE is_active = 1";
//     $stmt = $connect->prepare($query);
//     $stmt->execute();
//     $result = $stmt->get_result();

//     $tokens = array();
//     while ($row = $result->fetch_assoc()) {
//         if (!empty($row['token'])) {
//             $tokens[] = $row['token'];
//         }
//     }

//     if (!empty($tokens)) {
//         $message = CloudMessage::new()
//             ->withNotification([
//                 'title' => 'Produk Baru Ditambahkan',
//                 'body' => $productName . ' telah tersedia!',
//             ])
//             ->withData([
//                 'type' => 'newItem',
//                 'id' => strval($productId),
//             ]);

//         try {
//             $response = $messaging->sendMulticast($message, $tokens);

//             echo 'Berhasil dikirim ke: ' . $response->successes()->count() . ' perangkat.' . PHP_EOL;
//             echo 'Gagal dikirim ke: ' . $response->failures()->count() . ' perangkat.' . PHP_EOL;
//         } catch (Exception $e) {
//             echo 'Kesalahan saat mengirim pesan: ' . $e->getMessage() . PHP_EOL;
//         }
//     } else {
//         echo 'Tidak ada token aktif yang ditemukan.' . PHP_EOL;
//     }
// }

// function getMessaging()
// {
//     try {
//         $serviceAccountPath = __DIR__ . '/ecommerce-4ec3a-firebase-adminsdk-b30ai-a586364bd7.json';

//         $messaging = (new Factory)
//             ->withServiceAccount($serviceAccountPath)
//             ->createMessaging();

//         return $messaging;
//     } catch (\Kreait\Firebase\Exception\MessagingException $e) {
//         throw new Exception('Error saat mengirim notifikasi: ' . $e->getMessage());
//     } catch (\Kreait\Firebase\Exception\FirebaseException $e) {
//         throw new Exception('Firebase error: ' . $e->getMessage());
//     }
// }

function sendFCMNotification($productName, $productId, $tokens, $notification_id)
{
    $factory = getAccessToken();
    $messaging = $factory->createMessaging();
    // Buat pesan yang akan dikirim
    $message = CloudMessage::new()
        ->withNotification([
            'title' => 'Produk Baru Ditambahkan',
            'body' => $productName . ' telah tersedia!'
        ])
        ->withData([
            'id' => $notification_id
        ]);
    // 'fxmINLrHS4uKYiGR58GjD3:APA91bEsMpL2bSb0GHXdafmjki99TF6dhjDGHsL3uJRNeDFfZquQAYvUBqT2kArTvX-g93J45rWo4Jw1EB6HPrQyxzI8Nkh9CQUdoHtpJSoHqYZ24QWethY'
    foreach ($tokens as $token) {
        $messaging->send($message->toToken(
            $token
        ));
    }
    return true;
}
function sendFCMPromoNotification($tokens, $id)
{
    $factory = getAccessToken();
    $messaging = $factory->createMessaging();
    // Buat pesan yang akan dikirim
    $message = CloudMessage::new()
        ->withNotification([
            'title' => 'Promo Baru Ditambahkan',
            'body' => 'Promo telah tersedia!'
        ])
        ->withData([
            'id' => $id,
        ]);
    // 'fxmINLrHS4uKYiGR58GjD3:APA91bEsMpL2bSb0GHXdafmjki99TF6dhjDGHsL3uJRNeDFfZquQAYvUBqT2kArTvX-g93J45rWo4Jw1EB6HPrQyxzI8Nkh9CQUdoHtpJSoHqYZ24QWethY'
    foreach ($tokens as $token) {
        $messaging->send($message->toToken(
            $token
        ));
    }
    return true;
}
function getAccessToken()
{
    try {
        // Path ke file service account
        $serviceAccountPath = __DIR__ . '\ecommerce-4ec3a-firebase-adminsdk-b30ai-a586364bd7.json';

        // Inisialisasi Firebase
        $firebase = (new Factory)
            ->withServiceAccount($serviceAccountPath);

        // Inisialisasi Firebase Messaging

        if (isset($firebase)) {
            return $firebase;
        } else {
            throw new Exception('Failed to obtain access token: ' . json_encode($firebase));
        }
    } catch (\Kreait\Firebase\Exception\MessagingException $e) {
        throw new Exception('Error saat mengirim notifikasi: ' . $e->getMessage() . PHP_EOL);
    } catch (\Kreait\Firebase\Exception\FirebaseException $e) {
        throw new Exception('Firebase error: ' . $e->getMessage() . PHP_EOL);
    }
}
