<?php
namespace App\Models;

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

class EmailScheduled extends Model
{
    use HasFactory;

    protected $table = 'email_scheduled';

    protected $fillable = [
        'template_id',
        'subject',
        'content',
        'scheduled_at',
        'status',
        'created_by',
        'delivery_report'
    ];

    protected $casts = [
        'scheduled_at' => 'datetime',
        'delivery_report' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function template()
    {
        return $this->belongsTo(EmailTemplate::class, 'template_id');
    }

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

    public function recipients()
    {
        return $this->belongsToMany(Member::class, 'email_scheduled_recipients', 'email_scheduled_id', 'member_id')
                    ->withPivot(['email_address', 'status', 'error_message', 'sent_at'])
                    ->withTimestamps();
    }

    public function recipientDetails()
    {
        return $this->hasMany(EmailScheduledRecipient::class, 'email_scheduled_id');
    }

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

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

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

    public function getIsScheduledAttribute()
    {
        return $this->status === 'scheduled';
    }

    public function getIsSentAttribute()
    {
        return $this->status === 'sent';
    }

    public function getCanBeCancelledAttribute()
    {
        return $this->status === 'scheduled' && $this->scheduled_at->isFuture();
    }

    public function getTotalRecipientsAttribute()
    {
        return $this->recipients()->count();
    }

    public function getSuccessfulSendsAttribute()
    {
        return $this->recipientDetails()->where('status', 'sent')->count();
    }

    public function getFailedSendsAttribute()
    {
        return $this->recipientDetails()->where('status', 'failed')->count();
    }
}
