<?php

namespace App\Models\Graphics;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Clipart extends Model
{
    use SoftDeletes;
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];

    protected $appends = ['baselineID'];

    // explicitly define tables
    protected $table = 'clipart';

    protected $fillable = [
        'owner_id', 'name','description', 'citations', 'paid','type','path','filename', 'created_by','thumb'
    ];

    //
    public function colourways()
    {
        return $this->hasMany('App\Models\Graphics\Clipart_colourway', 'clipart_id', 'id');
    }



    // clipart tags
    public function tags()
    {
        return $this->belongsToMany('App\Models\Tag', 'clipart_tags', 'tag_id', 'clipart_id');
    }

    // clipart owner
    public function owner()
    {
        return $this->hasOne('App\Models\Auth\User', 'id', 'owner_id');
    }

    // scope for free clipart
    public function scopeFree($query){
        return $query-> where('paid', '<>', '1');
        ;
    }

    // filter by tags
    public function scopeWithTags($query, $tags)
    {
        return $query->whereHas('tags', function($q) use ($tags){
            $q->whereIn('tags.id',$tags);
        });
    }

    // get the ID of the baseline
    public function getBaselineIDAttribute()
    {
        $baseline = $this->colourways->where('colour_name', '=', 'baseline')->first();
        return $baseline?$baseline->id:null;
    }

    public function getAvailableColourwaysNamesAttribute()
    {
        return $this->colourways->pluck('colour_name');
    }

}
