<?php

namespace App\Models;

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

class InternalMessage extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'sender_id',
        'subject',
        'message',
        'attachments',
        'is_important',
    ];

    protected $casts = [
        'attachments' => 'array',
        'is_important' => 'boolean',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

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

    public function recipients()
    {
        return $this->belongsToMany(User::class, 'message_recipients')
                    ->withPivot('read_at', 'deleted_at')
                    ->withTimestamps();
    }

    // Scopes
    public function scopeImportant($query)
    {
        return $query->where('is_important', true);
    }

    public function scopeForSender($query, $userId)
    {
        return $query->where('sender_id', $userId);
    }

    public function scopeForRecipient($query, $userId)
    {
        return $query->whereHas('recipients', function($q) use ($userId) {
            $q->where('user_id', $userId);
        });
    }

    public function scopeSearch($query, $search)
    {
        return $query->where(function($q) use ($search) {
            $q->where('subject', 'like', "%{$search}%")
              ->orWhere('message', 'like', "%{$search}%");
        });
    }
}
