<?php

namespace App\Controllers;

class CoachesController extends BaseController
{
    public function index(): string
    {
        $data = service('coaches')->getIndexData($this->request->getGet(), auth()->user());

        return view('coaches/index', $data);
    }

    public function new(): string
    {
        $data = service('coaches')->getFormData(auth()->user());

        return view('coaches/form', $data);
    }

    public function create()
    {
        $result = service('coaches')->save($this->request->getPost(), auth()->user());

        if (! $result['success']) {
            $data = service('coaches')->getFormData(
                auth()->user(),
                null,
                $this->request->getPost(),
                $result['errors'] ?? [],
            );

            return view('coaches/form', $data);
        }

        return redirect()->to(url_to('coaches.show', $result['coach_id']))->with('message', 'Antrenorul a fost creat cu succes.');
    }

    public function show(int $coachId)
    {
        $data = service('coaches')->getProfileData($coachId, auth()->user());

        if ($data === null) {
            return $this->forbidden('Nu ai acces la acest profil de antrenor.');
        }

        return view('coaches/show', $data);
    }

    public function edit(int $coachId)
    {
        $data = service('coaches')->getFormData(auth()->user(), $coachId);

        if ($data === null || $data['coach'] === null) {
            return $this->forbidden('Profilul antrenorului nu a fost gasit.');
        }

        return view('coaches/form', $data);
    }

    public function update(int $coachId)
    {
        $result = service('coaches')->save($this->request->getPost(), auth()->user(), $coachId);

        if (! $result['success']) {
            $data = service('coaches')->getFormData(
                auth()->user(),
                $coachId,
                $this->request->getPost(),
                $result['errors'] ?? [],
            );

            return view('coaches/form', $data);
        }

        return redirect()->to(url_to('coaches.show', $coachId))->with('message', 'Profilul antrenorului a fost actualizat.');
    }
}
