<?php

namespace App\Controllers;

class EvaluationsController extends BaseController
{
    public function index()
    {
        $data = service('evaluations')->getIndexData($this->request->getGet(), auth()->user(), 'full-evaluation');

        if ($data === null) {
            return $this->forbidden('Tipul de evaluare solicitat nu este disponibil.');
        }

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

    public function quickChecks()
    {
        $data = service('evaluations')->getIndexData($this->request->getGet(), auth()->user(), 'quick-check');

        if ($data === null) {
            return $this->forbidden('Tipul de evaluare solicitat nu este disponibil.');
        }

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

    public function new(int $childId, string $typeSlug)
    {
        $data = service('evaluations')->getFormData($childId, $typeSlug, auth()->user());

        if ($data === null) {
            return $this->forbidden('Nu ai acces la aceasta evaluare sau copilul nu exista.');
        }

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

    public function create(int $childId, string $typeSlug)
    {
        $result = service('evaluations')->save($childId, $typeSlug, $this->request->getPost(), auth()->user());

        if (! $result['success']) {
            if (! empty($result['forbidden'])) {
                return $this->forbidden('Nu ai acces sa adaugi o evaluare pentru acest copil.');
            }

            $data = service('evaluations')->getFormData(
                $childId,
                $typeSlug,
                auth()->user(),
                $this->request->getPost(),
                $result['errors'] ?? [],
            );

            if ($data === null) {
                return $this->forbidden('Nu ai acces la aceasta evaluare sau copilul nu exista.');
            }

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

        return redirect()->to(url_to('evaluations.show', $result['evaluation_id']))->with('message', 'Evaluarea a fost salvata cu succes.');
    }

    public function show(int $evaluationId)
    {
        $data = service('evaluations')->getDetailData($evaluationId, auth()->user());

        if ($data === null) {
            return $this->forbidden('Nu ai acces la aceasta evaluare.');
        }

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