<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Notification;
use App\Notifications\SystemNotification;
use Illuminate\Support\Str;

class NotificationService
{
    /**
     * Send a notification to a user.
     * We'll use a generic Database notification for simplicity and speed.
     */
    public function notify(User $user, string $title, string $message, string $type = 'info', string $link = null)
    {
        // For simplicity in this non-stub implementation, we'll write directly to the table
        // since we are using Database notifications anyway.
        return \DB::table('notifications')->insert([
            'id' => Str::uuid(),
            'type' => 'App\Notifications\SystemNotification',
            'notifiable_type' => get_class($user),
            'notifiable_id' => $user->id,
            'data' => json_encode([
                'title' => $title,
                'message' => $message,
                'type' => $type,
                'link' => $link,
            ]),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    public function notifyAdmin(string $title, string $message, string $type = 'warning', string $link = null)
    {
        $admins = User::whereHas('role', function($q) { $q->where('name', 'admin'); })->get();
        foreach ($admins as $admin) {
            $this->notify($admin, $title, $message, $type, $link);
        }
    }
}
