<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Asset extends Model
{
    private $generic_condition;

   public function __construct()
    {
           
       $this->setCondition(['is_recycle' => '0']);
    }

    public function setCondition($condition = [])
    {
        $this->generic_condition = $condition;
    }

    public function getCondition()
    {
        return $this->generic_condition;
    }

      public function getAssetList()
    {
        return Asset::where($this->getCondition())->orderBy('id','desc')->get();
    }

    public function getAssetById($id)
    {
      
       $condition = $this->getCondition();
       $condition += ['id' => $id];
        return Asset::where($condition)->first();

    }

    public function getDistinctAsset($distinct_column,$column = "*")
    {
      $condition = $this->getCondition();

      return Asset::where($condition)->distinct($distinct_column)->select($column)->get();
    }

        public function storeAsset($object)
    {
        return \DB::transaction(function () use ($object)  {

            

          $asset                        = new Asset;
          $asset->asset_code            = $object['code'];
          $asset->name                  = $object['name'];
          $asset->type                  = ucwords($object['type']);
          $asset->description           = $object['description'];
          $asset->save();


            return with($asset);
          

        });
    }

    public function getUnAssignedAssetList($contract_id)
    {
        $condition = $this->getCondition();

        $other_condition = ['contract_details.contract_id' => $contract_id] + $this->getCondition();

          return Asset::where($condition)->whereNotExists( function ($query) use ($other_condition) {
              $query->select(DB::raw(1))
              ->from('contract_details')
              ->whereRaw('assets.id = contract_details.asset_id')
              ->where($other_condition);
              
          })->get();

    

    }

    public function updateAsset($object)
    {

       return \DB::transaction(function () use ($object) {

       $asset = Asset::find($object['asset']);

        if(isset($asset->id))
            {
      
           
          $asset->name              = $object['name'];
          $asset->asset_code              = $object['code'];
          $asset->description       = $object['description'];

          $asset->update();

                return with($asset);
                
            
            }
            
            return 0;
        });
    }
}
