<?php

namespace App\Model;

use App\Helpers\StringOperation;
use Illuminate\Database\Eloquent\Model;
use App\Model\Product;
use Auth;
use File;

class Review extends Model
{

    protected $fillable = ['name', 'body', 'email', 'rating', 'is_active', 'parent_id', 'filename'];

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->user_id = Auth::id();
        });

        static::deleting(function ($model) {
            $photo_root_path = StringOperation::getCompletePathCommentPhotos($model->id, false);;
            File::delete($photo_root_path . $model->filename);
        });
    }

    public function article()
    {
        return $this->belongsTo('App\Model\Article');
    }

    public function user()
    {
        return $this->belongsTo('App\Model\User');
    }

    public function scopeActive($query)
    {
        $query->where('is_active', true);
    }

    public function scopeRecent($query)
    {
        $query->orderByDesc('id');
    }


    public function isActive()
    {
        return $this->is_active;
    }

    public function hasPhoto()
    {
        return $this->filename;
    }

    public function getPhotoUrl()
    {
        return StringOperation::getPhotoUrlFromNumber($this->id, 'comments', $this->filename, false);
    }

    public static function tree(&$reviews = null, $parent_id = 0, $depth = 0)
    {
        // cached?
//        if (self::$tree) {
//            return self::$tree;
//        }
        $tree = collect();
        // feed initial categories
        if ($reviews === null) {
            $reviews = self::get();
        }
        // add to the tree recursively..
        foreach ($reviews as $review) {
            if ($review->parent_id === $parent_id) {
                $review->depth = $depth;
                $review->children = self::tree($reviews, $review->id, $depth + 1);
                $tree->push($review); // $review->toArray();
            }
        }
        // cache if origincal call
//        if ($is_initial_call) {
//            return self::$tree = $tree;
//        }
        return $tree;
    }
}
