<?php

namespace App\Repositories\Core;

class Trees
{
    public static function getTree($model)
    {
        $tree = $model->orderBy('_lft', 'asc')->get()->toTree()->toArray();
        return self::getChildren($tree[0]['children']);
    }

    public static function getChildren($data)
    {
        $tree = [];
        foreach ($data as $item) {
            $leaf = [];
            $leaf['name'] = $item['name'];
            $leaf['id'] = $item['id'];
            $children = (isset($item['children'])) ? self::getChildren($item['children']) : false;
            if ($children) {
                $leaf['children'] = $children;
            }
            $tree[] = $leaf;
        }
        return $tree;
    }

    public static function moveTree($node_id, $target_id, $type)
    {
        $item = self::getNode($node_id);
        $item_target = self::getNode($target_id);

        switch ($type) {
        case 'after':
            // dump("$node_id After $target_id");
            $item->afterNode($item_target);
            break;
        case 'inside':
            // dump("$node_id inside $target_id");
            $item_target->appendNode($item);
            break;
        }
        $item->save();
        return "1";
    }


    public static function create($data, $model)
    {
        $parent = (isset($data['parent_id']) && $data['parent_id']) ? self::getNode($data['parent_id']) : self::getRoot();
        $tree = $model->create(['name' => $data['name']]);
        $tree->appendToNode($parent)->save();
        return $tree;
    }

    public static function update($data, $id = false)
    {
        $id = $id ? $id : $data['id'];
        $item = self::get($id);
        return $item->update(['name' => $data['name']]);
    }

    public static function destroy($id)
    {
        // return Category::destroy($id);
    }

    public static function getRoot()
    {
        return self::getNode(1);
    }

    public static function getNode($id, $model)
    {
        return $model->find($id);
    }
}
