<?php

/**
 * AJAX processing file for Form Builder Module.
 *
 * @category Forms
 * @package  Mtc_Form_Builder
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
namespace Mtc\Modules\FormBuilder\Classes;

$path = '../../';
require_once $path.'core/includes/header.inc.php';

if (! empty($_REQUEST['ajax']) && ! empty($_REQUEST['form_id'])) {
    $form_data = $_REQUEST;

    $errors = FormManager::validateForm($form_data);
    $return = null;
    if (empty($errors)) {
        $return = FormManager::doFormActions($form_data, $twig);
        $status = 'OK';
    } else {
        $status = 'Failed';
    }

    $form = Form::where('id', $form_data['form_id'])
        ->with('questions.options')
        ->with('fieldsets.questions')
        ->first();
    if ($form->id) {
        if ($form->callback == 1 && $form->callback_class == 'FormBmi' && $form->callback_action == 'calculate') {
            echo
                json_encode([
                    'status' => 'bmi',
                    'bmi' => $return,
                ])
            ;
            exit();
        }

        $html = $twig->render(
            'FormBuilder/form.twig',
            [
                'status' => $status,
                'errors' => $errors,
                'request' => $form_data,
                'form' => $form,
            ],
        );
        echo
            json_encode(
                [
                    'status' => $status,
                    'id' => $form->id,
                    'html' => $html,
                    'redirect' => $form->redirect,
                ],
            )
        ;
    }
}
