<?php

namespace App\Models;

use App\Classes\General\PublicConstants;
use App\Classes\Helpers\FileHelper;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use function Termwind\renderUsing;

class Blog extends Model
{     
    protected $fillable = ['title','slug', 'user_id', 'category_id', 'banner', 'excerpt', 'para1', 'para2', 'para3', 'para4', 'para5'];
    public static function rules($id = null)
    {
        return [
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:blogs,slug' . ($id ? ',' . $id : ''),
            'category_id' => 'nullable|string|max:255',
            'BannerFile' => 'nullable|image|max:2048',
            'excerpt' => 'nullable|string|max:500',
            'para1' => 'nullable|string',
            'para2' => 'nullable|string',
            'para3' => 'nullable|string',
            'para4' => 'nullable|string',
            'para5' => 'nullable|string'
        ];
    }
    public function Category()
    {
        return $this->belongsTo(BlogCategory::class);
    }
    public function User(){
        return $this->belongsTo(User::class);
    }
    protected function bannerUrl(): Attribute
    {
        return Attribute::make(
            get: fn () =>FileHelper::FileLink(PublicConstants::BLOG_IMAGE_PATH, $this->banner)
        );
    }
    protected function TwoLineDescription():Attribute
    {
        return Attribute::make(
            get: function(){
                if($this->para1 == null || $this->para2 == '')
                    return '';
                $Lines= explode('.',$this->para1);
                $Lines=$Lines[0].$Lines[1]??'';
                if(strlen($Lines) > 255)
                    return  substr($Lines, 0, 255) . '...';                
                return $Lines;
            }
        );
    }
}
