<?php

namespace App\Http\Livewire;

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

class EventCalendarPost extends Component
{
    public $type;
    public int $limit;
    public bool $hideAuthor = false;
    public bool $showFallback = false;
    public bool $fallbackExists = false; // Add this new property

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

    public function loadFallback()
    {
        $this->showFallback = true;
    }

    public function getPosts($locale)
    {
        return Post::with([
            'category',
            'images' => function ($query) {
                $query->select('images.id', 'caption', 'path');
            },
            // Eager load meeting with related data for event display
            'meeting' => function ($query) {
                $query->with(['meetingable', 'transactionType']);
            },
            // Eager load all active translations for the given locale, ordered by most recent
            'translations' => function ($query) use ($locale) {
                $query->where('locale', 'like', $locale . '%') // Use LIKE for locale flexibility
                    ->whereDate('from', '<=', now())
                    ->where(function ($query) {
                        $query->whereDate('till', '>', now())->orWhereNull('till');
                    })
                    ->orderBy('updated_at', 'desc'); // No limit here for robustness
            }
        ])
        ->whereHas('category', function ($query) {
            $query->where('type', $this->type);
        })
        // Filter for posts that have at least one active translation for the given locale
        ->whereHas('translations', function ($query) use ($locale) {
            $query->where('locale', 'like', $locale . '%') // Use LIKE for locale flexibility
                ->whereDate('from', '<=', now())
                ->where(function ($query) {
                    $query->whereDate('till', '>', now())->orWhereNull('till');
                });
        })
        ->orderBy('created_at', 'desc')
        ->limit($this->limit)
        ->get();
    }

    /**
     * The render method prepares all data needed by the view.
     */
    public function render()
    {
        $locale = $this->showFallback ? config('app.fallback_locale') : App::getLocale();
        $posts = $this->getPosts($locale);

        // If no posts are found and we're not already showing the fallback,
        // perform an efficient check to see if any fallback content exists.
        if ($posts->isEmpty() && !$this->showFallback) {
            $fallbackLocale = config('app.fallback_locale');
            if (trim(App::getLocale()) !== trim($fallbackLocale)) {
                $this->fallbackExists = Post::whereHas('category', function ($query) {
                        $query->where('type', $this->type);
                    })
                    ->whereHas('translations', function ($query) use ($fallbackLocale) {
                        $query->where('locale', 'like', $fallbackLocale . '%')
                            ->whereDate('from', '<=', now())
                            ->where(function ($query) {
                                $query->whereDate('till', '>', now())->orWhereNull('till');
                            });
                    })
                    ->exists();
            }
        }

        $photo = null;
        if ($posts->isNotEmpty()) {
            $firstPost = $posts->first();
            if ($firstPost->hasMedia('*')) {
                $photo = $firstPost->getFirstMediaUrl('*');
            }
        }
    
        return view('livewire.event-calendar-post', [
            'posts' => $posts,
            'photo' => $photo,
            'fallbackLocale' => __(Language::where('lang_code', config('app.fallback_locale'))->first()->name ?? 'Fallback Language'),
        ]);
    }
}