<?php

namespace App\Models;

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

class EmailRecipients extends Model
{
    use HasFactory;

    protected $fillable = [
        'email_template_id',
        'member_id',
        'email_address',
        'status',
        'error_message',
        'sent_at'
    ];

    protected $casts = [
        'sent_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

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

    public function member()
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    public function markAsSent()
    {
        $this->update([
            'status' => 'sent',
            'sent_at' => now()
        ]);
    }

    public function markAsFailed($errorMessage = null)
    {
        $this->update([
            'status' => 'failed',
            'error_message' => $errorMessage
        ]);
    }

    public function markAsBounced($errorMessage = null)
    {
        $this->update([
            'status' => 'bounced',
            'error_message' => $errorMessage
        ]);
    }
}
