<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use App\Traits\ModelTimeFormat;

use App\Traits\ModelLogChanging;

class WMSReflectReceive extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    protected $fillable=['id_rejected_bill','is_uploaded','ASNNO','WAREHOUSEID','CUSTOMERID','ASNTYPE','ASNREFERENCE1',
        'ASNREFERENCE2','ASNREFERENCE3','NOTES','USERDEFINE1','USERDEFINE2','USERDEFINE3'];
    function skus(){
        return $this->hasMany('App\WMSReflectReceiveSku','wms_receive_id','id');
    }
    function bill(){
        return $this->belongsTo('App\RejectedBill','id_rejected_bill','id');
    }

    /**
     * @param $logisticNumberReturn
     * @param bool $withOutUploaded
     * @return Collection
     */
    static function downloadedSkus($logisticNumberReturn, $withOutUploaded=false){
        $wmsReceives=WMSReflectReceive::with('skus')->where('ASNREFERENCE3',$logisticNumberReturn);
        if($withOutUploaded)
            $wmsReceives=$wmsReceives->where('is_uploaded',0);
        $wmsReceives=$wmsReceives->get();
        $downloadedItems=[];
        foreach ($wmsReceives as $wmsReceive){
            $wmsReceive->skus()->each(function (WMSReflectReceiveSku $sku)use(&$downloadedItems){
                $repeated=false;
                foreach($downloadedItems as $item){
                    if($item['id']==$sku['id']){
                        $repeated=true;
                        break;
                    }
                }
                if(!$repeated){
                    $downloadedItems[]=$sku;
                }
            });
        }
        return new Collection($downloadedItems);
    }
}
