<?php

namespace App\Http\Controllers\Store;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Post;
use App\Models\Tag;
use App\Services\LocaleOverrideService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AnnouncementController extends Controller
{
    public function index(Request $request): View
    {
        $tagSlug = $request->query('tag');

        $query = Announcement::query()
            ->where('status', 'published')
            ->where(fn ($q) => $q->whereNull('published_at')->orWhere('published_at', '<=', now()))
            ->with('tags')
            ->orderBy('published_at', 'desc');

        if ($tagSlug) {
            $query->whereHas('tags', fn ($q) => $q->where('slug', $tagSlug));
        }

        $announcements = $query->paginate(15)->withQueryString();
        $tags = Tag::whereHas('announcements')->orderBy('slug')->get();

        // PRC-622 Dalga C — public sayfa; auth gerekmez.
        app(\App\Core\Hook\HookBridge::class)->fireAction('ClientAreaPageAnnouncements', [
            'announcements' => $announcements,
        ]);

        return view('announcements.index', compact('announcements', 'tags', 'tagSlug'));
    }

    public function show(string $slug, Request $request, LocaleOverrideService $localeService): View
    {
        $result = Post::findBySlugInAnyLocale($slug, 'announcement', app()->getLocale());
        if (! $result) {
            abort(404);
        }

        $announcement = $result['post'];
        $matchedLocale = $result['matched_locale'];

        if ($matchedLocale && $matchedLocale !== app()->getLocale()) {
            $localeService->resolveFromSlug($matchedLocale, $request);
        }

        $announcement->increment('view_count');

        $tagIds = $announcement->tags->pluck('id');
        $related = Announcement::query()
            ->where('id', '!=', $announcement->id)
            ->where('status', 'published')
            ->when($tagIds->isNotEmpty(), fn ($q) => $q->whereHas('tags', fn ($qq) => $qq->whereIn('tags.id', $tagIds)))
            ->orderBy('published_at', 'desc')
            ->limit(5)
            ->get();

        return view('announcements.show', compact('announcement', 'related'));
    }
}
