<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Causal extends Model
{
    use HasFactory;

    protected $fillable = [
        'parent_id',
        'name',
        'type',
        'money',
        'corrispettivo_fiscale',
        'no_receipt',
        'user_status',
        'no_first',
        'no_records',
        'enabled',
        'no_reports',
    ];


    public function childs() {
        return $this->hasMany(\App\Models\Causal::class,'parent_id','id') ;
    }

    public function getTree()
    {
        $str = '';
        if ($this->parent_id != null)
        {
            $a = $this->recursiveName($this->parent_id, array($this->name));
            $a = array_reverse($a);
            $str = implode(" - ", $a);
        }
        else
        {
            $str = $this->name;
        }
        return $str;
    }

    public function recursiveName($parent_id, $array)
    {
        $x = \App\Models\Causal::findOrFail($parent_id);
        $array[] = $x->name;

        if ($x->parent_id != null)
        {
            return $this->recursiveName($x->parent_id, $array);
        }
        else
        {
            return $array;
        }
    }

    public function recursiveParent($parent_id, $array)
    {
        if ($parent_id == null)
            return $array;
        $x = \App\Models\Causal::findOrFail($parent_id);
        $array[] = $x->id;

        if ($x->parent_id != null)
        {
            return $this->recursiveParent($x->parent_id, $array);
        }
        else
        {
            return $array;
        }
    }

}
