<?php

namespace App\Models\Stock;

use App\Models\Company;
use App\Traits\CrudTrait;
use App\Models\Stock\Client;
use App\Scopes\CompanyScope;
use App\Models\Stock\Proforma;
use App\Models\Stock\DeriveryNoteItems;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class DeriveryNote extends Model
{
    use HasFactory, CrudTrait, SoftDeletes;

    protected static function booted()
    {
        static::addGlobalScope(new CompanyScope);
    }

    protected $table = 'delivery_note';

    protected $fillable = [
        'reference',	
        'proforma_ref',
        'code',	
        'company_id',	
        'client_id',
        'date_initiated',	
        'amount',	
        'status',	
        'created_by',
    ];

    protected $casts = [
        'date_initiated' => 'date'
    ];

    protected $appends = ['total_items', 'ProformaRefe'];

        /**
     * @return BelongsTo
     */
    public function client()
    {
        return $this->belongsTo(Client::class, "client_id", 'id')
                    ->select('id', 'name', 'tinnumber', 'phone', 'address')
                    ->withTrashed();
    }

            /**
     * @return BelongsTo
     */
    public function proforma()
    {
        return $this->belongsTo(Proforma::class, "proforma_ref", 'referencem')
                    ->select('DocReference');
    }

            /**
     * @return BelongsTo
     */
    public function company()
    {
        return $this->belongsTo(Company::class, "company_id", 'id')
                    ->select('*')
                    ->withTrashed();
    }


    public function getTotalItemsAttribute()
    {
        return DeriveryNoteItems::where('derivery_id', $this->id)->count();
    }


    public function getProformaRefeAttribute()
    {
        return Proforma::select('DocReference')->where('reference', $this->proforma_ref)->get();
    }
}
