<?php

namespace apexl\Io\modules\display\controllers;

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

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

    public function entityCreateUpdate(Request $request, Response $response, $args)
    {
        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 System::asJson($response);
        } catch (\Exception $e) {
            $this->output::addMessage('basic.display.form.CreateUpdate', 'error', 'Fatal Error occurred: '.$e->getMessage());
        }
        return $this->throw404($response);
    }
}
