<?php

namespace App\Http\Controllers;


use App\Http\Requests\StoreSubjectRequest;
use App\Http\Requests\UpdateSubjectRequest;
use App\Models\Subject;
use App\Models\Dept;
use App\Models\Semester;

class SubjectController extends Controller
{
   
    public function index()
    {
        $subjects = Subject::all();
        $depts = Dept::all();
        $semesters = Semester::all();
        return view('pages.Subjects.index',compact('subjects','depts','semesters'));
    }

   
    public function create()
    {
        

    }

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

          $subject = new Subject();
          $subject->name = ['en' => $request->Name_en, 'ar' => $request->Name];
          $subject->dept_id = $request->dept_id;
          $subject->hours = $request->hours;
          $subject->semester_id = $request->semester_id;
          $subject->save();
  
            toastr()->success(trans('messages.success'));
            return redirect()->route('subjects.index');

      }

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


    }

   
    public function show(Subject $subject)
    {
        

    }

  
    public function edit(Subject $subject)
    {
        

    }

   
    public function update(UpdateSubjectRequest $request, Subject $subject)
    {

        try {

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

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

    }

   
    public function destroy(Subject $subject)
    {
        
        $subject->delete();
        toastr()->error(trans('messages.Delete'));
        return redirect()->route('subjects.index');

    }



}//end of controller
