<?php

namespace App\Http\Controllers\Academic;

use App\Http\Controllers\Controller;
use App\Models\Academic\ClassSection;
use App\Models\Academic\Section;
use App\Models\Academic\StudentClass;
use Illuminate\Http\Request;

class SectionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $student_classes = StudentClass::pluck('class_name','id');
        $sections = Section::all();
        return view('pages.academic.section.index',compact('sections','student_classes'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $student_classes = StudentClass::pluck('class_name','id');
        return view('pages.academic.section.create',compact('student_classes'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'section_name' => 'required|string|max:255',
        ]);

        Section::create([
            'section_name' => $request->section_name,
            'created_by' => auth()->id() ?? 1,
            'updated_by' => auth()->id() ?? 1,
        ]);

        return redirect('/academic/sections')->with('message','Section Successfully Created');
    }

    /**
     * Display the specified resource.
     */
    public function show(Section $section)
    {
        dd($section);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Section $section)
    {
        $student_classes = StudentClass::pluck('class_name','id');
        return view('pages/academic/section/edit',compact('section', 'student_classes'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
        $request->validate([
            'section_name' => 'required|string|max:255',
        ]);

        Section::where('id',$request->id)->update([
            'section_name' => $request->section_name,
            'created_by' => auth()->id() ?? NULL,
            'updated_by' => auth()->id() ?? NULL,
        ]);

        return redirect('/academic/sections')->with('message','Section Successfully Update');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Section $section)
    {
        $section->delete();
        return redirect('/academic/sections')->with('message','Section Successfully Deleted');
    }

    public function getSectionByClassID(Request $request){
        $section_ids = ClassSection::where('student_class_id',$request->student_class_id)->pluck('section_id')->toArray();
        $sections = Section::whereIn('id',$section_ids)->get();
        return response()->json($sections,200);
    }
}
