<?php

namespace App\Http\Controllers\Grades;
use App\Http\Controllers\Controller;


use App\Http\Requests\StoreGradeRequest;
use App\Http\Requests\UpdateGradeRequest;
use App\Models\Grade;
use App\Models\Semester;

class GradeController extends Controller
{
    public function index()
    {
        // pages\Grades
        $grades = Grade::all();
        return view('pages.Grades.index',compact('grades'));
    }

    public function create()
    {
        //
    }

    
    public function store(StoreGradeRequest $request)
    {
        //
        if(Grade::where('name->ar',$request->Name)->orWhere('name->en',$request->Name_en)->exists())
        {
           return redirect()->back()->withErrors(trans('Grades_trans.exists'));
        }
        try 
        {
            $validated = $request->validated();

            $grade = new Grade();
            $grade->name = ['en' => $request->Name_en, 'ar' => $request->Name];
            $grade->save();
    
              toastr()->success(trans('messages.success'));
              return redirect()->route('grades.index');

        }

        catch (\Exception $e){
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    
       

    }//end of store

    
    public function show(Grade $grade)
    {
        //
    }

   
    public function edit(Grade $grade)
    {
        //
    }

    
    public function update(UpdateGradeRequest $request, Grade $grade)
    {
        try {

            $validated = $request->validated();
            $grade = Grade::findOrFail($request->id);
           
            $grade->name = ['ar' => $request->Name, 'en' => $request->Name_en];
            $grade->save();

            toastr()->success(trans('messages.Update'));
            return redirect()->route('grades.index');
        }
        catch
        (\Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    
    public function destroy(Grade $grade)
    {
       
        $semester_id = Semester::where('grade_id',$grade->id)->pluck('grade_id');

        if($semester_id->count() == 0)
        {
            $grade->delete();
            toastr()->error(trans('messages.Delete'));
            return redirect()->route('grades.index');
        }
        else
        {

            toastr()->error(trans('Grades_trans.delete_Grade_Error'));
            return redirect()->route('grades.index');
  
        }

         
    }//end of destroy
} //end of controller
