<?php

namespace App\Models;

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

class SmsLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'recipient_phone',
        'message',
        'message_type',
        'status',
        'gateway',
        'gateway_response',
        'cost',
        'sent_by',
        'order_id',
        'customer_id',
    ];

    protected $casts = [
        'cost' => 'decimal:2',
        'gateway_response' => 'array',
    ];

    /**
     * Relationships
     */
    public function sender()
    {
        return $this->belongsTo(User::class, 'sent_by');
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

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

    /**
     * Check if SMS was successful
     */
    public function getIsSuccessfulAttribute()
    {
        return $this->status === 'sent';
    }

    /**
     * Check if SMS failed
     */
    public function getIsFailedAttribute()
    {
        return $this->status === 'failed';
    }

    /**
     * Get message type display name
     */
    public function getMessageTypeDisplayAttribute()
    {
        $types = [
            'booking_confirmation' => 'Booking Confirmation',
            'payment_confirmation' => 'Payment Confirmation',
            'appointment_reminder' => 'Appointment Reminder',
            'promotional' => 'Promotional',
            'system_notification' => 'System Notification',
        ];

        return $types[$this->message_type] ?? ucfirst($this->message_type);
    }

    /**
     * Scope for successful SMS
     */
    public function scopeSuccessful($query)
    {
        return $query->where('status', 'sent');
    }

    /**
     * Scope for failed SMS
     */
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    /**
     * Scope for SMS by type
     */
    public function scopeByType($query, $type)
    {
        return $query->where('message_type', $type);
    }

    /**
     * Scope for SMS by gateway
     */
    public function scopeByGateway($query, $gateway)
    {
        return $query->where('gateway', $gateway);
    }

    /**
     * Scope for SMS by date range
     */
    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('created_at', [$startDate, $endDate]);
    }

    /**
     * Get gateway response message
     */
    public function getGatewayMessageAttribute()
    {
        if (is_array($this->gateway_response) && isset($this->gateway_response['message'])) {
            return $this->gateway_response['message'];
        }
        return $this->status;
    }
}