<?php

namespace App\Models;

use App\Traits\ShowCreatedUpdatedDeletedDate;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Blog extends Model {
	use HasFactory, SoftDeletes;
	use ShowCreatedUpdatedDeletedDate;

	public $fillable = [
		'blog_category_id',
		'title',
		'subtitle',
		'slug',
		'descr',
		'content',
		'image',
		'scheduling_date',
		'count_views',
		'count_comments',
		'count_likes',
	];

	protected static function boot() {
		parent::boot();

		static::creating(function ($model) {
			$model->slug = Str::slug($model->title);
		});
	}

	public function setSchedulingDateAttribute($value) {
		// YYYY/MM/DD
		$this->attributes['scheduling_date'] = implode('-', array_reverse(explode('/', $value)));
	}

	public function getSchedulingDateAttribute($value) {
		if (empty($value)) return '';

		// DD/MM/YYYY
		$value = explode(' ', $value)[0];
		return implode('/', array_reverse(explode('-', $value)));
	}

	public function blogCategory() {
		return $this->belongsTo(BlogCategory::class);
	}
}
