<?php

namespace apexl\Io\modules\display\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\modules\display\includes\Forms;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

final readonly class formsController extends Controller
{
    public function entityDelete(Request $request, Response $response, $args): Response
    {
        // this is a dynamic form so get the entity details from the URL.
        $form = Forms::entityActionButtonForm(
            $this->routeManager->getRoutePattern($args['entity'] . '.delete', ['id' => $args['id']])
        );
        $form->setMethod('delete');
        $this->output->addResponse($request, $form->getBuiltFormArray());

        return $this->json($response);
    }

    public function entityCreateUpdate(Request $request, Response $response, $args): Response
    {
        try {
            // this is a dynamic form so get the entity details from the URL.
            $entity = $this->instantiateEntityFromRoute($request);
            $this->output->addResponse($request, Forms::entityForm($entity, $args)->getBuiltFormArray());

            return $this->json($response);
        } catch (Exception $e) {
            $this->output->addMessage(
                'basic.display.form.CreateUpdate',
                'error',
                'Fatal Error occurred: ' . $e->getMessage()
            );
        }

        return $this->throw404($response);
    }
}
