<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesParentScope;
use App\Models\Announcement;
use Illuminate\View\View;

class AnnouncementController extends PageController
{
    use ResolvesParentScope;

    public function index(): View
    {
        $activeChild = $this->activeStudent();
        $classIds = $activeChild
            ? $activeChild->classes()->pluck('classes.id')
            : collect();

        $announcements = Announcement::query()
            ->where('status', 'published')
            ->where('approval_status', 'approved')
            ->where(fn ($q) => $q->whereIn('audience', ['parents', 'all'])->orWhereNull('audience'))
            ->where(fn ($q) => $q->whereNull('class_id')->orWhereIn('class_id', $classIds))
            ->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>=', now()))
            ->latest('published_at')
            ->paginate(15);

        return $this->page('parent.announcements.index', [
            'crumbTitle' => 'Announcements',
            'crumbSub' => 'School notices',
            'announcements' => $announcements,
            'students' => $this->guardianStudents(),
            'activeChild' => $activeChild,
        ]);
    }
}
