<?php

namespace App\Models;

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

class PostalRecord extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'postal_type',
        'reference_number',
        'date',
        'from_name',
        'from_address',
        'to_name',
        'to_address',
        'subject',
        'description',
        'attachment',
        'status',
        'logged_by',
    ];

    protected $casts = [
        'date' => 'date',
    ];

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

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

    // Scopes
    public function scopeIncoming($query)
    {
        return $query->where('postal_type', 'incoming');
    }

    public function scopeOutgoing($query)
    {
        return $query->where('postal_type', 'outgoing');
    }

    public function scopeForDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('date', [$startDate, $endDate]);
    }

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