<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class UserNotification extends Model
{
    use HasFactory;

    protected $fillable = [
        'created_by_admin_id',
        'title',
        'message',
        'audience',
        'recipient_ids_json',
        'show_popup',
        'show_in_inbox',
        'is_active',
    ];

    protected $casts = [
        'recipient_ids_json' => 'array',
        'show_popup' => 'boolean',
        'show_in_inbox' => 'boolean',
        'is_active' => 'boolean',
    ];

    public function admin(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by_admin_id');
    }

    public function reads(): HasMany
    {
        return $this->hasMany(UserNotificationRead::class);
    }

    public function appliesToUser(int $userId): bool
    {
        if (! $this->is_active) {
            return false;
        }

        if ($this->audience === 'all') {
            return true;
        }

        $ids = array_map('intval', (array) ($this->recipient_ids_json ?? []));

        return in_array($userId, $ids, true);
    }
}
