<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserNotification extends Model
{
    protected $table    = 'user_notifications';
    protected $fillable = ['user_id', 'title', 'message', 'type', 'icon'];

    /** Target: 'all' if user_id is null, otherwise 'user' */
    public function getTargetAttribute(): string
    {
        return $this->user_id ? 'user' : 'all';
    }

    /** Is this notification read by the given user? */
    public function isReadBy(int $userId): bool
    {
        return NotificationRead::where('user_id', $userId)
            ->where('notification_id', $this->id)
            ->exists();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /** All notifications visible to a user (their own + broadcast) */
    public static function forUser(int $userId)
    {
        return static::where(function ($q) use ($userId) {
            $q->whereNull('user_id')->orWhere('user_id', $userId);
        })->latest();
    }

    /** Unread count for a user */
    public static function unreadCountFor(int $userId): int
    {
        return static::forUser($userId)
            ->whereNotIn('id', function ($q) use ($userId) {
                $q->select('notification_id')
                  ->from('notification_reads')
                  ->where('user_id', $userId);
            })
            ->count();
    }
}
