<?php

namespace App\Http\Livewire\Admin\Pages;

use App\Models\schclass;
use App\Models\Staff;
use App\Models\Student;
use Illuminate\Http\Request;
use Livewire\Component;

class Studentmanagement extends Component
{
    public $stdClass;

    public function mount()
    {
        $this->students = null;
        $schClasses = schclass::where('status', 1)->get();
        $this->schClasses = $schClasses;
        $staffs = Staff::where('status', 1)->get();
        $this->staffs = $staffs;
    }

    public function addStd(Request $request)
    {
        $request->validate([
            'admission_no' => 'required',
            'stdName' => 'required',
            'subjectClass' => 'required',
            'gender' => 'required',
        ],
        [
            'admission_no.required' => 'Admission Number is required',
            'stdName.required' => 'Student Number is required',
            'subjectClass.required' => 'Student Class is required',
            'gender.required' => 'Gender is required',
        ]
    );
    $newStudent = new Student();
    $newStudent->admission_no = $request->admission_no;
    $newStudent->name = $request->stdName;
    $newStudent->schclass_id = $request->subjectClass;
    $newStudent->gender = $request->gender;
    $newStudent->save();
    if($newStudent){
        return redirect()->back()->with('success','Student added successfully');
    }
    if(!$newStudent){
        return redirect()->back()->with('error','Student not added');
    }
    }

    public function updatedStdClass()
    {
        $students = Student::where('schClass_id', $this->stdClass)->get();
        if ($students->count() > 0) {
            $this->students = $students;
        } else {
            $this->students = null;
        }
    }
    public function render()
    {
        return view('livewire.admin.pages.studentmanagement')->layout('layouts.adminApp');
    }
}
