<?php

namespace App\Http\Livewire;

use App\Models\Post;
use Illuminate\Support\Facades\App;
use Livewire\Component;

class SystemAnnouncement extends Component
{
    public $type;
    public int $limit;

    public function mount($type, $limit = 1)
    {
        $this->type = $type;
        $this->limit = $limit ?? 1;
    }

    public function render()
    {
        $locale = App::getLocale();
        $fallbackLocale = config('app.fallback_locale');

        $posts = Post::whereHas('category', function ($query) {
            $query->where('type', $this->type);
        })
        ->whereHas('translations', function ($query) {
            $query->whereDate('from', '<=', now())
                  ->where(function ($query) {
                      $query->whereDate('till', '>', now())->orWhereNull('till');
                  });
        })
        // Apply the same date constraints here to only load active translations
        ->with(['translations' => function ($query) use ($locale, $fallbackLocale) {
            $query->whereIn('locale', [$locale, $fallbackLocale])
                  ->whereDate('from', '<=', now())
                  ->where(function ($query) {
                      $query->whereDate('till', '>', now())->orWhereNull('till');
                  });
        }])
        ->orderByDesc(
            \App\Models\PostTranslation::select('from')
                ->whereColumn('post_id', 'posts.id')
                ->where('from', '<=', now())
                ->where(function ($query) {
                    $query->where('till', '>', now())->orWhereNull('till');
                })
                ->latest('from')
                ->limit(1)
        )
        ->limit($this->limit)
        ->get();


        return view('livewire.system-announcement', [
            'posts' => $posts,
            'locale' => $locale,
            'fallbackLocale' => $fallbackLocale,
        ]);
    }
}