<?php

namespace App\Libraries;

use Modules\Passanger\Models\UserDeviceModel;

/**
 * Sends FCM to every active device for a user — same behaviour as
 * {@see \Modules\Passanger\Controllers\Api\Passanger::sendNotification()}.
 */
class UserPushNotification
{
    protected UserDeviceModel $userDeviceModel;

    protected ?FirebaseNotification $firebase = null;

    public function __construct(?UserDeviceModel $userDeviceModel = null, ?FirebaseNotification $firebase = null)
    {
        $this->userDeviceModel = $userDeviceModel ?? new UserDeviceModel();
        $this->firebase        = $firebase;
    }

    protected function getFirebase(): FirebaseNotification
    {
        return $this->firebase ??= new FirebaseNotification();
    }

    public function sendToUser(int $userId, string $title, string $body): void
    {
        $devices = $this->userDeviceModel->where('user_id', $userId)
            ->where('status', 1)
            ->findAll();

        if ($devices === []) {
            return;
        }

        $firebase = $this->getFirebase();

        foreach ($devices as $device) {
            try {
                $firebase->sendToToken($device->device_token, $title, $body);
            } catch (\Throwable $e) {
                log_message('error', 'FCM Error (user ' . $userId . '): ' . $e->getMessage());
            }
        }
    }
}
