<?php

namespace App\Http\Controllers\StudentPortal;

use App\Http\Controllers\Controller;
use App\Http\Controllers\StudentPortal\Concerns\ResolvesStudent;
use App\Models\LearningMaterial;
use App\Models\Submission;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class HomeworkController extends Controller
{
    use ResolvesStudent;

    public function index(): View
    {
        $student = $this->student();

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

        if ($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('student.homework', compact('student', 'materials', 'submissions'));
    }

    public function submit(Request $request, LearningMaterial $material): RedirectResponse
    {
        $student = $this->student();
        abort_unless($material->class_id === $student->class_id, 403);

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

        $existing = Submission::where('learning_material_id', $material->id)->where('student_id', $student->id)->first();
        $attachment = $request->hasFile('attachment')
            ? $request->file('attachment')->store("branches/{$student->branch_id}/lms/submissions", 'public')
            : $existing?->attachment;

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

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