<?php
namespace App\Models\Stock;

use App\Models\Stock\StockinHistory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\Stock\ProductChange;

class ProformaItem extends Model
{
    protected $table = 'proforma_items';
    protected $fillable = [
        'proforma_id',
        'product_id',	
        'batch',
        'requested_qty',	
        'received_qty',
        'price'
    ];

    //protected $appends = ['stock_quantity'];
    protected $appends = ['product_change'];
    /**
     * @return BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id')
                    ->select('products.id', 'products.name','products.packaging', 'products.code', 'products.pcode', 'units.name as unit', 'product_categories.name as category', 'products.quantity')
                    ->leftJoin('units', 'products.unit_id', '=', 'units.id')
                    ->leftJoin('product_categories', 'products.category_id', '=', 'product_categories.id');
    }

   /**
     * @return BelongsTo
     */
    public function expiry()
    {
        return $this->belongsTo(StockinHistory::class, 'product_id', 'product_id')
                    ->select('product_id', 'expiration_date')
                    ->withTrashed();
    }

    /** Get Product Change for specific batch */
    public function getProductChangeAttribute(){
        return ProductChange::where('product_id', $this->product_id)
                      ->where('batch_nber', $this->batch)
                      ->first();
    }

    /**
    *  Get Quantity for MENU & PRODUCTION ITEMS
    */

    public function getStockQuantityAttribute(){
        return Stock::where('product_id', $this->product_id)
                      ->whereNull('branch_id')
                      ->sum('quantity');
    }
}
