<?php

namespace App\Models;

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

class OrderTracking extends Model
{
    use HasFactory;

    protected $table = 'order_tracking';

    protected $fillable = [
        'order_id',
        'status',
        'status_label',
        'description',
        'location',
        'date',
        'completed',
    ];

    protected $casts = [
        'date' => 'datetime',
        'completed' => 'boolean',
    ];

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

    // Scopes
    public function scopeCompleted($query)
    {
        return $query->where('completed', true);
    }

    public function scopePending($query)
    {
        return $query->where('completed', false);
    }

    public function scopeRecent($query, $days = 7)
    {
        return $query->where('date', '>=', now()->subDays($days));
    }

    // Accessors
    public function getFormattedDateAttribute()
    {
        return $this->date->format('d/m/Y H:i');
    }

    public function getRelativeDateAttribute()
    {
        return $this->date->diffForHumans();
    }

    // Events
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($tracking) {
            if (!$tracking->date) {
                $tracking->date = now();
            }
        });
    }
}
