<?php

namespace App\Http\Livewire\Admin\Pages;

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

class SingleStudentAdd extends Component
{
    public $stateId, $lga_id, $lgas;
    public function mount()
    {
        $schClasses = schclass::where('status', 1)->get();
        $states = State::all();
        $this->schClasses = $schClasses;
        $this->states = $states;
        $this->lgas = null;
    }
    public function updatedStateId(){
        $this->lgas = lga::where('state_id', $this->stateId)->get();
    }
    public function save(){
        $this->emit('addStudent');
    }
    public function addStudent(Request $request)
    {
        $request->validate([
            'admission_no' => 'required',
            'fname' => 'required',
            'lname' => 'required',
            'schclass_id' => 'required',
            'enrollment_year' => 'required',
            'stateId' => 'required',
            'lga_id' => 'required',
            'dob' => 'required',
            'gender' => 'required',
            'blood_group' => 'required',
            'address' => 'required',
            'phone' => 'required',
        ]);
        $newStd = Student::create([
            'admission_no' => $request->admission_no,
            'name' => $request->lname . " " . $request->fname,
            'schclass_id' => $request->schclass_id,
            'enrollment_year' => $request->enrollment_year,
            'state_id' => $request->stateId,
            'lga_id' => $request->lga_id,
            'dob' => $request->dob,
            'gender' => $request->gender,
            'blood_group' => $request->blood_group,
            'address' => $request->address,
            'phone' => $request->phone,
        ]);
        if($newStd){
            return redirect()->back()->with('success','Student added successfully');
        }else{
            return redirect()->back()->with('error','Error adding Student');
        }
    }
    public function render()
    {
        return view('livewire.admin.pages.single-student-add')->layout('layouts.adminApp');
    }
}
