<?php

namespace App\Models;

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

class PromotionLog extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'call_log_id',
        'template_id',
        'phone_number',
        'message',
        'status',
        'trigger_type',
        'sent_at',
        'error_message',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'sent_at' => 'datetime',
    ];

    /**
     * Get the user that owns the promotion log.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the call log associated with this promotion.
     */
    public function callLog()
    {
        return $this->belongsTo(CallLog::class);
    }

    /**
     * Get the template used for this promotion.
     */
    public function template()
    {
        return $this->belongsTo(MessageTemplate::class, 'template_id');
    }

    /**
     * Scope a query to only include sent promotions.
     */
    public function scopeSent($query)
    {
        return $query->where('status', 'sent');
    }

    /**
     * Scope a query to only include failed promotions.
     */
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    /**
     * Scope a query to only include pending promotions.
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope by trigger type.
     */
    public function scopeByTrigger($query, string $type)
    {
        return $query->where('trigger_type', $type);
    }
}
