<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Announcement extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'announcement_id',
        'title',
        'message',
        'type',
        'alert_type',
        'target_type',
        'target_id',
        'display_from',
        'display_until',
        'active',
        'created_by',
    ];

    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($announcement) {
            if (empty($announcement->announcement_id)) {
                $announcement->announcement_id = \Str::random(10);
            }
        });
    }

    protected $casts = [
        'display_from' => 'datetime',
        'display_until' => 'datetime',
        'active' => 'boolean',
    ];

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

    public function target()
    {
        return match($this->target_type) {
            'student' => $this->belongsTo(User::class, 'target_id'),
            'class' => $this->belongsTo(SchoolClass::class, 'target_id'),
            'batch' => $this->belongsTo(Batch::class, 'target_id'),
            'staff' => $this->belongsTo(User::class, 'target_id'),
            default => null,
        };
    }

    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    public function scopeCurrentlyDisplayable($query)
    {
        $now = now();
        return $query->where(function ($q) use ($now) {
            $q->where('display_from', '<=', $now)
              ->orWhereNull('display_from');
        })->where(function ($q) use ($now) {
            $q->where('display_until', '>=', $now)
              ->orWhereNull('display_until');
        });
    }
}