<?php
namespace App\Models\Stock;

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

class SaleItem extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'sale_id',
        'item_id',
        'batch',
        'quantity',
        'price',
        'cost_price',
        'amount',
        'comment'
    ];

    /**
     * Here Item is for POs
     * Product for Production Sales - coz it comes with stock quantity and price
     */
    protected $appends = ['item', 'product','product_change'];
    protected $hidden = ['item', 'product'];
   

    public function sale()
    {
        return $this->belongsTo(Sale::class, "sale_id", "id");
    }

    /**
     * Get Sold Item Details
     * @return \Illuminate\Support\Collection
     */
    public function getItemAttribute()
    {
        return Product::select('products.name', 'products.code', 'products.pcode', 'units.name As unit')
                        ->leftJoin('units', 'products.unit_id', '=', 'units.id')
                        ->where('products.id', $this->item_id)
                        ->first();
    }


    public function expiry()
    {
        return $this->hasOne(StockinHistory::class, 'product_id', 'item_id')
            ->selectRaw('product_id, MAX(expiration_date) as latest_expiry_date')
            ->groupBy('product_id');
    }

    /** Get Product Change for specific batch */

    public function getProductChangeAttribute(){
        return ProductChange::where('product_id', $this->item_id)
                      ->where('batch_nber', $this->batch)
                      ->first();
    }

    /**
     * Get Production item details
     * @return \Illuminate\Support\Collection
     */
    public function getProductAttribute()
    {
        return Product::select('products.id','units.name As unit', 'products.name', 'products.quantity', 'products.code')
                        ->leftJoin('units', 'products.unit_id', '=', 'units.id')
                        ->where('products.id', $this->item_id)
                        ->first();
    }
}