<?php

namespace App\Models;

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

class CallLog extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'device_id',
        'device_name',
        'phone_number',
        'call_type',
        'call_time',
        'sms_sent',
        'synced_at',
    ];

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

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

    /**
     * Get the SMS log associated with this call.
     */
    public function smsLog()
    {
        return $this->hasOne(SmsLog::class);
    }

    /**
     * Scope a query to only include incoming calls.
     */
    public function scopeIncoming($query)
    {
        return $query->where('call_type', 'incoming');
    }

    /**
     * Scope a query to only include outgoing calls.
     */
    public function scopeOutgoing($query)
    {
        return $query->where('call_type', 'outgoing');
    }

    /**
     * Scope a query to only include missed calls.
     */
    public function scopeMissed($query)
    {
        return $query->where('call_type', 'missed');
    }

    /**
     * Scope a query to only include calls where SMS was sent.
     */
    public function scopeWithSmsSent($query)
    {
        return $query->where('sms_sent', true);
    }

    /**
     * Scope a query to filter by date range.
     */
    public function scopeDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('call_time', [$startDate, $endDate]);
    }

    /**
     * Get formatted call type for display.
     */
    public function getCallTypeFormattedAttribute()
    {
        return ucfirst($this->call_type);
    }

    /**
     * Get call type badge class.
     */
    public function getCallTypeBadgeAttribute()
    {
        return 'badge-' . $this->call_type;
    }
}
