<?php

namespace App\Models;

use App\Helpers\ImageHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class Page extends Model
{
    // Fields that mass assignment
    protected $fillable = ['image','image_second', 'status'];

    // Use soft delete
    use SoftDeletes;

    /**
     * Get description for pages
     * @return HasMany
     */
    public function descriptions() :HasMany
    {
        return $this->hasMany(PageDescription::class);
    }

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

    public function items() :HasMany
    {
        return $this->hasMany(Item::class,'page_id');
    }

    public static function withDescription($page_id = null)
    {
        $query = self::join('page_descriptions as sd', 'sd.page_id', 'pages.id')
            ->where('sd.language_id', currentLanguage()->id)
            ->select(['pages.created_at', 'sd.*']);

        if ($page_id){
            if (is_array($page_id))
            {
                $query->whereIn('pages.id', $page_id);
            }
            else
            {
                $query->where('pages.id', $page_id);
            }
        }

        $query->select([
            'pages.id',
            'pages.image',
            'sd.title',
            'sd.slug',
            'sd.meta_description',
            'sd.keywords',
            'sd.description',
        ]);
        return $query;
    }

}
