<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\Teacher\Concerns\ResolvesTeacherScope;
use App\Models\Announcement;
use App\Models\Subject;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AnnouncementController extends PageController
{
    use ResolvesTeacherScope;

    public function index(): View
    {
        $staffId = auth()->user()?->staff_id;
        $classIds = $this->scope()->assignedClasses()->pluck('id');

        $announcements = Announcement::query()
            ->where(function ($q) use ($staffId, $classIds) {
                $q->where('staff_id', $staffId)
                    ->orWhereIn('class_id', $classIds);
            })
            ->latest()
            ->paginate(20);

        return $this->page('teacher.announcements.index', [
            'crumbTitle' => 'Announcements',
            'crumbSub' => 'Class & subject notices',
            'announcements' => $announcements,
        ]);
    }

    public function create(): View
    {
        return $this->page('teacher.announcements.form', [
            'crumbTitle' => 'Announcements',
            'crumbSub' => 'New announcement',
            'announcement' => new Announcement,
            'classes' => $this->scope()->assignedClasses(),
            'subjects' => Subject::query()->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $this->validateAnnouncement($request);
        if ($validated['class_id'] ?? null) {
            $this->ensureClassAccess((int) $validated['class_id']);
        }

        Announcement::query()->create(array_merge($validated, [
            'created_by' => auth()->id(),
            'staff_id' => auth()->user()?->staff_id,
            'approval_status' => ($validated['audience'] ?? '') === 'all' ? 'pending' : 'approved',
            'published_at' => ($validated['status'] ?? '') === 'published' ? now() : null,
        ]));

        return redirect()->route('teacher.announcements.index')->with('success', 'Announcement saved.');
    }

    /**
     * @return array<string, mixed>
     */
    private function validateAnnouncement(Request $request): array
    {
        return $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string'],
            'audience' => ['required', 'in:students,parents,class,all'],
            'class_id' => ['nullable', 'exists:classes,id'],
            'subject_id' => ['nullable', 'exists:subjects,id'],
            'priority' => ['required', 'in:low,normal,high,urgent'],
            'expires_at' => ['nullable', 'date'],
            'status' => ['required', 'in:draft,published'],
        ]);
    }
}
