<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Announcement extends Model
{
    protected $fillable = [
        'created_by_user_id', 'title', 'message', 'type', 'target',
        'is_pinned', 'published_at', 'expires_at',
    ];

    protected $casts = [
        'is_pinned' => 'boolean',
        'published_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by_user_id');
    }

    public function vendors()
    {
        return $this->belongsToMany(Vendor::class, 'announcement_vendor')
            ->withPivot(['is_read', 'read_at'])
            ->withTimestamps();
    }

    public function scopeActive($query)
    {
        return $query->where(function ($q) {
            $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
        })->whereNotNull('published_at');
    }

    public function scopeForVendor($query, $vendorId)
    {
        return $query->where(function ($q) use ($vendorId) {
            $q->where('target', 'all_vendors')
              ->orWhereHas('vendors', fn($v) => $v->where('vendor_id', $vendorId));
        });
    }
}
