<?php

namespace App\Controllers;

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

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

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

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

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

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

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

        return redirect()->to(url_to('children.show', $result['child_id']))->with('message', 'Copilul a fost adaugat cu succes.');
    }

    public function show(int $childId)
    {
        $tab  = (string) ($this->request->getGet('tab') ?? 'overview');
        $data = service('children')->getProfileData($childId, auth()->user(), $tab);

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

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

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

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

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

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

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

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

        return redirect()->to(url_to('children.show', $childId))->with('message', 'Profilul copilului a fost actualizat.');
    }
}
