<?php

/**
 * @param $class_name
 */
function formsio_class_loader($class_name)
{
    $class_file = FORMIO_DIR . 'classes/class.'
                  . trim(strtolower(str_replace('\\', '_', $class_name)), '\\') . '.php';

    if (is_file($class_file)) {
        require_once $class_file;
    }
}

/**
 * Insert metabox into the post edit page
 */
function formsio_add_metabox_shortcode()
{
    global $settingsforms;

    add_meta_box(
        'formsio_add_metabox_shortcode',
        $settingsforms['shortcode']['short_code_label'],
        'formio_metabox_shortcode_show',
        'post',
        'side',
        'default',
        'high'
    );
}

/**
 * Insert metabox into the page edit page
 */
function formsio_add_metabox_shortcode_page()
{
    global $settingsforms;

    add_meta_box(
        'formsio_add_metabox_shortcode',
        $settingsforms['shortcode']['short_code_label'],
        'formio_metabox_shortcode_show',
        'page',
        'side',
        'default',
        'high'
    );
}
/**
 * @param $post
 * appending id to metabox 
 */
function formio_metabox_shortcode_show($post)
{
    global $settingsforms;
    echo '
    <script>
        const nf_url = \'' . home_url($settingsforms['page_details']['pages_details']) . '\';
        const nf_app = \'' . $settingsforms['wp']['app'] . '\';
        const nf_label = \'' . $settingsforms['shortcode']['short_code_label'] . '\';
    </script>
    <span id="id-nf-selector"></span>
    ';
}

/**
 * To add the token to DB
 */
function formsio_addtoken() {

  $token_value = $_POST['token_value'];
    if(get_option('user_token')){
      add_option('user_token', $token_value, null, 'no');
      echo "added";
    }
    else {
      update_option('user_token', $token_value);
      echo "updated";
    }
}

/**
* To Preview Single Form
*/
function formIo_SingleFrom_preview( $atts ){
    $id = $atts['id'];
    //$project_id = $atts['project'];
    $token_value = sanitize_text_field($_COOKIE["token"]);
    if(isset($token_value)){
            $token = $token_value;
            add_option('user_token', $token, null, 'no');
            $db_token = get_option('user_token');
            if ($token != $db_token) {
                update_option( 'user_token', $token );
            }
        }
        else {
            $token = get_option('user_token');
        }  
    $token         = get_option('user_token');
    $tokenParts    = explode(".", $token);
    $tokenHeader   = base64_decode($tokenParts[0]);
    $tokenPayload  = base64_decode($tokenParts[1]);
    $jwtHeader     = json_decode($tokenHeader);
    $jwtPayload    = json_decode($tokenPayload);
    $user_id       = $jwtPayload->user_id;
    $region        = $jwtPayload->env;
    $tenant_id     = $jwtPayload->tenant_id;
    $embed_script  = '<div id="DIV-ID"></div>
    <script>
      (async (f, o, r, m, s) => {
        m = o.getElementsByTagName("head")[0];
        s = o.createElement("script");
        s.async = 1;
        s.src = r;
        s.onload = async () => {
          // Please replace the DIV-ID to where this form has to be embedded
          let data = await f.wg.init("forms", "'.$region.'","'.$tenant_id.'", "'.$user_id.'", "forms/'.$id.'/embed", { width: "1200px", height: "750px" }, "widget", "DIV-ID");
        };
        m.appendChild(s);
      })(window, document,  "https://infinity-public-js.500apps.com/widget.min.js");
    </script>';
    return $embed_script;
}
add_shortcode( 'formio', 'formIo_SingleFrom_preview' );