<?php

namespace App\Http\Controllers;


use App\Http\Requests\StoreDeptRequest;
use App\Http\Requests\UpdateDeptRequest;
use App\Models\Dept;
use App\Models\Subject;

class DeptController extends Controller
{
    function __construct()
    { 

    $this->middleware('permission:عرض قسم', ['only' => ['index']]);
    $this->middleware('permission:اضافة قسم', ['only' => ['create','store']]);
    $this->middleware('permission:تعديل قسم', ['only' => ['edit','update']]);
    $this->middleware('permission:حذف قسم', ['only' => ['destroy']]);

    }
    
    public function index()
    {
        $depts = Dept::all();
        return view('pages.Depts.index',compact('depts'));
    }

    
    public function create()
    {
       
    }

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

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

        }

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

  
    public function show(Dept $dept)
    {

    }

    
    public function edit(Dept $dept)
    {
        
    }

    
    public function update(UpdateDeptRequest $request, Dept $dept)
    {
        try {

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

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

  
    public function destroy(Dept $dept)
    {
        $subject_id = Subject::where('dept_id',$dept->id)->pluck('dept_id');

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

            toastr()->error(trans('Depts_trans.delete_Dept_Error'));
            return redirect()->route('depts.index');
  
        }
    }
}
