mivita/app/Models/DashboardNews.php
2026-02-20 17:55:06 +01:00

147 lines
3.5 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* App\Models\DashboardNews
*
* @property int $id
* @property string|null $title
* @property string|null $teaser
* @property string|null $content
* @property array|null $trans_title
* @property array|null $trans_teaser
* @property array|null $trans_content
* @property bool $active
* @property \Illuminate\Support\Carbon|null $display_date
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
*
* @mixin \Eloquent
*/
class DashboardNews extends Model
{
protected $table = 'dashboard_news';
protected $casts = [
'trans_title' => 'array',
'trans_teaser' => 'array',
'trans_content' => 'array',
'file_links' => 'array',
'active' => 'boolean',
'display_date' => 'date',
];
protected $fillable = [
'title',
'teaser',
'content',
'trans_title',
'trans_teaser',
'trans_content',
'file_links',
'active',
'display_date',
];
/**
* Get translated value or fallback to default (German)
*/
public function getLang($key)
{
$lang = \App::getLocale();
if ($lang == 'de') {
return $this->{$key};
}
$trans = $this->getTrans($key, $lang);
if (! $trans || $trans == '') {
return $this->{$key};
}
return $trans;
}
/**
* Get specific translation
*/
public function getTrans($key, $lang)
{
$transKey = 'trans_'.$key;
if (! empty($this->{$transKey}[$lang])) {
return $this->{$transKey}[$lang];
}
return '';
}
/**
* Get active news
*/
public static function getActiveNews(): ?self
{
return self::where('active', true)
->orderBy('created_at', 'DESC')
->first();
}
/**
* Get all archived (non-active) news ordered by display date descending
*
* @return \Illuminate\Database\Eloquent\Collection<int, self>
*/
public static function getArchiveNews(): \Illuminate\Database\Eloquent\Collection
{
return self::where('active', false)
->orderBy('display_date', 'DESC')
->orderBy('created_at', 'DESC')
->get();
}
/**
* Get formatted display date or created_at as fallback
*/
public function getDisplayDateFormatted()
{
$date = $this->display_date ?: $this->created_at;
return $date ? $date->format('d.m.Y') : '';
}
/**
* Get file links for current language
*/
public function getFileLinks($lang = null)
{
if (! $lang) {
$lang = \App::getLocale();
}
if (! $this->file_links || ! isset($this->file_links[$lang])) {
return [];
}
return collect($this->file_links[$lang])->map(function ($link) {
if (isset($link['file_id'])) {
$file = \App\Models\DcFile::find($link['file_id']);
if ($file && $file->active) {
return [
'file' => $file,
'label' => $link['label'] ?? $file->original_name,
];
}
}
return null;
})->filter()->values();
}
/**
* Check if news has file links for current language
*/
public function hasFileLinks($lang = null)
{
return count($this->getFileLinks($lang)) > 0;
}
}