<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Department extends Model
{
	use SoftDeletes;
	
	protected $fillable = [
		'name', 'code', 'parent_id', 'is_activated'
	];
	
	protected $casts = [
		/*'is_activated' => 'boolean'*/
	];
	
	public function parent()
	{
		return $this->belongsTo(Department::class, 'parent_id')->with('parent');
	}
	
	public function children()
	{
		return $this->hasMany(Department::class, 'parent_id');
	}
	
	public function employees()
	{
		return $this->hasMany(Employee::class);
	}
	
	public function scopeIsActivated($query)
	{
		return $query->where('is_activated', true);
	}
	
	public function allChildren()
	{
		return $this->children()->with('allChildren');
	}
	
	public static function getAllChildrenIds($departmentId)
	{
		$department = self::with('allChildren')->find($departmentId);
		return self::extractIds($department);
	}
	
	private static function extractIds($department)
	{
		$ids = [$department->id];
		
		foreach ($department->allChildren as $child) {
			$ids = array_merge($ids, self::extractIds($child));
		}
		
		return $ids;
	}
}