<?php

namespace App\Models\Registries;

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 Category extends Model {
    use UuidScopeTrait, SoftDeletes, RelationValuesTrait;

    protected $table = 'registry_categories';

    protected $dates = [
    ];

    protected $fillable = [
        'uuid',
        'registry_id',
        'parent_id',
        'name',
        'ord'
    ];

    protected $hidden = [
        'id'
    ];


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

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

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

    public function entries(): HasMany {
        return $this->hasMany(Entry::class);
    }



    public function move($ord, ?Category $parent = null, ?Registry $registry = null) {
        $prevParent = $this->parent;
        if (($parent->id ?? 0) === ($prevParent->id ?? 0)) {
            ($ord > $this->ord) ? $this->moveSet('backward', $this->ord, $ord, $parent) : $this->moveSet('forward', $ord, $this->ord, $parent);
        } else $this->moveSet('forward', $ord, null, $parent);
        $this->update(['parent_id' => $parent->id ?? 0, 'ord' => $ord]);
        $this->trimIndexes([$prevParent->id ?? 0, $parent->id ?? 0]);
    }
    public function moveSet($dir = 'forward', $ordFrom = null, $ordTo = null, ?Category $parent = null) {
        $query = $parent ? $parent->children() : $this->registry->rootCategories();
        if ($ordFrom !== null) $query->where('ord', '>=', $ordFrom);
        if ($ordTo !== null) $query->where('ord', '<=', $ordTo);
        $query->get()->each(function($category) use($dir) {
            $category->update(['ord' => ($dir === 'forward') ? ($category->ord + 1) : ($category->ord - 1)]);
        });
    }
    public function trimIndexes($parentIds) {
        collect(is_array($parentIds) ? $parentIds : [$parentIds])->unique()->each(function($parentId) {
            $this->registry->categories()->where(['parent_id' => $parentId])->orderBy('ord')->orderBy('id')->get()->each(function($category, $index) {
                if ($category->ord !== $index) $category->update(['ord' => $index]);
            });
        });
    }
    public function getMaxOrd(): int {
        $res = $this->parent ? $this->parent->children()->max('ord') : $this->registry->rootCategories()->max('ord');
        return ($res !== null) ? ($res + 1) : 0;
    }


    public function addCategory(string $name): ?Model {
        $res = $this->children()->where(['name' => $name])->first();
        if (!$res) {
            $res = $this->children()->create(['registry_id' => $this->registry_id, 'name' => $name]);
            $res->update(['ord' => $res->getMaxOrd()]);
        }
        return $res;
    }

}
