<?php

namespace App\Livewire\Admin;

use App\Models\Mark;
use App\Models\Quiz;
use App\Models\Subject;
use App\Models\User;
use Livewire\Component;

class AddMark extends Component
{
    public bool $open = false;
    public string $student_id = '';
    public string $quiz_id = '';
    public string $score = '';
    public string $remarks = '';
    public string $toast = '';

    public function save(): void
    {
        $this->validate([
            'student_id' => 'required|exists:users,id',
            'quiz_id'    => 'required|exists:quizzes,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', 'quiz_id', 'score', 'remarks');
        $this->dispatch('mark-added');
    }

    public function render()
    {
        $students = User::where('role', 'student')->orderBy('name')->get();
        $quizzes  = Quiz::with('subject')->latest('quiz_date')->get();
        return view('livewire.admin.add-mark', compact('students', 'quizzes'));
    }
}
