<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;

class StatTree extends Model
{

    protected $table = 'stat_tree';
    public $timestamps = false;

    public function getRouteKeyName()
    {
        return 'uid';
    }

    public function pro(){
        return $this->hasOne(Pro::class, 'id', 'pro_id');
    }

    public function lines(){
        return $this->hasMany(StatTreeLine::class, 'stat_tree_id', 'id')->orderBy('id', 'ASC');
    }

    public function rootLines(){
        return $this->hasMany(StatTreeLine::class, 'stat_tree_id', 'id')->whereNull('parent_stat_tree_line_id')->orderBy('tree_order_position_index', 'ASC');
    }

    public function instantiateForPro(Pro $pro) {

        // create stat tree
        $instance = new StatTree();
        $nextId = DB::select("select nextval('stat_tree_id_seq')");
        $instance->id = $nextId[0]->nextval;
        $instance->uid = Uuid::uuid4();
        $instance->name = $this->name;
        $instance->model = $this->model;
        $instance->slug = $this->slug . ':' . $pro->uid;
        $instance->is_template = false;
        $instance->pro_id = $pro->id;
        $instance->pro_scope_clause = $this->pro_scope_clause;
        $instance->template_stat_tree_id = $this->id;
        $instance->save();

        // create tree lines
        foreach ($this->rootLines as $line) {
            $line->copy(null, $instance);
        }

        return $instance;

    }

    public function clone($name) {

        // create stat tree
        $instance = new StatTree();
        $nextId = DB::select("select nextval('stat_tree_id_seq')");
        $instance->id = $nextId[0]->nextval;
        $instance->uid = Uuid::uuid4();
        $instance->name = $name;
        $instance->model = $this->model;
        $instance->slug = $this->slug . '-' . rand(100, 999);
        $instance->is_template = $this->is_template;
        $instance->pro_id = $this->pro_id;
        $instance->pro_scope_clause = $this->pro_scope_clause;
        $instance->copied_from_stat_tree_id = $this->id;
        $instance->save();

        // create tree lines
        foreach ($this->rootLines as $line) {
            $line->copy(null, $instance);
        }

        return $instance;

    }
}
