<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Requests\CreateTeamRequest;
use App\Http\Requests\UpdateTeamRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use App\Services\TeamsService;
use App\Models\Team;
use Exception;

class TeamsController extends Controller
{
    protected $model;
    protected TeamsService $teamsService;

    public function __construct(TeamsService $teamsService)
    {
        $this->model = new Team();
        $this->teamsService = $teamsService;
    }

    // show teams list page
    public function index()
    {
        $teams = $this->teamsService->retrieve($this->model);
        return $this->teamsService->displayView('dashboard.about_us.teams.list', ['teams' => $teams]);
    }

    // Show the form for creating a new team.
    public function create()
    {
        return $this->teamsService->displayView('dashboard.about_us.teams.create');
    }

    // Store a newly created team.
    public function store(CreateTeamRequest $request)
    {
        try{
            $this->teamsService->storeTeam($request);
            Session::flash('success', 'Team member created successfully');
        } catch(Exception $e) {
            Session::flash('error', 'Something went wrong');
        }

        return Redirect::back();
    }

    //Show the form for editing the specified team.
    public function edit($id)
    {
        $team = $this->teamsService->show($this->model, $id);
        return $this->teamsService->displayView('dashboard.about_us.teams.update', ['team' => $team]);
    }

    // Update the specified team.
    public function update(UpdateTeamRequest $request, $id)
    {
        try{
            $this->teamsService->updateTeam($id, $request);
            Session::flash('success', 'Team member updated successfully');
        } catch(Exception $e) {
            Session::flash('error', 'Something went wrong'.$e->getMessage());
        }

        return Redirect::back();
    }

    // Remove the specified team.
    public function destroy($id)
    {
        try{
            $this->teamsService->deleteTeam($id);
            Session::flash('success', 'Team member deleted successfully');
        } catch(Exception $e) {
            Session::flash('error', 'Something went wrong');
        }

        return Redirect::back();
    }
}
