<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Session;
use App\Http\Requests\SessionRequest;
use App\Http\Resources\SessionResource;

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

    public function get_active(Request $request){
        $session = Session::where('status', 'ACTIVE')->first();
        return response()->json(['session' => new SessionResource($session) ]);
    }

    
    /**
     * create
     *
     * @param  mixed $request
     * @return void
     */
    public function create(SessionRequest $request){
        
        $session = new Session();
        $session->title = $request->title;        
        $session->description = $request->description;           
        $session->started_at = $request->date('started_at');
        $session->ended_at = $request->date('ended_at');             
        $session->save();

        return response()->json([ 'session' => new SessionResource($session) ]);

    }

    public function update(SessionRequest $request, $id){
        
        $session = Session::find($id);
        if($session){
            $session->title = $request->title;        
            $session->description = $request->description;           
            $session->started_at = $request->date('started_at');
            $session->ended_at = $request->date('ended_at');             
            $session->save();

            return response()->json([ 'session' => new SessionResource($session) ]);
        }

        return response()->json([ 'error' => 'Session not found' ], 409);

    }
}
