<?php

namespace App\Services;

use App\Models\User;
use App\Notifications\GeneralNotification;
use Throwable;

class NotificationService
{
    /**
     * Send a notification to a specific user (or admin).
     *
     * @param int|User $user
     * @param string $title
     * @param string $message
     * @param string|null $url
     * @param string $type (info, success, warning, danger)
     */
    public static function send($user, string $title, string $message, ?string $url = null, string $type = 'info', bool $sendMail = false)
    {
        if (is_numeric($user)) {
            $user = User::find($user);
        }

        if (!$user) return;

        $payload = [
            'title'   => $title,
            'message' => $message,
            'url'     => $url,
            'type'    => $type,
            'mail'    => $sendMail,
        ];

        try {
            $user->notify(new GeneralNotification($payload));
        } catch (Throwable $exception) {
            $payload['mail'] = false;
            $user->notify(new GeneralNotification($payload));
        }
    }

    /**
     * Notify all administrators.
     */
    public static function notifyAdmins(string $title, string $message, ?string $url = null, string $type = 'info', bool $sendMail = false)
    {
        $admins = User::where('role', 'admin')->get();
        foreach ($admins as $admin) {
            self::send($admin, $title, $message, $url, $type, $sendMail);
        }
    }
}
