<?php

namespace routes;

use classes\authentication;
use classes\form;
use Exception;
use traits\route_t;

class formRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/form', function () {
            global $response;
            $form_identifier = $this->validateFormIdentifier();

            $form = new form();

            if (!$form->doesFormExist($form_identifier)) {
                $response->error('Form does not exist', 400);
            }

            $response->success(
                $form->getForm($form_identifier)->asArray()
            );
        });

        $this->post('/form', function () {
            global $response;
            // Check if the user is authenticated
            $user = (new authentication())->get_user();
            if (!$user) {
                self::requireRecaptcha();
            };

            $form_identifier = $this->validateFormIdentifier();

            $form = new form();

            if (!$form->doesFormExist($form_identifier)) {
                $response->error('Form does not exist', 400);
            }

            $form->submitForm(
                $form->getForm($form_identifier)
            );

            $response->success(
                (isset($form->last_submitted_form->booking_object)) ? $form->last_submitted_form->booking_object->asArray() : $form->form_submission->asArray()
            );
        });
    }

    /**
     * Validates the 'form_identifier' parameter and returns it in uppercase.
     * @return string Validated and transformed form identifier.
     * @throws Exception if validation fails.
     */
    private function validateFormIdentifier(): string
    {
        self::requireParameters(['id']);

        $form_identifier = self::getParameter('id');

        self::requireType($form_identifier, self::type_string());
        self::requireMinLength('id', 1);
        self::requireMaxLength('id', 255);

        return strtoupper($form_identifier);
    }
}