<?php

namespace App\Models\Companies;

use App\Models\User;
use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Department extends Model {
    use UuidScopeTrait, SoftDeletes, RelationValuesTrait;

    protected $table = 'company_departments';

    protected $dates = [
    ];

    protected $fillable = [
        'uuid',
        'company_id',
        'parent_id',
        'name',
        'title',
        'level'
    ];

    protected $hidden = [
    ];

    public function company(): BelongsTo {
        return $this->belongsTo(Company::class);
    }

    public function parent(): BelongsTo {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function children(): HasMany {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function members(): HasMany {
        return $this->hasMany(CompanyMember::class);
    }
    public function management(): HasMany {
        return $this->members()->whereIn('rank', [CompanyMemberRank::VICE, CompanyMemberRank::CHIEF]);
    }
    public function vices(): HasMany {
        return $this->members()->where(['rank' => CompanyMemberRank::VICE]);
    }
    public function employees(): HasMany {
        return $this->members()->where(['rank' => CompanyMemberRank::EMPLOYEE]);
    }


    public function getChiefAttribute() {
        return $this->members()->where(['rank' => CompanyMemberRank::CHIEF])->first();
    }


    public function addChildren($name, $title): ?Department {
        $result = null;
        if (($name = trim($name)) && ($title = trim($title))) {
            $result = $this->company->departments()->firstOrCreate(['name' => $name]);
            $result->update(['title' => $title, 'parent_id' => $this->id, 'level' => ++$this->level]);
        }
        return $result;
    }

    public function addMember(User $user, $position = null): Model {
        return $this->members()->firstOrCreate(['company_id' => $this->company_id, 'user_id' => $user->id, 'position' => $position]);
    }

    public function isMember(CompanyMember $member): bool {
        return $this->members()->where(['id' => $member->id])->exists();
    }

    public function isParentFor(Department $department): bool {
        while ($parent = $department->parent) {
            if ($parent->id === $this->id) return true;
            $department = $department->parent;
        }
        return false;
    }

}
