<?php

namespace App\Models;

use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use App\Traits\TaggableTrait as Taggable;
use Laracasts\Presenter\PresentableTrait;

class Product extends Model
{
    use Taggable, PresentableTrait, ModelTrait;

    protected $presenter = 'App\Presenters\ContentPresenter';

    protected $table = 'products';

    protected $guarded = ['tags', 'referer', 'description', 'attrs', 'download_id', 'intros'];

    protected $casts = [
        'page_ids' => 'collection',
    ];

    public function cates()
    {
        return $this->belongsTo(ProductCate::class, 'pid');
    }

    public function brand()
    {
        return $this->belongsTo(Manufacturer::class, 'manufacturer_id', 'manufacturer_id');
    }

    public function description()
    {
        $lang = config('lang') ?: config('setting.lang');

        if (config('visit') == 'frontend' && config('lang') != config('setting.lang')) {
            return $this->hasOne(ProductDescription::class)->whereIn('lang', [config('lang'), config('setting.lang')])->orderByRaw(\DB::raw("FIELD(lang, '". config('lang') ."', '". config('setting.lang') ."')"));
        } elseif (config('visit') == 'admin' && config('managerLang') != config('setting.lang')) {
            return $this->hasOne(ProductDescription::class)->whereIn('lang', [config('managerLang'), config('setting.lang')])->orderByRaw(\DB::raw("FIELD(lang, '". config('managerLang') ."', '". config('setting.lang') ."')"));
        }

        return $this->hasOne(ProductDescription::class)->where('lang', $lang);
    }

    /**
     * 属于该产品的下载。
     */
    public function downloads()
    {
        return $this->belongsToMany(Download::class);
    }

    public function attrs()
    {
        $lang = config('lang') ?: config('setting.lang');

        return $this->hasMany(ProductAttribute::class, 'product_id')->where('lang', $lang);
    }
}
