<?php

declare(strict_types=1);

namespace App\Http\Controllers\Pages;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index(Request $request)
    {
        $now = now();

        $posts = Post::query()
            ->where('posts.section', 'club_news')
            ->where('posts.is_published', true)
            ->where(function ($query) use ($now): void {
                $query
                    ->whereNull('posts.published_at')
                    ->orWhere('posts.published_at', '<=', $now);
            })
            ->leftJoin('venues', 'posts.venue_id', '=', 'venues.id')
            ->select([
                'posts.*',
                'venues.name as venue_name',
            ])
            ->orderByDesc('posts.is_pinned')
            ->orderBy('posts.sort_order')
            ->orderByDesc('posts.published_at')
            ->orderByDesc('posts.id')
            ->paginate(10)
            ->withQueryString();

        return view('pages.news.index', [
            'posts' => $posts,
        ]);
    }

    public function show(Request $request, string $slug)
    {
        $now = now();

        $post = Post::query()
            ->where('posts.section', 'club_news')
            ->where('posts.slug', $slug)
            ->where('posts.is_published', true)
            ->where(function ($query) use ($now): void {
                $query
                    ->whereNull('posts.published_at')
                    ->orWhere('posts.published_at', '<=', $now);
            })
            ->leftJoin('venues', 'posts.venue_id', '=', 'venues.id')
            ->select([
                'posts.*',
                'venues.name as venue_name',
            ])
            ->firstOrFail();

        return view('pages.news.show', [
            'post' => $post,
        ]);
    }
}
