<?php

namespace Modules\Survey\Http\Controllers;

use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Modules\Survey\Entities\SurveyGroup;

class SurveyGroupController extends Controller
{
    public function index()
    {
        try {
            $groups = SurveyGroup::latest()->get();
            return view('survey::group.index', compact('groups'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function store(Request $request)
    {

        if (demoCheck()) {
            return redirect()->back();
        }
        $rules = [
            'title' => 'required|max:255'
        ];

        $this->validate($request, $rules, validationMessage($rules));

        try {

            $store = new SurveyGroup();
            $store->title = $request->title;
            $store->save();

            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect()->route('survey.group.index');
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }

    }


    public function edit($id)
    {
        try {
            $edit = SurveyGroup::find($id);
            $groups = SurveyGroup::latest()->get();
            return view('survey::group.index', compact('groups', 'edit'));
        } catch (\Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }

    public function update(Request $request)
    {
        if (demoCheck()) {
            return redirect()->back();
        }
        $rules = [
            'title' => 'required|max:255'
        ];

        $this->validate($request, $rules, validationMessage($rules));

        $edit = SurveyGroup::findOrFail($request->id);
        $edit->title = $request->title;
        $edit->save();
        Toastr::success(trans('common.Operation successful'), trans('common.Success'));
        return redirect()->route('survey.group.index');
    }

    public function destroy($id)
    {
        $item = SurveyGroup::findOrFail($id);
        $item->delete();
        Toastr::success(trans('common.Operation successful'), trans('common.Success'));
        return redirect()->route('survey.group.index');
    }
}
