<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class HierarchyController extends Controller
{
    public function index()
    {
        $cid = auth()->user()->company_id;

        $elements = User::select('name', 'id','parent_id')->get()->toArray();
        $childs = $this->bulidItems($elements);

        dd($childs);

        $roles = roleSelect();
        return view('hierarchy.structure', compact('users', 'childrens', 'roles'));
    }

    function bulidItems(array $elements, $parentId = NULL) 
    {
        $child = array();    

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {

                $children = $this->bulidItems($elements, $element['id']);

                    if (!empty($children) > 0 ) {
                        $element['children'] = $children;
                    }

                $child[] = $element;
            }
        }

        return $child;
    }
}
