<?php

namespace App\Models;

use App\Traits\HasDeliveryCode;
use App\Traits\HasTrackingCode;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Delivery extends Model
{
    use HasDeliveryCode, HasFactory, HasTrackingCode;

    protected $fillable = [
        'order_id',
        'delivery_time_id',
        'user_id',
        'address_id',
        'tracking_code',
        'type',
        'date',
        'time',
        'status',
        'price',
        'provider_id',
        'carrier',
        'carrier_code',
        'origin_lat',
        'origin_lon',
        'dest_lat',
        'dest_lon',
        'picked_up_at',
        'delivered_at',
    ];

    /**
     * The part below is for this model relationships
     */
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function deliveryTime()
    {
        return $this->belongsTo(DeliveryTime::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function address()
    {
        return $this->belongsTo(OrderDeliveryAddress::class, 'address_id');
    }

    public function provider()
    {
        return $this->belongsTo(DeliveryProvider::class);
    }

    public function items()
    {
        return $this->hasMany(DeliveryItem::class);
    }

    public function events()
    {
        return $this->hasMany(DeliveryEvent::class)
            ->orderBy('happened_at', 'asc');
    }
    /**
     * The above is for this model relationships
     */
    public static function boot()
    {
        parent::boot();
        self::creating(function ($model) {
            $model->code = self::createDeliveryCode();
            $model->tracking_code = self::createTrackingCode();
        });
    }
}
