<?php

namespace App\Controllers;

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

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

    public function new(): string
    {
        $data = service('academyCatalog')->getGroupFormData();

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

    public function create()
    {
        $result = service('academyCatalog')->saveGroup($this->request->getPost());

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

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

        return redirect()->to(url_to('groups.index'))->with('message', 'Grupa a fost adaugata.');
    }

    public function edit(int $groupId)
    {
        $data = service('academyCatalog')->getGroupFormData($groupId);

        if ($data === null || $data['group'] === null) {
            return $this->forbidden('Grupa solicitata nu a fost gasita.');
        }

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

    public function update(int $groupId)
    {
        $result = service('academyCatalog')->saveGroup($this->request->getPost(), $groupId);

        if (! $result['success']) {
            $data = service('academyCatalog')->getGroupFormData(
                $groupId,
                $this->request->getPost(),
                $result['errors'] ?? [],
            );

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

        return redirect()->to(url_to('groups.index'))->with('message', 'Grupa a fost actualizata.');
    }
}
