<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Auth;
use DB;
use Crypt;
use App\User;

class Leave 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 storeLeave($object)
    {
          
        return DB::transaction(function () use ($object){
        
            $leave = new Leave;

            $leave->user_id      = $object['employee'];
            $leave->start_date   = $object['start_date'];
            $leave->end_date     = $object['end_date'];
            $leave->no_of_hours  = $object['no_of_hours'];
            $leave->type         = $object['type'];
            $leave->reason       = $object['reason'];
            $leave->status       = 'Pending';

            $leave->save();

            return with($leave);
        });

    } 


    // Updating leave modal data

    public function updateLeave($object)
    {
          
        return DB::transaction(function () use ($object){
        
            $leave = Leave::find($object['leave']);
             
          if(isset($leave->id))
          {

            $leave->start_date   = $object['start_date'];
            $leave->end_date     = $object['end_date'];
            $leave->no_of_hours  = $object['no_of_hours'];
            $leave->type         = $object['type'];
            $leave->reason       = $object['reason'];
            $leave->status       = $object['status'];

            $leave->update();
           }

            return with($leave);
        });

    } 

    
     //RETRIEVING leave BY ID
    public function getLeaveById($id)
    {
      
       $condition = $this->getCondition();
       $condition += ['id' => $id];
        return leave::where($condition)->first();

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

    }
    
    

    // ALL FORIGN KEY RELATIONSHIP FUNCTION
    public function designation()
    {
        return $this->belongsTo(Designation::class,'designation_id')->withDefault();
    }

    public function user()
    {
        return $this->belongsTo(User::class,'user_id')->withDefault();
    }


    // END ALL FORIGN KEY RELATIONSHIP FUNCTION


    // Storing leave modal data

    
     
}
