<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Product extends Model
{
    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    protected $fillable = [
        'sku',
        'weight',
        'price',
        'variants',
        'vendor',
        'tags',
        'sizes',
        'colors',
        'materials'
    ];

    public function post()
    {
        return $this->morphOne('App\Post', 'postable');
    }

    public function getImagesAttribute()
    {
        return $this->post->media->sortBy('post.order') ?? null;
    }
    public function getImageAttribute()
    {
        return $this->images->first()->post->image ?? null;
    }

    public function getActualPriceAttribute()
    {
        return $this->price;
    }

    public function getThumbnailAttribute()
    {
        return $this->images->first()->thumbnail ?? null;
    }

    public function getTagsArrayAttribute()
    {
        return explode(',', $this->tags);
    }

    public function getSizesArrayAttribute()
    {
        return explode(',', $this->sizes);
    }

    public function getColorsArrayAttribute()
    {
        return explode(',', $this->colors);
    }

    public function getMaterialsArrayAttribute()
    {
        return explode(',', $this->materials);
    }

    public function getActiveAttribute()
    {
        return $this->price && $this->post->active;
    }

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = str_replace('.', '', $value);
    }
}
