<?php

namespace Hilco\Models;

use Illuminate\Support\Facades\Auth;
use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
 * Hilco\Models\WebLandingPage
 *
 * @property integer $id
 * @property string $position
 * @property string $title
 * @property string $date_modified
 * @property string $date_created
 * @property string $deleted_at
 */
class WebLinkCategory extends WebModel {

    protected $table = "WebLinkCategories";
    protected $fillable = ['user_visibility','position','title','order','webSiloIds'];
    public static $userVisibility = ['Hidden', 'Visible For All', 'For Anonymous User', 'For Logged In User'];
    public static $positions =['hb2b-footer'=>'Hilco footer','hb2b-header'=>'Hilco header'];

    public function links() {
        return $this->hasMany(WebLink::class, 'web_link_category_id');
    }

    public function webSilos() {
        return $this->belongsToMany(WebSilo::class, 'WebLinkCategory_WebSilo', 'weblinkcategory_id', 'websilo_id');
    }

    public function setWebSiloIdsAttribute($ids) {
        $this->webSilos()->sync($ids);
    }

    public function scopeAvailableForUser($query){
        $user = Auth::user();
        if(isset($user)){
            $query = $query->whereRaw('WebLinkCategories.user_visibility IN (1, 3)');
        }else{
            $query = $query->whereRaw('WebLinkCategories.user_visibility IN (1, 2)');
        }

        $activeWebSiloId = b2b()->activeWebSilo()->id;
        return $query->forWebSilo($activeWebSiloId);
    }

    public function scopeInFooter($query){
        return $query->where('position', 'hb2b-footer');
    }

    public function scopeForWebSilo ($query, $webSiloId) {
        return $query->whereRaw(
            "EXISTS (
                SELECT 1 
                FROM WebLinks 
                WHERE WebLinks.web_link_category_id = WebLinkCategories.id 
                AND WebLinks.deleted_at = 0 
                AND EXISTS (
                    SELECT 1 
                    FROM WebLink_WebSilo 
                    WHERE WebLinks.id = WebLink_WebSilo.weblink_id 
                    AND WebLink_WebSilo.websilo_id = ? 
                    AND WebLink_WebSilo.deleted_at = 0
                )
            )",
            [$webSiloId]);
    }

    public function getTitleAttribute() {
        $translatedName = $this->getTranslation('name');
        if (!strlen($translatedName)) $translatedName = $this->attributes['title'];
        return $translatedName;
    }

    public function getDisplayNameForUACAttribute() {
        return $this->getTitleAttribute();
    }

    use HasModelTranslations;

}
