<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Gallery extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
        'image','link'
    ];

    public function getUrlAttribute()
    {
        $url = $this->status == 'video' ? asset($this->video) : $this->link;
        return $url;
    }

    public function descriptions($language_id= null)
    {

        if ($language_id) {
            $data = $this->hasMany(GalleryDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(GalleryDescription::class)->first();
            }

            return $data;
        }
        $data = $this->hasMany(GalleryDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }


    public static function withDescription($gallery_id = null)
    {
        $query = self::orderByDesc('galleries.id')->join('gallery_descriptions as ad', 'ad.gallery_id', 'galleries.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['galleries.created_at', 'ad.*']);

        if ($gallery_id)
        {
            if (is_array($gallery_id))
            {
                $query->whereIn('galleries.id', $gallery_id);
            }
            else
            {
                $query->where('galleries.id', $gallery_id);
            }
        }
        $query->select([
            'galleries.*',
            'ad.name',
            'ad.description',
            'ad.link as link_url'
        ]);
        return $query;
    }
}
