<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use RalphJSmit\Laravel\SEO\Support\HasSEO;
use App\Models\NewsCategory;
use Spatie\Translatable\HasTranslations;

class News extends Model
{
    use HasFactory, SoftDeletes, HasTranslations;

    protected $casts = [
        'on_top' => 'boolean',
        "list_audit_state" => "string",
    ];

    protected $guarded = ['id'];
    protected $appends = ["news_img_pc_url", "news_img_mobile_url", "news_meta_img"];

    public $translatable = ['title', 'written_by', 'description', 'meta_title', 'meta_description', 'meta_keyword'];

    public function newsCategory(){
        return $this->belongsTo(NewsCategory::class);
    }

    public function paragraphs(){
        return $this->hasMany(NewsParagraph::class)->orderBy('order');
    }
    protected function newsImgPcUrl(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => is_null($this->news_img_pc) ? null :Storage::disk('public')->url($this->news_img_pc),
        );
    }
    protected function newsImgMobileUrl(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => is_null($this->news_img_mobile) ? null :Storage::disk('public')->url($this->news_img_mobile),
        );
    }
    protected function newsMetaImg(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => is_null($this->meta_img) ? null :Storage::disk('public')->url($this->meta_img),
        );
    }

    protected function listAuditState(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $this->attributes["visible"] == 1 ? "已發佈" : "暫存",
        );
    }
    protected static function booted()
    {
        static::saving(function ($news) {
            // 如果正在將此記錄設為置頂
            if ($news->isDirty('on_top') && $news->on_top == 1) {
                // 將其他所有記錄的置頂狀態取消
                static::where('id', '!=', $news->id)
                    ->where('news_category_id', $news->news_category_id)
                    ->where('on_top', 1)
                    ->update(['on_top' => 0]);
            }
        });
    }
}
