<?php

namespace App\Http\Controllers\Admin\Core\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Core\Auth\Team;
use App\Models\Core\Auth\Role;

class TeamController extends Controller
{
    public function __construct()
    {
        $this->middleware('ability:admin,teams_crud');
    }

    public function index()
    {
        return view('Admin.Core.Auth.Team.list', ['teams' => Team::all()]);
    }

    public function create()
    {
        return view('Admin.Core.Auth.Team.create');
    }

    public function store(Request $request)
    {
        $input = $request->all();
        $input['name'] = Str::slug($input['display_name']);
        $request->replace($input);

        $this->validate(
            $request, [
            'name'         => 'required|unique:teams,name',
            'display_name' => 'required',
            'description'  => 'required',
            ]
        );

        $team = Team::create($input);
        $team->teams()->sync(array_keys($request->input('team', [])));

        return redirect()->route('admin.Teams.edit', $team)
            ->with('growl', [__('teams.successadd'), 'success']);
    }

    public function edit($id)
    {
        $team = Team::find($id);
        return view('Admin.Core.Auth.Team.edit', compact('team'));
    }

    public function update(Request $request, $id)
    {
        $this->validate(
            $request, [
            'display_name' => 'required',
            'description'  => 'required',
            ]
        );

        $team = Team::find($id);

        return redirect()->route('admin.Teams.edit', $team)
            ->with('growl', [__('teams.successmod'), 'success']);
    }

    public function destroy($id)
    {
        Team::destroy($id);
    }
}
