<?php
/**
 * AJAX processing file for Form Builder Admin functionality.
 *
 * @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($_POST['action'])) {
    http_response_code(404);
    exit;
} elseif ($_POST['action'] == 'update') {
    $result = FormManager::processSaveRequest($_POST);
    echo json_encode($result);
    exit;
} elseif ($_POST['action'] == 'generate_preview') {

    $form = $_POST;
    if (!empty($form['fieldsets'])) {
        usort($form['fieldsets'], function ($first, $second) {
            return $first['order'] > $second['order'];
        });
        foreach ($form['fieldsets'] as $key => $fieldset) {
            $form['fieldsets'][$key]['questions'] = [];
        }
    }
    if (!empty($form['questions'])) {
        foreach ($form['questions'] as $question_key =>  $question) {

            if (!empty($question['options'])) {
                usort($question['options'], function ($first, $second) {
                    return $first['order'] > $second['order'];
                });
            }
            if (!empty($question['fieldset_id'])) {
                foreach ($form['fieldsets'] as $fieldset_key => $fieldset) {
                    if ($fieldset['id'] == $question['fieldset_id']) {
                        $form['fieldsets'][$fieldset_key]['questions'][$question['order']] = $question;
                    }
                }
            }
        }

        foreach ($form['fieldsets'] as $fieldset_key => $fieldset) {
            if (!empty($form['fieldsets'][$fieldset_key]['questions'])) {
                usort($form['fieldsets'][$fieldset_key]['questions'], function ($first, $second) {
                    return $first['order'] > $second['order'];
                });
            }
        }
    }

    $_SESSION['preview_data'] = $form;
    echo json_encode([
        'status' => 'ok',
    ]);
}



