<?php
defined('BASEPATH') or exit('No direct script access allowed');

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

class Notif
{
    private $messaging;

    public function __construct()
    {
        $firebase = (new Factory)
            ->withServiceAccount(FCPATH . 'firebase/firebase-credentials.json');

        $this->messaging = $firebase->createMessaging();
    }

    public function send($token, $title, $body, $data = [])
    {
        $message = CloudMessage::withTarget('token', $token)
            ->withData(array_merge([
                'title' => $title,
                'body' => $body
            ], $data)); // kirim semua sebagai data

        try {
            $this->messaging->send($message);
            return true;
        } catch (\Kreait\Firebase\Exception\MessagingException $e) {
            log_message('error', 'FCM Error: ' . $e->getMessage());
            return false;
        }
    }
}
