<?php

namespace App\Http\Controllers;
use App\Group;
use App\User;
use Illuminate\Http\Request;

class UserGroupController extends Controller
{
    //
    public function store(Request $request)
    {
        //新增一使用者群組
        $group = new Group;
        $group->Group_Name=$request->Group_Name;
        if ($request->Group_Detail != null){
            $group->Group_Detail=$request->Group_Detail;
        }
        try{
            $group->save();
        }
        catch (\Illuminate\Database\QueryException $e){
            $erro_meg="群組名稱已重複";
            //$e->getMessage(); 真正錯誤原因
            return back()->withError($erro_meg)->withInput();
        }
        return redirect()->route('account');
    }
    public function delete(Request $request){
        //刪除一使用者群組
        $group = Group::where('Group_Name',$request->Group_Name);

        if (!$group->get()->isEmpty()){
            $group_id=$group->get()[0]["ID"];
            $user = new User;
            if ($user->where('Group_ID',$group_id)->get()->isEmpty()){
                $group->delete();
                return redirect()->route('account');
//                return;
            }
            else{
                $erro_meg="群組內還有其他成員，不可刪除其群組";
                //$e->getMessage(); 真正錯誤原因
                return back()->withError($erro_meg)->withInput();
//                return $erro_meg;
            }
        }

    }

    public function update(Request $request)
    {
        // 修改資料
        $group = Group::where('ID',$request->ID);
        try {
            $group->update([
                'Group_Name' => $request->Group_Name,
                'Group_Detail' => $request->Group_Detail,
//                'Group_Detail' => $request->Group_Detail == null ? $group-> Group_Detail : $request->Group_Detail,
            ]);
        }
        catch (Exception $e){
            $erro_meg="修改失敗";
            //$e->getMessage(); 真正錯誤原因
            return back()->withError($erro_meg)->withInput();
        }
        return redirect()->route('account');
    }
}
