<?php

namespace App;

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

class Level extends Model
{
	use SoftDeletes;
	
	protected $fillable = [
		'code',
		'name',
		'points',
		'parent_id',
		'created_by'
	];
	
	protected $casts = [
		'points'    => 'decimal:2',
		'parent_id' => 'integer',
	];
	
	protected static function boot()
	{
		parent::boot();
		
		static::deleting(function ($employee) {
			$employee->details()->delete();
		});
		
		static::restoring(function ($employee) {
			$employee->details()->withTrashed()->restore();
		});
	}
	
	public function creator()
	{
		return $this->belongsTo(User::class, 'created_by');
	}
	
	public function parent()
	{
		return $this->belongsTo(Level::class, 'parent_id', 'id')
			->with('parent')
			->select('id', 'code', 'name', 'points', 'parent_id', 'created_by')
			->orderBy('code');
	}
	
	public function children()
	{
		return $this->hasMany(Level::class, 'parent_id', 'id')
			->with('children', 'parent')
			->select('id', 'code', 'name', 'points', 'parent_id', 'created_by')
			->orderBy('code');
	}
	
	public function details()
	{
		return $this->hasMany(LevelDetail::class)->with('level')->orderBy('salary_grade_from');
	}
}
