<?php

namespace FluxCms\Core\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;

class CmsNewsItem extends Model
{
    use HasTranslations;

    protected $table = 'flux_cms_news_items';

    protected $fillable = [
        'icon',
        'text',
        'title',
        'excerpt',
        'content',
        'image',
        'date',
        'author',
        'link',
        'pdf_path',
        'pdf_open_text',
        'pdf_download_text',
        'is_published',
        'order',
    ];

    /** @var array<string> */
    public array $translatable = [
        'text',
        'title',
        'excerpt',
        'content',
        'pdf_open_text',
        'pdf_download_text',
    ];

    protected function casts(): array
    {
        return [
            'text' => 'array',
            'title' => 'array',
            'excerpt' => 'array',
            'content' => 'array',
            'pdf_open_text' => 'array',
            'pdf_download_text' => 'array',
            'date' => 'date',
            'is_published' => 'boolean',
            'order' => 'integer',
        ];
    }

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('order');
    }

    /**
     * @return array<string, mixed>
     */
    public function toFrontendArray(?string $locale = null): array
    {
        $locale = $locale ?? app()->getLocale();

        return [
            'icon' => $this->icon,
            'text' => $this->getTranslation('text', $locale),
            'title' => $this->getTranslation('title', $locale),
            'excerpt' => $this->getTranslation('excerpt', $locale),
            'content' => $this->getTranslation('content', $locale),
            'image' => $this->image ? media_url($this->image) : '',
            'date' => $this->date?->format('Y-m-d'),
            'author' => $this->author,
            'link' => $this->link,
            'pdf_path' => $this->pdf_path ? media_url($this->pdf_path) : '',
            'pdf_open_text' => $this->getTranslation('pdf_open_text', $locale),
            'pdf_download_text' => $this->getTranslation('pdf_download_text', $locale),
        ];
    }
}
