<?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 = $item['children'] ?? false ? self::getChildren($item['children']) : false;
            if ($children) {
                $leaf['children'] = $children;
            }
            $tree[] = $leaf;
        }

        return $tree;
    }

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

        switch ($type) {
            case 'after':
                $item->afterNode($item_target);
                break;
            case 'inside':
                $item_target->appendNode($item);
                break;
            default:
                $item->afterNode($item_target);
        }

        return $item->save();
    }

    public static function create($data, $model)
    {
        $parent = $data['parent_id'] ?? false ? self::getNode($data['parent_id'], $model) : self::getRoot($model);
        $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($model)
    {
        return self::getNode(1, $model);
    }

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