<?php

namespace Modules\Order\Entities;

use App\Models\BaseModel;
use Modules\Address\Entities\Model as Address;
use Modules\Branch\Entities\Model as Branch;
use Modules\Client\Entities\Model as Client;
use Modules\Delivery\Entities\Model as Delivery;
use Modules\Payment\Entities\Model as Payment;

class Model extends BaseModel
{
    protected $guarded = [];

    protected $table = 'orders';

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

        static::creating(function ($order) {
            if (is_null($order->branch_id)) {
                $firstBranch = Branch::query()->first();
                if ($firstBranch) {
                    $order->branch_id = $firstBranch->id;
                }
            }
        });
    }

    public function Products()
    {
        return $this->hasMany(ModelProduct::class, 'order_id');
    }

    public function Branch()
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

    public function Payment()
    {
        return $this->belongsTo(Payment::class, 'payment_id');
    }

    public function Delivery()
    {
        return $this->belongsTo(Delivery::class, 'delivery_id');
    }

    public function Client()
    {
        return $this->belongsTo(Client::class, 'client_id')->withTrashed();
    }

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