<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use \App\Models\traits\SetConnection;

class TempImage extends Model
{
    use SetConnection;

    protected $fillable = [
        'article_id', 'file_type', 'file_path', 'file_disp', 'property', 'property_sub', 'memo', 'order', 'company_id', 'relation_article_photo_id'
    ];

    const CREATED_AT = null;
    const UPDATED_AT = null;

    public function article()
    {
        return $this->belongsTo(Article::class, "article_id", "building_id");
    }

    //
    public static function getTopImagePath($id)
    {

        $res = TempImage::where('article_id', '=', $id)
        ->where('file_disp', '=', 1)
        ->orderBy('order')
        ->first();
        return $res;
    }

    public static function getImgByArticleId($id)
    {

        $res = TempImage::where('article_id', '=', $id)
	->where("company_id", auth()->user()->company_id)
        ->orderBy('order')
        ->get();
        return $res;
    }

    public static function getCountImgByArticleId($id, $property_sub = null)
    {
        $user = Auth::user();

        $res = RelationArticlePhoto::where('article_id', '=', $id);

        if ($user) {
            $res->where('company_id', $user->company_id);
        }

        if ($property_sub != null) {
            $res = $res->where('property_sub', '=', $property_sub);
        }

        return $res->count();
    }

    public static function getDispImgByArticleId($id, $property_sub = null)
    {

        $res = TempImage::where('article_id', '=', $id)->where("company_id", auth()->user()->company_id);
        if (!empty($property_sub)) {
            $res= $res->where('property_sub', '=', $property_sub);
        }
        $res= $res->orderBy('order')->get();
        return $res;
    }

    public function getStorageLinkAttribute()
    {
        return str_replace('public', '/storage', $this->attributes["file_path"]);
    }
}
