<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Translatable\HasTranslations;

/**
 * Class ProductionPackaging
 * @package App\Models
 * @version October 11, 2019, 10:41 pm UTC
 *
 */
class ProductionPackaging extends CRUDAwareModel
{

    public $table = 'production_packagings';

    protected $primaryKey = 'packing_id';

    public $incrementing = false;
    

    protected $dates = ['deleted_at'];


    public $fillable = [
        'packing_id',
        'qty',
        'narration',
        'weight'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'qty' => 'float',
        'weight' => 'float'
    ];

    /**
     * Validation rules
     *
     * @var array
     */
    public static $rules = [
        
    ];

    public static function getTotalPackedQty($materialId){
        $qty = \App\Models\ProductionPackagingDetail::where('material_id','=',$materialId)->sum('qty');
        if(empty($qty)){
            return 0;
        }
        return $qty;
     }

     public static function getBondData($packingId){
        $packingDetail = ProductionPackagingDetail::where('packing_id','=', $packingId)->orderBy('qty', 'DESC')->first();
        $bondMaterial = $packingDetail->material;
        $object = new \stdClass();
        $bondProduct = $bondMaterial->bondproduct;
        $object->product_name = $bondProduct->name; 
        $object->bond_name = $bondProduct->bond->name; 
        $object->size = $bondProduct->design->size_print;
        $object->product_desc = $bondProduct->type->name;
        $object->hsn_code = $bondProduct->hsn_code;
        $object->category = $bondProduct->category;
        $object->unit = $bondProduct->unit->alias;
        return $object;
     }

    public function packingDetail(){
        return ProductionPackagingDetail::where('packing_id','=', $this->packing_id)->orderBy('created_at', 'DESC')->get();
    }


    public static function updateQty($id){
        $productionPackaging= ProductionPackaging::find($id);   
        $productionPackaging->qty = ProductionPackagingDetail::where('packing_id','=', $id)->sum('qty');
        $productionPackaging->save();
    }
    
}
