<?php

namespace App\Models;

use App\Traits\UuidTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Product extends Model
{
    use HasFactory,SoftDeletes, UuidTrait;

    protected $table = 'products';
    public $timestamps = true; 

    protected $fillable = [
        'name',
        'uuid',
        'brand_id',
        'unit_type',
        'calculation',        
        'is_active',
        'created_by',
        'updated_by',
        'deleted_at',
    ];

    protected $appends = [
        'full_name','order_count',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function(Product $model) {
            $model->created_by = auth()->user()->id;
        });

        /*
        static::deleting(function(Product $model) {
            $model->deleted_by = auth()->user()->id;
            $model->save();
        });
        */

        static::updating(function(Product $model) {
            $model->updated_by = auth()->user()->id;
        });
    }

    public function brands(){
        return $this->belongsTo(Brand::class, 'brand_id');
    }

    public function product_unit(){
        return $this->belongsTo(UnitType::class, 'unit_type');
    }

    public function getPurchasePriceEncodeAttribute()
    {
        $encodedPrice = str_replace(config('constant.cost_price_encode_format.code'), config('constant.cost_price_encode_format.encode'),$this->price);
		return $encodedPrice ?? '';
    }   

    public function orderProducts()
    {
        return $this->hasMany(OrderProduct::class, 'product_id');
    }

    public function getFullNameAttribute()
    {
        // return $this->name . ' - ' .$this->brands->name . ' - ' .$this->product_unit->name;
         return $this->name. ' - ' .$this->brands->name;
    }

    public function getOrderCountAttribute()
    {
        return Order::whereHas('orderProduct', function ($query) {
            $query->where('product_id', $this->id);
        })->count();
    }

}
