<?php

namespace App;

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

class Allowance 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 getAllowanceList()
    {
        return Allowance::where($this->getCondition())->orderBy('id','desc')->get();
    }

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

            

          $allowance                    = new Allowance;
          $allowance->title             = $object['title'];
          $allowance->is_taxable        = $object['is_taxable'];
          $allowance->type              = ucwords($object['type']);
          $allowance->amount            = $object['amount'];
          $allowance->percentage        = $object['percentage'];


          $allowance->save();


            return with($allowance);
          

        });
    }

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

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


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

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

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

    

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

    }

    public function updateAllowance($object)
    {

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

       $allowance = Allowance::find($object['id']);

        if(isset($allowance->id))
            {
      
           
          $allowance->title             = $object['title'];
          $allowance->type              = ucwords($object['type']);
          $allowance->amount            = $object['amount'];
          $allowance->percentage        = $object['percentage'];
          $allowance->is_taxable        = $object['is_taxable'];

        

             $allowance->update();

                return with($allowance);
                
                return 1;
            }
            
            return 0;
        });
    }
}
