<?php

namespace App\Models;

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

class SmsLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'school_id',
        'to_phone',
        'message',
        'sent_at',
        'status',
        'gateway_response',
        'sms_count',
        'cost',
        'sent_by',
    ];

    protected $casts = [
        'sent_at' => 'datetime',
        'sms_count' => 'integer',
        'cost' => 'decimal:2',
    ];

    // 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('to_phone', 'like', "%{$search}%");
    }
}
