<?php

namespace App\Livewire\Teacher;

use App\Models\Mark;
use App\Models\Quiz;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class AddMark extends Component
{
    public ?int $quiz_id = null;
    public string $student_id = '';
    public string $score = '';
    public string $remarks = '';
    public string $toast = '';

    public function mount(): void
    {
        $subject = Auth::user()->taughtSubject;
        if ($subject) {
            $quiz = Quiz::where('subject_id', $subject->id)->latest()->first();
            $this->quiz_id = $quiz?->id;
        }
    }

    public function save(): void
    {
        $this->validate([
            'quiz_id'    => 'required|exists:quizzes,id',
            'student_id' => 'required|exists:users,id',
            'score'      => 'required|integer|min:0|max:100',
        ]);

        Mark::updateOrCreate(
            ['quiz_id' => $this->quiz_id, 'student_id' => $this->student_id],
            ['score' => $this->score, 'remarks' => $this->remarks]
        );

        $student = User::find($this->student_id);
        $this->toast = "Marks saved for {$student->name}!";
        $this->reset('student_id', 'score', 'remarks');
        $this->dispatch('mark-saved');
    }

    public function render()
    {
        $subject  = Auth::user()->taughtSubject;
        $quizzes  = $subject ? Quiz::where('subject_id', $subject->id)->latest()->get() : collect();
        $students = $subject ? $subject->enrolledStudents : collect();

        return view('livewire.teacher.add-mark', compact('quizzes', 'students'));
    }
}
