<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;
use DB;
use App\User;
use App\Department;

class AssignDepartment 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 assignDepartment($object)
    {

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

            $department = Department::find($object['department']);
            $user       = User::find($object['user_id']);
           

            if(isset($department->id) && isset($user->id))
            {
            	 $condition  = $this->getCondition();
                 $condition  += ['user_id'=> $user->id];

                 $assigned_user = AssignDepartment::where($condition)->first();
                 
                  if(isset($assigned_user->id))
			            {
			            	$assigned_user->is_recycle = 1;
			            	$assigned_user->update();
			            }
                 $assign_department = new AssignDepartment;

                 $assign_department->user_id       = $user->id;

                 $assign_department->department_id = $department->id;

                $assign_department->save();

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

    public function getUserDepartment($id)
    {
      $condition = $this->getCondition();
      $condition += ['user_id'=> $id];
      return AssignDepartment::where($condition)->with('department')->first();

     
    }

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

    public function minuteSheet()
    {
        return $this->belongsTo(MinuteSheet::class,'minute_sheet_id')->withDefault();
    }
}
