<?php

namespace App\Models;

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

class EmailLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'school_id',
        'to_email',
        'cc_email',
        'bcc_email',
        'from_email',
        'subject',
        'body',
        'attachments',
        'sent_at',
        'status',
        'error_message',
        'sent_by',
    ];

    protected $casts = [
        'sent_at' => 'datetime',
        'attachments' => 'array',
        'cc_email' => 'array',
        'bcc_email' => 'array',
    ];

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

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

    // Scopes
    public function scopeSent($query)
    {
        return $query->where('status', 'sent');
    }

    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

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

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