<?php

namespace App\Services;

use App\Models\Notification;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    /**
     * Send a notification to a specific user.
     */
    public static function send(User $user, $title, $body, $type = 'info', $url = null)
    {
        try {
            $firebase = new FirebaseService();
            return $firebase->sendToUser($user, $title, $body, $url, ['type' => $type]);
        } catch (\Exception $e) {
            // Fallback to basic DB notification if Firebase fails or is not configured
            Log::warning("Firebase notification failed, falling back to database: " . $e->getMessage());
            
            return \App\Models\Notification::create([
                'user_id' => $user->id,
                'type' => $type,
                'title' => $title,
                'body' => $body,
                'url' => $url,
                'is_read' => false
            ]);
        }
    }

    /**
     * Send announcement notification to all active users.
     */
    public static function notifyAll($title, $body, $url = null)
    {
        $users = User::where('is_active', true)->get();
        foreach ($users as $user) {
            self::send($user, $title, $body, 'info', $url);
        }
    }
}
