<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\GroupRequest;
use App\Http\Resources\GroupResource;
use App\Models\Group;
use Illuminate\Http\Request;

// use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Validator;

class GroupController extends Controller
{
    public function index(){
        $group=Group::all();
        if($group->count() > 0){
            return response()->json([
                'status'=>200,
                'group'=>$group
            ],200);
        }else{
            return response()->json([
                'status'=>404,
                'message'=>'not found'
            ],404);
        }
    }
    public function store(GroupRequest $request){

        $group=Group::create([
            'name'=>$request->name,
            'user_id'=>$request->user_id,
            'subject_id'=>$request->subject_id
        ]);
        return new GroupResource($group);
    }
    public function show($id){
        $group=Group::findOrFail($id);
        if($group){
            return response()->json([
                'status'=>200,
                'group'=>$group
            ],200);
        }else{
            return response()->json([
                'status'=>404,
                'message'=>'not found'
            ],404);
        }
    }
    public function update(GroupRequest $request,$id){
        $group = Group::find($id);
        $group->update($request->all());
        return new GroupResource($group);
    }
    public function delete($id){
        $group=Group::find($id);
        $group->delete();
        if($group){
            return response()->json([
                'status'=>200,
                'message'=>'Deleted'
            ],200);
        }
    }
    public function search($name){
        $group=Group::where('name','Like','%'.$name.'%')->get();
        if($group->count() > 0){
            return response()->json([
                'status'=>200,
                'group'=>$group
            ],200);
        }else{
            return response()->json([
                'status'=>404,
                'message'=>'not found'
            ],404);
        }
    }
    public function group_user(Request $request){
        $request->validate([
            'group_id' => 'required',
            'user_code' => 'required'
        ]);

        $user = User::where('code', $request->user_code)->first();

        $group = Group::where('id', $request->group_id)->first();

        if (isset($group) && isset($user)){
            $user->groups()->sync($group->id);
        }


        return response()->json([
            'status'=>200,
            'data'=> isset($user) && isset($group) ? ' User joined to group successfully ' : 'No users or groups found'
        ],200);

    }
}
