<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Controller;
use App\Models\SchoolClass;
use App\Models\Subject;
use App\Models\Student;
use App\Models\Grade;
use Illuminate\Http\Request;

class GradeEntryController extends Controller
{
    public function create(SchoolClass $class, Subject $subject)
    {
        $teacher = auth()->user();

        // Get students in this class
        $students = $class->students()->orderBy('admission_number')->get();

        // Get existing grades for this class + subject
        $existingGrades = Grade::where('school_class_id', $class->id)
            ->where('subject_id', $subject->id)
            ->where('teacher_id', $teacher->id)
            ->pluck('score', 'student_id');

        return view('teacher.grades.create', compact('class', 'subject', 'students', 'existingGrades'));
    }

    public function store(Request $request, SchoolClass $class, Subject $subject)
    {
        $teacher = auth()->user();

        foreach ($request->scores as $studentId => $score) {
            if ($score !== null) {
                Grade::updateOrCreate(
                    [
                        'student_id' => $studentId,
                        'school_class_id' => $class->id,
                        'subject_id' => $subject->id,
                        'exam_type' => $request->exam_type,
                    ],
                    [
                        'teacher_id' => $teacher->id,
                        'score' => $score,
                        'status' => 'submitted',
                        'remarks' => $request->remarks[$studentId] ?? null,
                    ]
                );
            }
        }

        return redirect()->route('teacher.grades.index')
            ->with('success', 'Marks saved successfully for ' . $subject->name);
    }
}