<?php

namespace App\Http\Livewire\Admin\Pages;

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

class Subjectmanagement extends Component
{
    public function mount()
    {
        $subjects = Subject::with('student')->with('stdClass')->with('ca')->with('teacher')
        ->where('status',1)->get();
        $allSubjects = Subject::with('stdClass')->get();
        $staffs = Staff::where('status', 1)->get();
        $schClasses = schclass::where('status', 1)->get();
        $this->schClasses = $schClasses;
        $this->staffs = $staffs;
        $this->subjects = $subjects;
        $this->allSubjects = $allSubjects;
       
    }

    public function addSubject(Request $request)
    {
        $request->validate([
            'subjectName' => 'required',
            'subjectClass' => 'required',
            'teacher_id' => 'required',
        ]);
        $newSubject = new Subject();
        $newSubject->subject = $request->subjectName;
        $newSubject->schclass_id = $request->subjectClass;
        $newSubject->teacher_id = $request->teacher_id;
        $newSubject->save();
        if ($newSubject) {
            return redirect()->back()->with('success', 'Subject added successfully');
        } else {
            return redirect()->back()->with('error', 'Subject not added');
        }
    }

    public function updateSubject(Request $request){
        $request->validate([
            'subject_id' => 'required',
            'teacher_id' => 'required',
            'status' => 'required',
        ]);
        $updateSubject = Subject::find($request->subject_id);
        $updateSubject->teacher_id = $request->teacher_id;
        $updateSubject->status = $request->status;
        $updateSubject->save();
        if($updateSubject){
            return redirect()->back()->with('success','Subject updated successfully');
        }
        if(!$updateSubject){
            return redirect()->back()->with('error','Subject not updated');
        }
    }

    public function render()
    {
        return view('livewire.admin.pages.subjectmanagement')->layout('layouts.adminApp');
    }
}
