<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grade;
use App\Models\GradeSection;
use App\Http\Resources\GradeResource;
use App\Http\Requests\GradeRequest;

class GradeController extends Controller
{
    /**
     * get
     *
     * @param  mixed $request
     * @return void
     */
    public function get(Request $request){
        $grades = Grade::all();
        return response()->json(['grades' => GradeResource::collection($grades)]);
    }

    
    /**
     * create
     *
     * @param  mixed $request
     * @return void
     */
    public function create(GradeRequest $request){
        
        $grade = new Grade();
        $grade->title = $request->title;        
        $grade->label = $request->label;
        $grade->description = $request->description;        
        $grade->save();

        if($request->has('sections')){
            foreach($request->sections as $sect){
                GradeSection::updateOrCreate([
                    'grade_id'      => $grade->id,
                    'section_id'    => $sect
                ],[
                    'grade_id'      => $grade->id,
                    'section_id'    => $sect
                ]);
            }
        }
        return response()->json([ 'grade' => new GradeResource($grade) ]);
    }
    
    /**
     * update
     *
     * @param  mixed $request
     * @param  mixed $id
     * @return void
     */
    public function update(GradeRequest $request, $id){
        
        $grade = Grade::find($id);
        $grade->title = $request->title;        
        $grade->label = $request->label;
        $grade->description = $request->description;        
        $grade->save();

        if($request->has('sections')){
            
            GradeSection::where('grade_id', $grade->id)->whereNotIn('section_id', $request->sections)->delete();

            foreach($request->sections as $sect){
                GradeSection::updateOrCreate([
                    'grade_id'      => $grade->id,
                    'section_id'    => $sect
                ],[
                    'grade_id'      => $grade->id,
                    'section_id'    => $sect
                ]);
            }
        }
        return response()->json([ 'grade' => new GradeResource($grade) ]);
    }
}
