<?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 Product extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
        'image','date','hours','city_id','category_id','publish'
    ];

    public function category()
    {
        return $this->belongsTo(Category::class)->withTrashed();
    }
    public function city()
    {
        return $this->belongsTo(City::class)->withTrashed();
    }

    public function getImageUrlAttribute()
    {
        return asset($this->image);
    }

    public function getUrlApplyAttribute()
    {
        $link = route('apply_course',$this->id);
        return $link;
    }
    public function getDateTimeAttribute()
    {
        $time = date('D',strtotime($this->date));
        $date = $time .', ';
        $date .= date('Y/m/d',strtotime($this->date));
        return $date;
    }

    public function getUrlAttribute()
    {
        return route('courses.show',$this->id);
    }

    public function details($language_id= null)
    {
        return $this->hasOne(ProductDescription::class)->where('language_id', currentLanguage()['id']);
    }
    public function descriptions($language_id= null)
    {

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

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

    public function photos() :hasMany
    {
        return $this->hasMany(ProductPhoto::class);
    }

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

        if ($product_id)
        {
            if (is_array($product_id))
            {
                $query->whereIn('products.id', $product_id);
            }
            else
            {
                $query->where('products.id', $product_id);
            }
        }
        $query->select([
            'products.*',
            'ad.name',
            'ad.description',
            'ad.details',
        ]);
        return $query;
    }
}
