<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Attribute extends Model
{
    protected $primaryKey = 'atr_id';

    public function values() {
        return $this->hasMany("App\AttributeValue", 'atr_id', 'atr_id');
    }

    public function categories()
    {
        return $this->belongsToMany('App\Category', 'attribute_category', 'atr_id', 'cat_id');
    }

    public function products()
    {
        return $this->belongsToMany('App\Product', 'product_attribute_values', 'atr_id', 'atr_id');
    }


    public function translations() {
        return $this->hasMany("App\AttributeTranslation", 'atr_id', 'atr_id');
    }

    public function translation($lang) {
        return $this->hasOne("App\AttributeTranslation", 'atr_id', 'atr_id')->where('lang', '=', $lang)->first();
    }

    public function ctranslation() {
        return $this->hasOne("App\AttributeTranslation", 'atr_id', 'atr_id')->where('lang', '=', app()->getLocale());
    }





    // Admin custom methods

    public static function getAttributeWithValues($atrid){

        $data = collect(DB::select(
                'SELECT a.atr_id, at.atr_name, at.`atr_displ_name`, a.`atr_type`, av.atr_val_id, avt.atr_value  
                       FROM attribute_values av 
                       INNER JOIN attribute_value_translations avt  ON av.atr_val_id = avt.atr_val_id AND avt.lang = :lang
                       INNER JOIN attributes a  ON av.atr_id = a.atr_id
                       INNER JOIN attribute_translations at  ON a.atr_id = at.atr_id AND at.lang = :lang
                       WHERE av.atr_id = :id  ORDER BY av.atr_val_id',
                [':id' => $atrid, ':lang' => app()->getLocale()]
        ));

        return $data;
    }

    public static function getAttributeExtendedData($atrid){

        $data = collect(DB::select(
            'SELECT a.atr_id, at.atr_name, a.atr_type, at.atr_displ_name, av.atr_val_id, avt.atr_value  
                   FROM attribute_values av 
                   INNER JOIN attribute_value_translations avt  ON av.atr_val_id = avt.atr_val_id AND avt.lang = :lang
                   INNER JOIN attributes a  ON av.atr_id = a.atr_id
                   INNER JOIN attribute_translations at  ON a.atr_id = at.atr_id AND at.lang = :lang
                   WHERE av.atr_id = :id  ORDER BY av.atr_val_id',
            [':id' => $atrid, ':lang' => app()->getLocale()]
        ));

        return $data;
    }
}
