<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesFamily;
use App\Models\LearningMaterial;
use App\Models\Student;
use App\Models\Submission;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class HomeworkController extends Controller
{
    use ResolvesFamily;

    public function index(Request $request): View
    {
        $family = $this->family();
        $children = $family->students;

        $studentId = $request->integer('student_id') ?: $children->first()?->id;
        $student = $studentId ? Student::find($studentId) : null;
        if ($student) {
            $this->authorizeChild($student);
        }

        $materials = collect();
        $submissions = collect();

        if ($student && $student->class_id) {
            $materials = LearningMaterial::with(['subject', 'teacher'])
                ->published()->where('class_id', $student->class_id)
                ->latest()->get();

            $submissions = Submission::where('student_id', $student->id)
                ->whereIn('learning_material_id', $materials->pluck('id'))
                ->get()->keyBy('learning_material_id');
        }

        return view('parent.homework', compact('children', 'student', 'materials', 'submissions'));
    }

    public function submit(Request $request, LearningMaterial $material): RedirectResponse
    {
        $family = $this->family();

        $data = $request->validate([
            'student_id' => ['required', 'exists:students,id'],
            'note' => ['nullable', 'string', 'max:1000'],
            'attachment' => ['nullable', 'file', 'mimes:pdf,doc,docx,jpg,jpeg,png,zip', 'max:8192'],
        ]);

        $student = Student::findOrFail($data['student_id']);
        abort_unless($student->family_id === $family->id, 403);
        abort_unless($material->class_id === $student->class_id, 403);

        $attachment = $request->hasFile('attachment')
            ? $request->file('attachment')->store("branches/{$family->branch_id}/lms/submissions", 'public')
            : null;

        Submission::updateOrCreate(
            ['learning_material_id' => $material->id, 'student_id' => $student->id],
            [
                'branch_id' => $family->branch_id,
                'note' => $data['note'] ?? null,
                'attachment' => $attachment ?: \App\Models\Submission::where('learning_material_id', $material->id)->where('student_id', $student->id)->value('attachment'),
                'status' => 'submitted',
                'submitted_at' => now(),
            ]
        );

        return back()->with('success', 'Assignment submitted.');
    }
}
