<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesParentScope;
use App\Models\DisciplinaryCase;
use App\Services\School\DisciplinaryCaseService;
use App\Services\School\PortalActivityService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CaseController extends PageController
{
    use ResolvesParentScope;

    public function __construct(
        private readonly DisciplinaryCaseService $cases,
        private readonly PortalActivityService $activity,
    ) {}

    public function index(): View
    {
        $activeChild = $this->activeStudent();
        $studentIds = $activeChild
            ? [$activeChild->id]
            : $this->guardianStudents()->pluck('id')->all();

        $cases = DisciplinaryCase::query()
            ->with(['subjectStudent', 'schoolClass'])
            ->whereIn('subject_student_id', $studentIds)
            ->latest()
            ->paginate(15);

        return $this->page('parent.cases.index', [
            'crumbTitle' => 'Discipline',
            'crumbSub' => 'Cases involving your children',
            'cases' => $cases,
            'casesService' => $this->cases,
            'students' => $this->guardianStudents(),
            'activeChild' => $activeChild,
        ]);
    }

    public function show(DisciplinaryCase $case): View
    {
        abort_unless($this->cases->canView(auth()->user(), $case), 403);

        $case->load(['subjectStudent', 'schoolClass', 'attachments']);

        return $this->page('parent.cases.show', [
            'crumbTitle' => 'Disciplinary Case',
            'crumbSub' => $case->case_number,
            'case' => $case,
            'casesService' => $this->cases,
        ]);
    }

    public function acknowledge(Request $request, DisciplinaryCase $case): RedirectResponse
    {
        abort_unless($this->cases->canView(auth()->user(), $case), 403);

        $validated = $request->validate([
            'parent_response' => ['nullable', 'string', 'max:2000'],
        ]);

        $case->update([
            'parent_acknowledged_at' => now(),
            'parent_response' => $validated['parent_response'] ?? null,
        ]);

        $this->activity->log('parent', 'discipline_acknowledged', $case);

        return back()->with('success', 'Discipline notice acknowledged.');
    }
}
