<?php

class FrontendView {

    private $frontend_id = 0;
    private $current_locale = null;

    /**
     * FrontendView constructor
     */
    public function __construct() {
        $this->current_locale = get_user_locale() ;
    }

    function af2_generate_frontend($atts) {
        $atts = shortcode_atts( array(
            'id' => 0,
            'popup_by_delay' => false,
            'popup_delay' => 0,
            'popup_by_click' => false,
            'popup_click_class' => '',
            'preview' => false
        ), $atts, 'anfrageformular2' );
        return $this->_af2_generate_frontend($atts);
    }
    function af2_generate_frontend_($atts) {
        $atts = shortcode_atts( array(
            'id' => 0,
            'popup_by_delay' => false,
            'popup_delay' => 0,
            'popup_by_click' => false,
            'popup_click_class' => '',
            'preview' => false
        ), $atts, 'funnelforms' );
        return $this->_af2_generate_frontend($atts);
    }

    /**
     * The function to generate the base construct of the frontend
     *
     * @param $atts
     * @return string
     */
    function _af2_generate_frontend($atts) {


        require_once AF2_RESOURCE_HANDLER_PATH;


        $dataid = $atts['id'];                                                            // The Dataid of the Formular
        $base_post = get_post($dataid);                                                   // The post of it out of DB
        require_once AF2_MISC_FUNCTIONS_PATH;
        $base_json = af2_get_post_content($base_post);             

        $base_json = json_decode(json_encode($base_json));


        global $wp_locale_switcher;
        if(isset($base_json->fe_locale) && $base_json->fe_locale !== "default") {
            $wp_locale_switcher->switch_to_locale( $base_json->fe_locale );
        }
        else if(strpos(get_locale(), 'de_') !== false) {
            $wp_locale_switcher->switch_to_locale( 'de_DE' );
        }

        $type = 0;
        if(isset($base_json->adjust_containersize) && $base_json->adjust_containersize == 'true') $type = 2;
        if($atts['preview'] == true) $type = 1;
        else update_option('checklist_shortcode', 'true');

        af2_load_frontend_resources($type);


        $suported_types = af2_get_supported_mime_types();
        $server_max_size = size_format(wp_max_upload_size());
        wp_localize_script('af2_frontend', 'af2_frontend_ajax', // Localizing the Script to use ajax loading
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('af2_FE_nonce'),
                'supported_file_types' => implode(',', $suported_types),
                'server_max_size' => trim(str_replace("MB","", $server_max_size)),
                'supported_server_size' => 'AIzaSyBndbQcPBJHZyoqmdgexoTStZUk53dHRNw',
                'strings' => array(
                    'antworten_tag' => __('[ANSWERS]', 'af2_multilanguage'),
                    'error_01' => __('ERROR - [01] Ajax error (caching error, please contact support)!', 'af2_multilanguage'),
                    'fehler_admin' => __('An error has occurred! If you are an administrator of this website, you can find more information here:', 'af2_multilanguage'),
                    'fehler_find' => __('An error has occurred! Please check your questions, contact forms and forms for completeness!', 'af2_multilanguage'),
                    'help' => __('Get help', 'af2_multilanguage'),
                    'help_url' => __('https://help.funnelforms.io/das-formular-wird-auf-der-website-nicht-angezeigt/', 'af2_multilanguage'),
                    'erroroccured' => __('An error has occurred!', 'af2_multilanguage'),
                    'sms' => __('SMS verification', 'af2_multilanguage'),
                    'sms_sent' => __('A verification code was sent via SMS to the following number:', 'af2_multilanguage'),
                    'sms_change' => __('Change number', 'af2_multilanguage'),
                    'sms_repeat' => __('Send again', 'af2_multilanguage'),
                    'sms_verify' => __('Verify', 'af2_multilanguage'),
                    'country_search_placeholder' => __('Search for country or dial code', 'af2_multilanguage'),
                    'dot' => __(',', 'af2_multilanguage'),
                    'form_sent' => __('FORM SENT', 'af2_multilanguage'),
                    'street' => __('Street', 'af2_multilanguage'),
                    'no' => __('No.', 'af2_multilanguage'),
                    'postcode' => __('Postcode', 'af2_multilanguage'),
                    'city' => __('City', 'af2_multilanguage'),
                    'resend' => __('Send again', 'af2_multilanguage'),
                    'choosedur' => __('Select duration of appointment', 'af2_multilanguage'),
                    'choosedurdot' => __('Select duration of appointment:', 'af2_multilanguage'),
                    'choosetime' => __('Select time of appointment', 'af2_multilanguage'),
                    'choosetimedot' => __('Select time of appointment:', 'af2_multilanguage'),
                    'noappointments' => __('No appointments available on this day!', 'af2_multilanguage'),
                    'mr' => __('Mr.', 'af2_multilanguage'),
                    'mrs' => __('Mrs.', 'af2_multilanguage'),
                    'diverse' => __('Diverse', 'af2_multilanguage'),
                    'company' => __('Company', 'af2_multilanguage'),
                    'dropzone' => array(
                        'remove' => __('Remove', 'af2_multilanguage'),
                        'max_uploads' => __('Maximum number of uploads reached', 'af2_multilanguage'),
                        'max_uploads_size' => __('Maximum upload size exceeded: {{maxFilesize}} MB', 'af2_multilanguage'),
                        'wrong_filetype' => __('Filetype not allowed', 'af2_multilanguage'),
                    ),
                    'date' => array(
                        'sonntag' => __('Sunday', 'af2_multilanguage'), 
                        'montag' => __('Monday', 'af2_multilanguage'),
                        'dienstag' => __('Tuesday', 'af2_multilanguage'),
                        'mittwoch' => __('Wednesday', 'af2_multilanguage'),
                        'donnerstag' => __('Thursday', 'af2_multilanguage'),
                        'freitag' => __('Friday', 'af2_multilanguage'),
                        'samstag' => __('Saturday', 'af2_multilanguage'),
                        'so' => __('Su', 'af2_multilanguage'),
                        'mo' => __('Mo', 'af2_multilanguage'),
                        'di' => __('Tu', 'af2_multilanguage'),
                        'mi' => __('We', 'af2_multilanguage'),
                        'do' => __('Th', 'af2_multilanguage'),
                        'fr' => __('Fr', 'af2_multilanguage'),
                        'sa' => __('Sa', 'af2_multilanguage'),
                        "januar" => __('January', 'af2_multilanguage'),
                        "februar" => __('February', 'af2_multilanguage'),
                        "marz" => __('March', 'af2_multilanguage'),
                        "april" => __('April', 'af2_multilanguage'),
                        "mai" => __('May', 'af2_multilanguage'),
                        "juni" => __('June', 'af2_multilanguage'),
                        "juli" => __('July', 'af2_multilanguage'),
                        "august" => __('August', 'af2_multilanguage'),
                        "september" => __('September', 'af2_multilanguage'),
                        "oktober" => __('October', 'af2_multilanguage'),
                        "november" => __('November', 'af2_multilanguage'),
                        "dezember" => __('December', 'af2_multilanguage'),
                        "jan" => __('Jan', 'af2_multilanguage'),
                        "feb" => __('Feb', 'af2_multilanguage'),
                        "mar" => __('Mar', 'af2_multilanguage'),
                        "apr" => __('Apr', 'af2_multilanguage'),
                        "mai" => __('May', 'af2_multilanguage'),
                        "jun" => __('Jun', 'af2_multilanguage'),
                        "jul" => __('Jul', 'af2_multilanguage'),
                        "aug" => __('Aug', 'af2_multilanguage'),
                        "sep" => __('Sep', 'af2_multilanguage'),
                        "okt" => __('Oct', 'af2_multilanguage'),
                        "nov" => __('Nov', 'af2_multilanguage'),
                        "dez" => __('Dec', 'af2_multilanguage'),
                    ),
                )
            )
        );

        load_basic_frontend_resources($type);

        
        $content = '';                         // Content to draw

        //$loading_path = plugins_url(AF2_LOADING_GIF, AF2_PLUGIN);


        /** Check if license is active * */
        if (get_option('af2_license_stat') === 'Die Domain ist aktiviert!') {
            /** Fetching Data from the given "Formular" * */
            //Popup Attributes
            $popup_by_delay = $atts['popup_by_delay'];
            $popup_delay = $atts['popup_delay'];
            $popup_by_click = $atts['popup_by_click'];
            $popup_click_class = $atts['popup_click_class'];

            if($popup_by_delay && $popup_by_click) $popup_by_click = false;
            $popup_delay = intval($popup_delay);

            

            if ($base_json != null) {
                if(isset($base_json->error) && $base_json->error) return __('Your form has an error', 'af2_multilanguage');
                $size = sizeof($base_json->sections);                  // The maximum amount of steps

                /** If there are special fields -> the size will be one less * */
                if (strpos($base_json->sections[$size - 1]->contents[0]->data, 'redirect:') !== false || strpos($base_json->sections[$size - 1]->contents[0]->data, 'dealsnprojects:') !== false || strpos($base_json->sections[$size - 1]->contents[0]->data, 'activecampaign:') !== false || strpos($base_json->sections[$size - 1]->contents[0]->data, 'klicktipp:') !== false
                || strpos($base_json->sections[$size - 1]->contents[0]->data, 'getresponse:') !== false
                || strpos($base_json->sections[$size - 1]->contents[0]->data, 'pipedrive:') !== false
                || strpos($base_json->sections[$size - 1]->contents[0]->data, 'hubspot:') !== false
                || strpos($base_json->sections[$size - 1]->contents[0]->data, 'fincrm:') !== false
                || strpos($base_json->sections[$size - 1]->contents[0]->data, 'webhook:') !== false) {
                    $size--;
                }

                /** Getting the Frontend-Title * */
                /*
                 * INCOMING -> Build migration!
                 * $fe_title = --> access_database -> get( $dataid ) -> get_frontend_name
                 */
                $fe_title = isset($base_json->styling->fe_title) ? $base_json->styling->fe_title : '';                 // Frontent-Title of Formular
                
                $loader_color = !empty($base_json->styling->form_loader_color)?$base_json->styling->form_loader_color:'rgba(0, 0, 0, 1)';
                
                $back_btn_style_class = '';
                $forward_btn_style_class = '';


                
                $rtl_layout = false;
                if(isset($base_json->rtl_layout) && $base_json->rtl_layout != '') {
                    $rtl_layout = $base_json->rtl_layout;
                }
                

                if(!$rtl_layout)
                {
                    if(!empty($base_json->styling->global_prev_text)){
                        $back_btn_text = $base_json->styling->global_prev_text;
                        $back_btn_style_class = 'special';
                    }else if(isset($base_json->showFontAwesome) && $base_json->showFontAwesome){
                        $back_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-left" class="svg-inline--fa fa-long-arrow-alt-left fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M134.059 296H436c6.627 0 12-5.373 12-12v-56c0-6.627-5.373-12-12-12H134.059v-46.059c0-21.382-25.851-32.09-40.971-16.971L7.029 239.029c-9.373 9.373-9.373 24.569 0 33.941l86.059 86.059c15.119 15.119 40.971 4.411 40.971-16.971V296z"></path></svg>';
                        //$back_btn_text = '<i class="fas fa-long-arrow-alt-left fa-lg"></i>';
                    }else{
                        $back_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-left" class="svg-inline--fa fa-long-arrow-alt-left fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M134.059 296H436c6.627 0 12-5.373 12-12v-56c0-6.627-5.373-12-12-12H134.059v-46.059c0-21.382-25.851-32.09-40.971-16.971L7.029 239.029c-9.373 9.373-9.373 24.569 0 33.941l86.059 86.059c15.119 15.119 40.971 4.411 40.971-16.971V296z"></path></svg>';
                    }
                    
                    if(!empty($base_json->styling->global_next_text)){
                        $forward_btn_text = $base_json->styling->global_next_text;
                        $forward_btn_style_class = 'special';
                    }else if(isset($base_json->showFontAwesome) && $base_json->showFontAwesome){
                        $forward_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-right" class="svg-inline--fa fa-long-arrow-alt-right fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M313.941 216H12c-6.627 0-12 5.373-12 12v56c0 6.627 5.373 12 12 12h301.941v46.059c0 21.382 25.851 32.09 40.971 16.971l86.059-86.059c9.373-9.373 9.373-24.569 0-33.941l-86.059-86.059c-15.119-15.119-40.971-4.411-40.971 16.971V216z"></path></svg>';
                    }else{
                        $forward_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-right" class="svg-inline--fa fa-long-arrow-alt-right fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M313.941 216H12c-6.627 0-12 5.373-12 12v56c0 6.627 5.373 12 12 12h301.941v46.059c0 21.382 25.851 32.09 40.971 16.971l86.059-86.059c9.373-9.373 9.373-24.569 0-33.941l-86.059-86.059c-15.119-15.119-40.971-4.411-40.971 16.971V216z"></path></svg>';
                    }
                }
                else {
                    if(!empty($base_json->styling->global_prev_text)){
                        $back_btn_text = $base_json->styling->global_prev_text;
                        $back_btn_style_class = 'special';
                    }else if(isset($base_json->showFontAwesome) && $base_json->showFontAwesome){
                        $back_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-right" class="svg-inline--fa fa-long-arrow-alt-right fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M313.941 216H12c-6.627 0-12 5.373-12 12v56c0 6.627 5.373 12 12 12h301.941v46.059c0 21.382 25.851 32.09 40.971 16.971l86.059-86.059c9.373-9.373 9.373-24.569 0-33.941l-86.059-86.059c-15.119-15.119-40.971-4.411-40.971 16.971V216z"></path></svg>';
                        //$back_btn_text = '<i class="fas fa-long-arrow-alt-left fa-lg"></i>';
                    }else{
                        $back_btn_text = '<<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-right" class="svg-inline--fa fa-long-arrow-alt-right fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M313.941 216H12c-6.627 0-12 5.373-12 12v56c0 6.627 5.373 12 12 12h301.941v46.059c0 21.382 25.851 32.09 40.971 16.971l86.059-86.059c9.373-9.373 9.373-24.569 0-33.941l-86.059-86.059c-15.119-15.119-40.971-4.411-40.971 16.971V216z"></path></svg>';
                    }
                    
                    if(!empty($base_json->styling->global_next_text)){
                        $forward_btn_text = $base_json->styling->global_next_text;
                        $forward_btn_style_class = 'special';
                    }else if(isset($base_json->showFontAwesome) && $base_json->showFontAwesome){
                        $forward_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-left" class="svg-inline--fa fa-long-arrow-alt-left fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M134.059 296H436c6.627 0 12-5.373 12-12v-56c0-6.627-5.373-12-12-12H134.059v-46.059c0-21.382-25.851-32.09-40.971-16.971L7.029 239.029c-9.373 9.373-9.373 24.569 0 33.941l86.059 86.059c15.119 15.119 40.971 4.411 40.971-16.971V296z"></path></svg>';
                    }else{
                        $forward_btn_text = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="long-arrow-alt-left" class="svg-inline--fa fa-long-arrow-alt-left fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M134.059 296H436c6.627 0 12-5.373 12-12v-56c0-6.627-5.373-12-12-12H134.059v-46.059c0-21.382-25.851-32.09-40.971-16.971L7.029 239.029c-9.373 9.373-9.373 24.569 0 33.941l86.059 86.059c15.119 15.119 40.971 4.411 40.971-16.971V296z"></path></svg>';
                    }
                }
                
                
                /** Getting the Preload-Part * */
                /*
                 * INCOMING -> Build migration!
                 *
                 */
                $preload = 2;

                $errormail = false;
                $aScrollToAnchor = true;
                $aShowSuccessScreen = true;

                /*if(!isset($base_json->send_error_mail) || $base_json->send_error_mail !== false) {
                    $errormail = true;
                }*/
                if(isset($base_json->activateScrollToAnchor) && ($base_json->activateScrollToAnchor === 'false' || $base_json->activateScrollToAnchor === false)) {
                    $aScrollToAnchor = false;
                }
                if(isset($base_json->showSuccessScreen) && ($base_json->showSuccessScreen === 'false' || $base_json->showSuccessScreen === false)) {
                    $aShowSuccessScreen = false;
                }

                /**$loading_delay = 0;
                if($base_json->loadingDelay != null && $base_json->loadingDelay != "") {
                    $loading_delay = $base_json->loadingDelay;
                }

                $popcssclass = "";
                if($base_json->popcssclass != null && $base_json->popcssclass != "") {
                    $popcssclass = $base_json->popcssclass;
                }**/

                // TODO

                if($popup_by_click || $popup_by_delay) {
                    $content .= '<div style="display: none;">';
                    $content .= '<div class="af2_popup_background" id="afpbg_'.$this->frontend_id.'">';
                    $content .= '<div class="af2_popup_wrapper">';
                    $content .= '<div class="af2_close_popup" data-num="'.$this->frontend_id.'"></div>';
                }

                $success_text = __('Thank you! The form was sent successfully!', 'af2_multilanguage');
                if(isset($base_json->success_text) && $base_json->success_text != '') {
                    $success_text = $base_json->success_text;
                }

                $success_image = plugins_url("../res/images/success_standard", __FILE__);
                if(isset($base_json->success_image) && $base_json->success_image != '') {
                    $success_image = $base_json->success_image;
                }

                
                /** Building Content **/
                $content .= '<div id="af2_form_' . $this->frontend_id . '" class="af2_form_wrapper af2_form-type-'.$type.'"
								data-preload="' . $preload . '" data-rtl="'. $rtl_layout .'" data-size="' . $size . '" data-num="' . $this->frontend_id . '"
                                data-did="' . $dataid . '" data-errormail="' . $errormail . '" data-activatescrolltoanchor="' . $aScrollToAnchor . '" data-showsuccessscreen="'.$aShowSuccessScreen.'"
                                data-popup_by_delay="'.$popup_by_delay.'" data-popup_delay="'.$popup_delay.'" data-popup_by_click="'.$popup_by_click.'"
                                data-popup_click_class="'.$popup_click_class.'">';
                
                if(isset($base_json->showLoading) && $base_json->showLoading === true) {
                $content .= '<div class="af2_loading_overlay">
                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin:auto;background:transparent;display:block;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
 <g transform="translate(50 50)">  <g transform="translate(-19 -19) scale(0.6)"> <g transform="rotate(22.5612)">
<animateTransform attributeName="transform" type="rotate" values="0;45" keyTimes="0;1" dur="0.2s" begin="0s" repeatCount="indefinite"></animateTransform><path style="fill:'.$loader_color.'" d="M31.359972760794346 21.46047782418268 L38.431040572659825 28.531545636048154 L28.531545636048154 38.431040572659825 L21.46047782418268 31.359972760794346 A38 38 0 0 1 7.0000000000000036 37.3496987939662 L7.0000000000000036 37.3496987939662 L7.000000000000004 47.3496987939662 L-6.999999999999999 47.3496987939662 L-7 37.3496987939662 A38 38 0 0 1 -21.46047782418268 31.35997276079435 L-21.46047782418268 31.35997276079435 L-28.531545636048154 38.431040572659825 L-38.43104057265982 28.531545636048158 L-31.359972760794346 21.460477824182682 A38 38 0 0 1 -37.3496987939662 7.000000000000007 L-37.3496987939662 7.000000000000007 L-47.3496987939662 7.000000000000008 L-47.3496987939662 -6.9999999999999964 L-37.3496987939662 -6.999999999999997 A38 38 0 0 1 -31.35997276079435 -21.460477824182675 L-31.35997276079435 -21.460477824182675 L-38.431040572659825 -28.531545636048147 L-28.53154563604818 -38.4310405726598 L-21.4604778241827 -31.35997276079433 A38 38 0 0 1 -6.999999999999992 -37.3496987939662 L-6.999999999999992 -37.3496987939662 L-6.999999999999994 -47.3496987939662 L6.999999999999977 -47.3496987939662 L6.999999999999979 -37.3496987939662 A38 38 0 0 1 21.460477824182686 -31.359972760794342 L21.460477824182686 -31.359972760794342 L28.531545636048158 -38.43104057265982 L38.4310405726598 -28.53154563604818 L31.35997276079433 -21.4604778241827 A38 38 0 0 1 37.3496987939662 -6.999999999999995 L37.3496987939662 -6.999999999999995 L47.3496987939662 -6.999999999999997 L47.349698793966205 6.999999999999973 L37.349698793966205 6.999999999999976 A38 38 0 0 1 31.359972760794346 21.460477824182686 M0 -23A23 23 0 1 0 0 23 A23 23 0 1 0 0 -23" fill="#070707"></path></g></g> <g transform="translate(19 19) scale(0.6)"> <g transform="rotate(44.9388)">
<animateTransform attributeName="transform" type="rotate" values="45;0" keyTimes="0;1" dur="0.2s" begin="-0.1s" repeatCount="indefinite"></animateTransform><path style="fill:'.$loader_color.'" d="M-31.35997276079435 -21.460477824182675 L-38.431040572659825 -28.531545636048147 L-28.53154563604818 -38.4310405726598 L-21.4604778241827 -31.35997276079433 A38 38 0 0 1 -6.999999999999992 -37.3496987939662 L-6.999999999999992 -37.3496987939662 L-6.999999999999994 -47.3496987939662 L6.999999999999977 -47.3496987939662 L6.999999999999979 -37.3496987939662 A38 38 0 0 1 21.460477824182686 -31.359972760794342 L21.460477824182686 -31.359972760794342 L28.531545636048158 -38.43104057265982 L38.4310405726598 -28.53154563604818 L31.35997276079433 -21.4604778241827 A38 38 0 0 1 37.3496987939662 -6.999999999999995 L37.3496987939662 -6.999999999999995 L47.3496987939662 -6.999999999999997 L47.349698793966205 6.999999999999973 L37.349698793966205 6.999999999999976 A38 38 0 0 1 31.359972760794346 21.460477824182686 L31.359972760794346 21.460477824182686 L38.431040572659825 28.531545636048158 L28.53154563604818 38.4310405726598 L21.460477824182703 31.35997276079433 A38 38 0 0 1 6.9999999999999964 37.3496987939662 L6.9999999999999964 37.3496987939662 L6.999999999999995 47.3496987939662 L-7.000000000000009 47.3496987939662 L-7.000000000000007 37.3496987939662 A38 38 0 0 1 -21.46047782418263 31.359972760794385 L-21.46047782418263 31.359972760794385 L-28.531545636048097 38.43104057265987 L-38.431040572659796 28.531545636048186 L-31.35997276079433 21.460477824182703 A38 38 0 0 1 -37.34969879396619 7.000000000000032 L-37.34969879396619 7.000000000000032 L-47.34969879396619 7.0000000000000355 L-47.3496987939662 -7.000000000000002 L-37.3496987939662 -7.000000000000005 A38 38 0 0 1 -31.359972760794346 -21.46047782418268 M0 -23A23 23 0 1 0 0 23 A23 23 0 1 0 0 -23" fill="#000000"></path></g></g></g>
</svg>
                        </div>';
                        
                    $content .= '<div class="af2_form" style="display: none;">';
                }
                else {
                    $content .= '<div class="af2_form" style="display: block;">';
                }

                $content .= '<div class="af2_success_message_screen desktop" style="display: none;">';
                    $content .= '<div class="af2_success_image">';
                    $content .= '<img src="'.$success_image.'" />';
                    $content .= '</div>';
                    $content .= '<div class="af2_success_text">';
                    $content .=  $success_text;
                    $content .= '</div>';
                $content .= '</div>';
                $content .= '<div class="af2_success_message_screen af2_mobile" style="display: none;">';
                    $content .= '<div class="af2_success_image">';
                    $content .= '<img src="'.$success_image.'" />';
                    $content .= '</div>';
                    $content .= '<div class="af2_success_text">';
                    $content .=  $success_text;
                    $content .= '</div>';
                $content .= '</div>';
                
                $content .= '<div class="af2_form_heading_wrapper">';
                $content .= '<div class="af2_form_heading desktop">' . $fe_title . '</div>';
                $content .= '<div class="af2_form_heading af2_mobile">' . $fe_title . '</div>';
                $content .= '</div>';
                $content .= '<div class="af2_form_carousel">';
                $content .= '</div>';
                $content .= '<div class="af2_form_bottombar">';
                $content .= '<button class="af2_form_back_button af2_form_button af2_disabled af2_mobile '.$back_btn_style_class.'">'.$back_btn_text.'</button>';
                $content .= '<button class="af2_form_back_button af2_form_button af2_disabled desktop '.$back_btn_style_class.'">'.$back_btn_text.'</button>';
                $content .= '<div class="af2_form_progress_bar"><div class="af2_form_progress"></div></div>';
                $content .= '<button class="af2_form_foward_button af2_form_button af2_disabled af2_mobile '.$forward_btn_style_class.'">'.$forward_btn_text.'</button>';
                $content .= '<button class="af2_form_foward_button af2_form_button af2_disabled desktop '.$forward_btn_style_class.'">'.$forward_btn_text.'</button>';
                $content .= '</div>';
                $content .= '</div>';
                
            
                $content .= '</div>';

                if($popup_by_click || $popup_by_delay) {
                    $content .= '</div>';
                    $content .= '</div>';
                    $content .= '</div>';
                }

                // Update the Impressions in the Database
                update_option('af2_impressions', intval(get_option('af2_impressions')) + 1);
                
                // Update the Impressions for the year - month - af2_impressions_data
                $impression_year = intval(date('Y'));
                $impression_month = intval(date('m'));
                $full_impression_data = unserialize(get_option('af2_impressions_data'));
                if( isset($full_impression_data[$impression_year]) ){
                    if( isset($full_impression_data[$impression_year][$impression_month]) ){
                        $old_count = intval($full_impression_data[$impression_year][$impression_month]);
                        $full_impression_data[$impression_year][$impression_month] = $old_count+1;
                        update_option('af2_impressions_data', serialize($full_impression_data));
                    }else{
                        $full_impression_data[$impression_year][$impression_month] = 1;
                        update_option('af2_impressions_data', serialize($full_impression_data));
                    }
                }else{
                    $full_impression_data[$impression_year] = array( $impression_month => 1 );
                    update_option('af2_impressions_data', serialize($full_impression_data));
                }
            }
        } // ENDIF /** Check if license is active **/

        /** RETURNING * */
        $this->frontend_id++;

        $wp_locale_switcher->switch_to_locale( $this->current_locale );

        return $content;
    }

    /**
     * Getting all data for the frontend to work with
     */
    function af2_get_data() {
        if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce', false) )) {
            echo __('ERROR - [01] Ajax error (caching error, please contact support)!', 'af2_multilanguage');
            die();
        }

        /** Check that all attributes are sent * */
        if (!isset($_GET['ids'])) {
            echo 'ERRORX';
            die();
        }

        /** Get all attributes * */
        $dataids = $_GET['ids'];                      // The Array of Dataids

        /** Checking for bad input and fetching posts * */
        $base_posts = array();                       // The post of it out of DB
        $x = 0;                           // Loop
        foreach ($dataids as $dataid) {
            if (sql_check_it($dataid) === 'ERROR') {
                echo 'ERRORX';
                die();
            }

            $base_posts[$x] = $this->af2_check_params_for_getting_content($dataid);

            /** Checking that no Errors are given * */
            if ($base_posts[$x] === 'ERROR') {
                echo __('ERROR - [02] Please contact support!', 'af2_multilanguage');
                die();
            }

            $x++;
        }

        /** Fetching content out of Database * */
        $base_structures = array();                      // The json Strings
        $base_jsons = array();                       // The json-Objects of it
        $post_types = array();                       // The Types of the post
        $x = 0;                           // Loop
        require_once AF2_MISC_FUNCTIONS_PATH;
        foreach ($base_posts as $base_post) {
            $base_jsons[$x] = af2_get_post_content($base_post);


            $base_jsons[$x] = json_decode(json_encode($base_jsons[$x]));

            /** Checking that no Error is given * */
            $check = $this->af2_check_for_errors($base_jsons[$x]);
            if ($check === 'ERROR') {
                echo __('ERROR - [03] There is an error in a form element!', 'af2_multilanguage');
                die();
            }

            $post_types[$x] = get_post_field('post_type', $base_post);

            $x++;
        }

        /** Cleaning the jsons for the frontend * */
        $new_jsons = json_decode('{}');                    // The clean Jsons
        $x = 0;                           // Loop
        foreach ($post_types as $post_type) {
            $data = strval($dataids[$x]);                   // Actual called Dataid
            switch ($post_type) {
                case 'af2_frage': {
                        $new_jsons->$data = $this->af2_clean_frage_json($base_jsons[$x]);
                        break;
                    }
                case 'af2_kontaktformular': {
                        $new_jsons->$data = $this->af2_clean_kontaktformular_json($base_jsons[$x]);
                        break;
                    }
                case 'af2_formular': {
                        $new_jsons->$data = $this->af2_clean_formular_json($base_jsons[$x]);
                        break;
                    }
            }

            $x++;
        }

        $jsons = json_encode($new_jsons, JSON_UNESCAPED_UNICODE);              // Json to return

        echo $jsons;
        wp_die();
    }

    /**
     * Making the json usable for the frontend
     *
     * @param $base_json
     * @return string
     */
    function af2_clean_frage_json($base_json) {
        $new_json = json_decode('{}');

        /** Processing... * */
        $new_json->frontend_name = $base_json->name;
        $new_json->frontend_description = $base_json->description == null ? '' : $base_json->description;
        $new_json->typ = $base_json->typ;
        $new_json->type_specifics = $this->af2_process_type_specifics($base_json);
        $new_json->af2_type = 'frage';
        $new_json->tracking = $base_json->tracking_code;

        return $new_json;
    }

    /**
     * Making the json usable for the frontend
     *
     * @param $base_json
     * @return string
     */
    function af2_clean_kontaktformular_json($base_json) {
        $new_json = json_decode('{}');

        /** Processing... * */
        $new_json->frontend_name = $base_json->cftitle;
        $new_json->frontend_description = $base_json->description == null ? '' : $base_json->description;
        $new_json->questions = $base_json->questions;
        $new_json->sendButtonLabel = $base_json->send_button;
        $new_json->af2_type = 'kontaktformular';
        $new_json->show_bottombar = $base_json->show_bottombar;
        $new_json->tracking_code = $base_json->tracking_code;

        return $new_json;
    }

    /**
     * Making the json usable for the frontend
     *
     * @param $base_json
     * @return string
     */
    function af2_clean_formular_json($base_json) {
        $new_json = json_decode('{}');

        /** Processing... * */
        $new_json->sections = $this->af2_process_connections($base_json->sections);/** TODO ERRORS * */
        $new_json->styling = $this->af2_process_styling($base_json->styling);/** TODO ERRORS * */
        $new_json->af2_type = 'formular';

        return $new_json;
    }

    /*
     * INCOMING -> DELEDEABLE Part of the Method, WHEN ITS DONE IN BACKEND PERFECTLY
     */

    /**
     * Building the dataids of following into the connections
     *
     * @param $base_array
     * @return mixed
     */
    function af2_process_connections($base_array) {
        $new_json = json_decode('{}');
        $new_json->sections = $base_array;                    // Puffer

        /** Iterating all Sections * */
        for ($x = sizeof($new_json->sections) - 1; $x >= 0; $x--) {
            $section = $new_json->sections[$x];                  // ForEach object

            /** Iterating all Contents * */
            for ($y = sizeof($section->contents) - 1; $y >= 0; $y--) {
                $content = $section->contents[$y];                 // ForEach object

                /** Check if content should be deleted because its an interface * */
                if ($this->af2_check_data_type($content->data) === 'interface') {
                    /** SAFE THE OTHER ONES * */
                    /** Iterating all Contents * */
                    for ($z = sizeof($section->contents) - 1; $z >= 0; $z--) {
                        if ($z > $y) {
                            if ($this->af2_check_data_type($base_array[$x]->contents[$z]) === 'redirect') {
                                foreach ($base_array[$x]->contents[$z]->incoming_connections as $inc) {
                                    $from_section = $inc->from_section;
                                    $from_content = $inc->from_content;

                                    $a = 0;
                                    foreach ($base_array[$from_section]->contents[$from_content]->connections as $con) {
                                        if ($con->to_section == $x && $con->to_content == $z) {
                                            $new_json->sections[$from_section]->contents[$from_content]->connections[$a]->to_content = $base_array[$from_section]->contents[$from_content]->connections[$a]->to_content - 1;
                                        }
                                        $a++;
                                    }
                                }
                            }
                        }
                    }

                    array_splice($new_json->sections[$x]->contents, $y, 1);
                    continue;
                }

                /** Iterating all Connections * */
                if(isset($content->connections)) {
                    for ($z = sizeof($content->connections) - 1; $z >= 0; $z--) {
                        $connection = $content->connections[$z];               // ForEach object

                        $to_section = $connection->to_section;                // The Section to go on
                        $to_content = $connection->to_content;                // The Content to go on
                        $base_section = $base_array[$to_section];
                        $contents = null;
                        $to_dataid = null;
                        if(isset($base_section->contents[$to_content])) {
                            $contents = $base_section->contents[$to_content];
                            $to_dataid = $contents->data;        // The Dataid to go on
                        }

                        /** Check that dataid is an interface * */
                        if ($this->af2_check_data_type($to_dataid) === 'undefined') {
                            array_splice($new_json->sections[$x]->contents[$y]->connections, $z, 1);
                        } else {
                            /** Correcting everything into numbers! * */
                            /*
                            * INCOMING -> DELETEABE, when its perfectly done in the backend!
                            */
                            $new_json->sections[$x]->contents[$y]->connections[$z]->from = intval($connection->from);
                            $new_json->sections[$x]->contents[$y]->connections[$z]->to_section = intval($connection->to_section);
                            $new_json->sections[$x]->contents[$y]->connections[$z]->to_content = intval($connection->to_content);

                            /** Adding the Dataid into the connections * */
                            $new_json->sections[$x]->contents[$y]->connections[$z]->to_dataid = $to_dataid;
                        }
                    } // ENDLOOP /** Iterating all Connections **/
                }
                /** Iterating all incoming connections * */
                if(isset($content->incoming_connections)) {
                    for ($z = sizeof($content->incoming_connections) - 1; $z >= 0; $z--) {
                        $incoming_connection = $content->incoming_connections[$z];          // ForEach object
                        /** Correcting everything into numbers! * */
                        /*
                        * INCOMING -> DELETEABE, when its perfectly done in the backend!
                        */
                        $new_json->sections[$x]->contents[$y]->incoming_connections[$z]->from_section = intval($incoming_connection->from_section);
                        $new_json->sections[$x]->contents[$y]->incoming_connections[$z]->from_content = intval($incoming_connection->from_content);
                    } // ENDLOOP /** Iterating all Connections **/
                }
            } // ENDLOOP /** Iterating all Contents **/
        } // ENDLOOP /** Iterating all Sections **/

        return $new_json->sections;
    }

    /**
     * Process the specifics for every type
     *
     * @param $base_json
     * @return string
     */
    function af2_process_type_specifics($base_json) {
        require_once AF2_MISC_FUNCTIONS_PATH;
        $new_json = json_decode('{}');

        $type = $base_json->typ;                      // Typ of the actual Frage

        switch ($type) {
            case 'af2_select': {
                    $new_json->answers = $this->af2_process_answers($base_json->answers);
                    $new_json->desktop_layout = $base_json->desktop_layout;
                    $new_json->mobile_layout = $base_json->mobile_layout;
                    break;
                }
            case 'af2_multiselect': {
                    $new_json->answers = $this->af2_process_answers($base_json->answers);
                    $new_json->condition = $base_json->condition;
                    $new_json->desktop_layout = $base_json->desktop_layout;
                    $new_json->mobile_layout = $base_json->mobile_layout;
                    break;
                }
            case 'af2_textfeld': {
                    $new_json->placeholder = $base_json->textfeld;
                    $new_json->mandatory = $base_json->textfield_mandatory;
                    if($base_json->min_length != null) $new_json->min_length = $base_json->min_length;
                    if($base_json->max_length != null) $new_json->max_length = $base_json->max_length;

                    if($base_json->text_only_text != null) $new_json->text_only_text = $base_json->text_only_text;
                    if($base_json->text_only_numbers != null) $new_json->text_only_numbers = $base_json->text_only_numbers;
                    if($base_json->text_birthday != null) $new_json->text_birthday = $base_json->text_birthday;
                    if($base_json->text_only_numbers != null) $new_json->text_only_numbers = $base_json->text_only_numbers;
                    //if($base_json->text_plz != null) $new_json->text_plz = $base_json->text_plz;
                    break;
                }
            case 'af2_textbereich': {
                    $new_json->placeholder = $base_json->textarea;
                    $new_json->mandatory = $base_json->textarea_mandatory;
                    
                    if($base_json->min_length != null) $new_json->min_length = $base_json->min_length;
                    if($base_json->max_length != null) $new_json->max_length = $base_json->max_length;

                    if($base_json->text_only_text != null) $new_json->text_only_text = $base_json->text_only_text;
                    if($base_json->text_only_numbers != null) $new_json->text_only_numbers = $base_json->text_only_numbers;
                    if($base_json->text_birthday != null) $new_json->text_birthday = $base_json->text_birthday;
                    //if($base_json->text_plz != null) $new_json->text_plz = $base_json->text_plz;

                    break;
                }
            case 'af2_datum': {
                $new_json->placeholder = $base_json->datum;
                $new_json->format = $base_json->datum_format;
                $new_json->datemandatory = $base_json->datemandatory;
                break;
            }
            case 'af2_slider': {
                $new_json->min = $base_json->min;
                $new_json->max = $base_json->max;
                $new_json->step = $base_json->step;
                $new_json->label = $base_json->label;
                $new_json->start = $base_json->start;
                $new_json->thousand = $base_json->thousand;
                $new_json->labelBefore = $base_json->lab;
                $new_json->manual = $base_json->manual;
                $new_json->text_manual = $base_json->text_manual;
                $image = isset($base_json->slider_image) ? $base_json->slider_image : null;
                $new_json->icon = null;
                $new_json->image = null;
                if($image == null) break;
                
                if(af2_str_contains($image, 'https:')) $new_json->image = $image;
                else $new_json->icon = $image;
                break;
            }
            case 'af2_content': {
                $new_json->content = $base_json->content_area;
                $new_json->content_button = $base_json->content_button;
                $new_json->content_button_text = $base_json->content_button_text;
                $new_json->content_wait_time = $base_json->content_wait;
                break;
            }
            case 'af2_dateiupload': {
                $new_json->description = $base_json->fileupload_desc;
                $new_json->mandatory = $base_json->fileupload_mandatory;
                $new_json->max_size = $base_json->fileupload_max_size;
                $new_json->max_count = $base_json->fileupload_max_count;
                $new_json->restricted_types = $base_json->restrictedFiles == null ? array() : $base_json->restrictedFiles;
                break;
            }
            case 'af2_dropdown': {
                $new_json->dropdown_options = $base_json->dropdown_options;
                break;
            }
            case 'af2_adressfeld': {
                $new_json->zoomlevel = $base_json->zoomlevel;
                $new_json->center = $base_json->startposition->loc;
                $new_json->mapmandatory = $base_json->mapmandatory;
            }
            case 'af2_terminbuchung': {
                $termineventid = $base_json->terminbuchungsid;
                $terminevent = get_post($termineventid);
                if(isset($terminevent) && $terminevent != null) {

                    require_once AF2_MISC_FUNCTIONS_PATH;
                    $structure_base_json = af2_get_post_content($terminevent);                         
                    $jsonm = json_decode(json_encode($structure_base_json));
                    
                    $new_json->termineventcontent = $jsonm;
                    $new_json->termineventcontent->cronofy_token_data = null;
                } else {
                    $new_json->termineventcontent = null;
                }
            }
        }

        return $new_json;
    }

    /**
     * Processing the answers, that all types in there are corredt
     *
     * @param $answers
     * @return array
     */
    function af2_process_answers($answers) {
        $new_array = array();

        foreach ($answers as $answer) {
            $new_answer = json_decode('{}');                   // The new answer object
            $new_answer->text = $answer->text;                   // Text of the answer
            $new_answer->icon = $answer->img;                   // Actual Icon
            $new_answer->icon_type = '';                    // Type of the icon
            if (strpos($new_answer->icon, 'http') !== false) {
                $new_answer->icon_type = 'url';
            } else {
                $new_answer->icon_type = 'font-awesome';
            }

            array_push($new_array, $new_answer);
        }

        return $new_array;
    }

    /*
     * INCOMING -> DELEt´TEABLE METHOD, WHEN ITS DONE IN BACKEND PERFECTLY
     */

    /**
     * Building the right styling for the frontend to use
     *
     * @param $base_json
     * @return string
     */
    function af2_process_styling($base_json) {
        $new_json = json_decode('{}');

        /** Get all stylings * */
    
        /** COLORS * */
        $form_heading_color = json_decode('{"attribute": "color","value":"' . $base_json->form_heading_color . '"}');
        
        $form_question_heading_color = json_decode('{"attribute": "color","value":"' . $base_json->form_question_heading_color . '"}');
        
        $form_question_description_color = json_decode('{"attribute": "color","value":"' . $base_json->form_question_description_color . '"}');
        
        $form_answer_card_text_color = json_decode('{"attribute": "color","value":"' . $base_json->form_answer_card_text_color . '"}');
        
        $form_answer_card_icon_color = json_decode('{"attribute": "color","value":"' . $base_json->form_answer_card_icon_color . '"}');
        
        $form_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_background_color . '"}');
        $form_font = json_decode('{"attribute": "font-family","value":"' . $base_json->global_font . '"}');
        $form_fontfc = json_decode('{"attribute": "font-family","value":"' . $base_json->global_font . '", "special_class":"form_font"}');
        
        $form_answer_card_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_answer_card_background_color . '"}');
        
        $form_button_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_button_background_color . '"}');
        
        $form_button_disabled_background_color = json_decode('{"attribute":"background-color","value": "' . $base_json->form_button_disabled_background_color . '","special_class": "af2_disabled"}');
        
        $form_button_label_text_desktop = json_decode('{"attribute":"font-size","value": "' . $base_json->form_button_label_size_desktop . 'px","special_class": "desktop"}');
     
        $form_button_label_text_mobile = json_decode('{"attribute":"font-size","value": "' . $base_json->form_button_label_size_mobile . 'px","special_class": "af2_mobile"}');
    
        $answer_card_box_shadow_value = isset($base_json->form_box_shadow_color_answer_card) ? $base_json->form_box_shadow_color_answer_card : 'rgba(225,225,225,1)';
        $form_box_shadow_color_answer_card = json_decode('{"attribute": "box-shadow","value":" 5px 5px 15px 0 ' . $answer_card_box_shadow_value . '"}');

        $answer_card_box_shadow_value_unfocus = isset($base_json->form_box_shadow_color_unfocus) ? $base_json->form_box_shadow_color_unfocus : 'rgba(225,225,225,1)';
        
        $form_box_shadow_color_unfocus = json_decode('{"attribute": "box-shadow","value":" 0px 0px 10px 0 ' . $answer_card_box_shadow_value_unfocus . '"}');
        $form_box_shadow_color = json_decode('{"attribute": "box-shadow","value":" 0px 0px 10px 0 ' . $base_json->form_box_shadow_color . '", "special_state": "focus"}');
        $form_box_shadow_colorfc = json_decode('{"attribute": "box-shadow","value":" 0px 0px 10px 0 ' . $base_json->form_box_shadow_color . '", "special_state": "focus", "special_class":"form_class"}');
        
        $form_progress_bar_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_progress_bar_color . '"}');
        
        $form_progress_bar_unfilled_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_progress_bar_unfilled_background_color . '"}');
        
        $form_border_color = json_decode('{"attribute": "border","value":"1px solid ' . $base_json->form_border_color . '","special_state":"focus"}');
        $form_border_colorfc = json_decode('{"attribute": "border","value":"1px solid ' . $base_json->form_border_color . '","special_state":"focus", "special_class":"form_class"}');
        
        $form_slider_frage_bullet_color = json_decode('{"attribute": "color","value":"' . $base_json->form_slider_frage_bullet_color . '"}');
        
        $form_slider_frage_thumb_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_slider_frage_thumb_background_color . ' !important","special_extra":"-moz-range-thumb"}');
        
        $form_slider_frage_thumb_background_color2 = json_decode('{"attribute": "background-color","value":"' . $base_json->form_slider_frage_thumb_background_color . ' !important","special_extra":"-webkit-slider-thumb"}');
        $form_slider_frage_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_slider_frage_background_color . '"}');
        
        $form_input_background_color = json_decode('{"attribute": "background-color","value":"' . $base_json->form_input_background_color . '"}');
        
         $form_loader_color = json_decode('{"attribute": "color","value":"' . $base_json->form_loader_color . '"}');

        /** TEXT THINGS * */
        //form heading
        $form_heading_size_desktop = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_heading_size_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_heading_size_mobile = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_heading_size_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');
        $form_heading_weight = json_decode('{"attribute": "font-weight",
								 						 	"value":"' . $base_json->form_heading_weight . '"}');
        $form_heading_line_height_desktop = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_heading_line_height_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_heading_line_height_mobile = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_heading_line_height_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');

        //question heading
        $form_question_heading_size_desktop = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_question_heading_size_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_question_heading_size_mobile = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_question_heading_size_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');
        $form_question_heading_weight = json_decode('{"attribute": "font-weight",
								 						 	"value":"' . $base_json->form_question_heading_weight . '"}');
        $form_question_heading_line_height_desktop = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_question_heading_line_height_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_question_heading_line_height_mobile = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_question_heading_line_height_mobile . 'px",
															  "special_class":"af2_mobile"}');

        //question description
        $form_question_description_size_desktop = json_decode('{"attribute": "font-size",
															"value":"' . $base_json->form_question_description_size_desktop . 'px",
															"special_class":"desktop"}');
        $form_question_description_size_mobile = json_decode('{"attribute": "font-size",
															"value":"' . $base_json->form_question_description_size_mobile . 'px",
															"special_class":"af2_mobile"}');
        $form_question_description_weight = json_decode('{"attribute": "font-weight",
															"value":"' . $base_json->form_question_description_weight . '"}');
        $form_question_description_line_height_desktop = json_decode('{"attribute": "line-height",
															"value":"' . $base_json->form_question_description_line_height_desktop . 'px",
															"special_class":"desktop"}');
        $form_question_description_line_height_mobile = json_decode('{"attribute": "line-height",
															"value":"' . $base_json->form_question_description_line_height_mobile . 'px",
															"special_class":"af2_mobile"}');

        //answers
        $form_answer_card_text_size_desktop = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_answer_card_text_size_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_answer_card_text_size_desktop_ = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_answer_card_text_size_desktop . 'px"}');
        $form_answer_card_text_size_desktop_fc = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_answer_card_text_size_desktop . 'px", "special_class":"form_class"}');
        $form_answer_card_text_size_mobile = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_answer_card_text_size_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');
        $form_answer_card_text_size_mobile_ = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_answer_card_text_size_mobile . 'px"}');
        $form_answer_card_text_size_mobile_fc = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_answer_card_text_size_mobile . 'px", "special_class":"form_class"}');
        $form_answer_card_text_weight = json_decode('{"attribute": "font-weight",
								 						 	"value":"' . $base_json->form_answer_card_text_weight . '"}');
        $form_answer_card_text_weightfc = json_decode('{"attribute": "font-weight",
								 						 	"value":"' . $base_json->form_answer_card_text_weight . '", "special_class":"form_class"}');
        $form_answer_card_text_line_height_desktop = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_answer_card_text_line_height_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_answer_card_text_line_height_mobile = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_answer_card_text_line_height_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');

        //input text sizes
        $form_text_input_size_desktop = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_text_input_size_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_text_input_size_mobile = json_decode('{"attribute": "font-size",
								 						 	"value":"' . $base_json->form_text_input_size_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');
        $form_text_input_weight = json_decode('{"attribute": "font-weight",
								 						 	"value":"' . $base_json->form_text_input_text_weight . '"}');
        $form_text_input_line_height_desktop = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_text_input_line_height_desktop . 'px",
								 						 	"special_class":"desktop"}');
        $form_text_input_line_height_mobile = json_decode('{"attribute": "line-height",
								 						 	"value":"' . $base_json->form_text_input_line_height_mobile . 'px",
								 						 	"special_class":"af2_mobile"}');

        /** BORDER RADIUS * */
        $form_answer_card_border_radius = json_decode('{"attribute": "border-radius",
								 						 	"value":"' . $base_json->form_answer_card_border_radius . 'px"}');
        $form_text_input_border_radius = json_decode('{"attribute": "border-radius",
								 						 	"value":"' . $base_json->form_text_input_border_radius . 'px"}');
        $form_text_input_border_radiusfc = json_decode('{"attribute": "border-radius",
								 						 	"value":"' . $base_json->form_text_input_border_radius . 'px", "special_class":"form_class"}');
        $form_text_input_border_radius_ = json_decode('{"attribute": "border-radius",
								 						 	"value":"' . $base_json->form_text_input_border_radius . 'px 0 0 ' . $base_json->form_text_input_border_radius . 'px"}');
        $form_text_input_border_radiuslr = json_decode('{"attribute": "border-radius",
                                                        "value":"0 ' . $base_json->form_text_input_border_radius . 'px ' . $base_json->form_text_input_border_radius . 'px 0"}');

        /** CONTACT FORM * */
        $form_contact_form_label_size = json_decode('{"attribute": "font-size",
															"value":"' . $base_json->form_contact_form_label_size . 'px"}');
        $form_contact_form_label_size_ = json_decode('{"attribute": "font-size",
															"value":"' . $base_json->form_contact_form_label_size . 'px", "special_class": "desktop"}');
        $form_contact_form_label_weight = json_decode('{"attribute": "font-weight",
															"value":"' . $base_json->form_contact_form_label_weight . '"}');
        $form_contact_form_input_size = json_decode('{"attribute": "font-size",
																	"value":"' . $base_json->form_contact_form_input_size . 'px"}');
        $form_contact_form_input_weight = json_decode('{"attribute": "font-weight",
																	"value":"' . $base_json->form_contact_form_input_weight . '"}');
        $form_contact_form_button_size = json_decode('{"attribute": "font-size",
																	"value":"' . $base_json->form_contact_form_button_size . 'px"}');
        $form_contact_form_button_weight = json_decode('{"attribute": "font-weight",
																	"value":"' . $base_json->form_contact_form_button_weight . '"}');
        $form_contact_form_button_padding_top_bottom = json_decode('{"attribute": "padding",
																	"value":"' . $base_json->form_contact_form_button_padding_top_bottom . 'px 0"}');
        
        $form_contact_form_button_padding_left = json_decode('{"attribute": "padding-left","value":"' . $base_json->form_contact_form_button_padding_left_right . 'px"}');
        $form_contact_form_button_padding_right = json_decode('{"attribute": "padding-right","value":"' . $base_json->form_contact_form_button_padding_left_right . 'px"}');
        
        $form_contact_form_cb_size = json_decode('{"attribute": "font-size",
																	"value":"' . $base_json->form_contact_form_cb_size . 'px"}');
        $form_contact_form_cb_weight = json_decode('{"attribute": "font-weight",
																	"value":"' . $base_json->form_contact_form_cb_weight . '"}');
        $form_contact_form_input_height = json_decode('{"attribute": "height",
																	"value":"' . $base_json->form_contact_form_input_height . 'px"}');
        $form_contact_form_input_border_radius = json_decode('{"attribute": "border-radius",
																	"value":"0 ' . $base_json->form_contact_form_input_border_radius . 'px '.$base_json->form_contact_form_input_border_radius.'px 0"}');
        $form_contact_form_input_border_radiuslr = json_decode('{"attribute": "border-radius",
																	"value":"' . $base_json->form_contact_form_input_border_radius . 'px 0 0 '.$base_json->form_contact_form_input_border_radius.'px"}');
        $form_contact_form_input_border_radius_ = json_decode('{"attribute": "border-radius",
																	"value":"' . $base_json->form_contact_form_input_border_radius . 'px"}');
        $form_contact_form_button_border_radius = json_decode('{"attribute": "border-radius",
																	"value":"' . $base_json->form_contact_form_button_border_radius . 'px"}');
        $form_contact_form_button_background_color = json_decode('{"attribute": "background-color",
																	"value":"' . $base_json->form_contact_form_button_background_color . '"}');
        $form_contact_form_button_background_color_ = json_decode('{"attribute": "color",
																	"value":"' . $base_json->form_contact_form_button_background_color . ' !important"}');
        $form_contact_form_button_background_color_fc = json_decode('{"attribute": "background-color",
																	"value":"' . $base_json->form_contact_form_button_background_color . ' !important", "special_class": "form_class"}');
        $form_contact_form_button_color = json_decode('{"attribute": "color",
																		"value":"' . $base_json->form_contact_form_button_color . '"}');
        
        $rgb = explode(',', explode('(', $base_json->form_contact_form_button_background_color)[1]);
        $form_contact_form_button_background_color_rgb = json_decode('{"attribute": "--rgb",
            "value":"' . $rgb[0].', '.$rgb[1].', '.$rgb[2] . '"}');

            $rgb = explode(',', explode('(', $base_json->form_contact_form_button_color)[1]);
            $form_contact_form_button_color_rgb = json_decode('{"attribute": "--rgbcol",
                "value":"' . $rgb[0].', '.$rgb[1].', '.$rgb[2] . '"}');




        $form_contact_form_input_padding_left_right = json_decode('{"attribute": "padding",
																		"value":"0 ' . $base_json->form_contact_form_input_padding_left_right . 'px"}');
        
        $form_contact_form_font_color = json_decode('{"attribute": "color","value":"' . $base_json->form_contact_form_font_color . '"}');

        /** Append them into the json * */
        $new_json->af2_answer_card = array($form_answer_card_icon_color, $form_answer_card_background_color,
            $form_answer_card_border_radius, $form_box_shadow_color_answer_card);
        $new_json->af2_slider_image_icon_wrapper = array($form_answer_card_icon_color);
        $new_json->af2_form_heading = array($form_heading_color,
            $form_heading_size_desktop, $form_heading_size_mobile, $form_heading_weight, $form_heading_line_height_desktop, $form_heading_line_height_mobile);
        $new_json->af2_question_heading = array($form_question_heading_color,
            $form_question_heading_size_desktop, $form_question_heading_size_mobile, $form_question_heading_weight, $form_question_heading_line_height_desktop, $form_question_heading_line_height_mobile);
        $new_json->af2_question_description = array($form_question_description_color,
            $form_question_description_size_desktop, $form_question_description_size_mobile, $form_question_description_weight, $form_question_description_line_height_desktop, $form_question_description_line_height_mobile);
        
        $new_json->af2_answer_text = array($form_answer_card_text_color,
            $form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile, $form_answer_card_text_weight, $form_answer_card_text_line_height_desktop, $form_answer_card_text_line_height_mobile);
        $new_json->af2_form = array($form_answer_card_border_radius, $form_background_color,$form_font, $form_answer_card_border_radius);
        $new_json->af2_form_button = array($form_font, $form_answer_card_border_radius, $form_button_background_color, $form_button_disabled_background_color,$form_button_label_text_desktop,$form_button_label_text_mobile);
        $new_json->af2_form_progress = array($form_progress_bar_color);
        $new_json->af2_form_progress_bar = array($form_progress_bar_unfilled_background_color);
        $new_json->af2_textfeld_frage = array($form_box_shadow_color, $form_input_background_color,
            $form_text_input_size_desktop, $form_border_color, $form_text_input_size_mobile, $form_text_input_weight, $form_text_input_line_height_desktop, $form_text_input_line_height_mobile,
            $form_text_input_border_radius, $form_box_shadow_color_unfocus);
        $new_json->af2_textbereich_frage = array($form_box_shadow_color, $form_input_background_color,
            $form_text_input_size_desktop, $form_text_input_size_mobile, $form_text_input_weight, $form_text_input_line_height_desktop, $form_text_input_line_height_mobile,
            $form_text_input_border_radius, $form_border_color, $form_box_shadow_color_unfocus);
        
        $new_json->af2_datum_frage = array($form_box_shadow_color, $form_input_background_color,
            $form_text_input_size_desktop, $form_text_input_size_mobile, $form_text_input_weight, $form_text_input_line_height_desktop, $form_text_input_line_height_mobile,
            $form_text_input_border_radius, $form_border_color, $form_box_shadow_color_unfocus);
        
        // datepicker styling
        $datepicker_header_backgroud = json_decode('{"attribute": "background-color","value":"' . $base_json->form_datepicker_background_color . '", "special_class":"af2_datepicker","sub_class":"ui-datepicker-title"}');
        $datepicker_header_color = json_decode('{"attribute": "color","value":"' . $base_json->form_datepicker_color . '", "special_class":"af2_datepicker","sub_class":"ui-datepicker-title"}');
        $new_json->af2_datepicker_header = array($datepicker_header_backgroud,$datepicker_header_color);
        
        $new_json->{'ui-datepicker-title'} = array($form_font);
        $new_json->{'desktop .ui-datepicker-title'} = array($form_answer_card_text_size_desktop_);
        $new_json->{'af2_mobile .ui-datepicker-title'} = array($form_answer_card_text_size_mobile_);
        
        $datepicker_active_backgroud = json_decode('{"attribute": "background-color","value":"' . $base_json->form_datepicker_background_color . ' !important", "special_class":"af2_datepicker","sub_class":"ui-datepicker-current-day"}');
        $datepicker_active_color = json_decode('{"attribute": "color","value":"' . $base_json->form_datepicker_color . ' !important", "special_class":"af2_datepicker","sub_class":"ui-state-active"}');
        $new_json->af2_datepicker_active = array($datepicker_active_backgroud,$datepicker_active_color);
        
        $new_json->af2_question_wrapper = array($form_contact_form_font_color);
        $new_json->af2_text_type = array($form_contact_form_input_padding_left_right, $form_box_shadow_color, $form_border_color, $form_input_background_color, $form_contact_form_input_size, $form_contact_form_input_weight, $form_contact_form_input_height, $form_contact_form_input_border_radius,$form_contact_form_font_color, $form_box_shadow_color_unfocus);
        $new_json->{'af2_text_type.af2_rtl_layout'} = array($form_contact_form_input_border_radiuslr);
        $new_json->af2_text_type_ = array($form_contact_form_input_padding_left_right, $form_box_shadow_color, $form_border_color, $form_input_background_color, $form_contact_form_input_size, $form_contact_form_input_weight, $form_contact_form_input_height, $form_contact_form_input_border_radius_,$form_contact_form_font_color, $form_box_shadow_color_unfocus);
        $new_json->af2_slider_frage = array($form_box_shadow_color, $form_slider_frage_thumb_background_color, $form_slider_frage_thumb_background_color2,$form_slider_frage_background_color, $form_box_shadow_color_unfocus);
        $new_json->af2_slider_frage_bullet = array($form_question_heading_size_desktop, $form_question_heading_size_mobile, $form_question_heading_weight, $form_slider_frage_bullet_color);
        $new_json->af2_slider_frage_val = array($form_border_color, $form_box_shadow_color, $form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile, $form_text_input_weight, $form_box_shadow_color_unfocus);
        $new_json->af2_slider_frage_val_after = array($form_text_input_border_radius_);
        $new_json->af2_slider_frage_val_before = array($form_text_input_border_radiuslr);
        $new_json->{'af2_slider_frage_val_after.af2_rtl_layout'} = array($form_text_input_border_radiuslr);
        $new_json->{'af2_slider_frage_val_before.af2_rtl_layout'} = array($form_text_input_border_radius_);

        //$new_json['select2-search__field'] = array($form_text_input_border_radius);
        
        // 2.0.9.2
        $new_json->af2_question_label = array($form_contact_form_label_size_, $form_text_input_size_mobile, $form_contact_form_label_weight);
        $new_json->af2_radio_label = array($form_contact_form_input_size, $form_contact_form_input_weight);
        $new_json->af2_submit_button = array($form_contact_form_button_background_color_rgb, $form_contact_form_button_color_rgb, $form_font,$form_contact_form_button_color, $form_contact_form_button_size, $form_contact_form_button_weight, $form_contact_form_button_padding_top_bottom,$form_contact_form_button_padding_left,$form_contact_form_button_padding_right, $form_contact_form_button_border_radius, $form_contact_form_button_background_color);
        $new_json->af2_question_cb_label = array($form_contact_form_cb_size, $form_contact_form_cb_weight);
        
        $new_json->af2_dateiupload_inner = array($form_answer_card_border_radius);
        
        
        $new_json->af2_form_html_content = array($form_contact_form_label_size, $form_contact_form_label_weight);
        
        // 2.1.2
        $new_json->af2_form_loader = array($form_loader_color);
        $new_json->af2_address_field_ = array($form_answer_card_border_radius);
        $new_json->af2_adress_map_input_wrapper = array($form_answer_card_border_radius);
        $new_json->af2_html_content_summary = array($form_answer_card_border_radius);

        $new_json->af2_ahref = array($form_contact_form_button_background_color_);

        //$new_json->af2_form_percentage 	= array( $buffer_main_background_color );
        /*         * }
          /** NEW VARIANT **
          else
          {
          //DO ANYTHING
          } */

          $new_json->af2_question_cf_text_type_icon = array($form_contact_form_button_background_color, $form_contact_form_input_height, $form_contact_form_input_border_radiuslr);
          $new_json->{'af2_question_cf_text_type_icon.af2_rtl_layout'} = array($form_contact_form_input_border_radius);
          $new_json->af2_ad_trans = array($form_font, $form_text_input_border_radius, $form_border_color, $form_box_shadow_color, $form_text_input_size_desktop, $form_text_input_size_mobile, $form_text_input_weight, $form_box_shadow_color_unfocus);
          $new_json->alternate_text_wrap_span = array($form_contact_form_button_background_color, $form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile, $form_answer_card_text_weight);
          $new_json->alternate_text_wrap_span_before = array($form_text_input_border_radius_);
          $new_json->alternate_text_wrap_span_after = array($form_text_input_border_radiuslr);
          $new_json->{'alternate_text_wrap_span_before.af2_rtl_layout'} = array($form_text_input_border_radiuslr);
          $new_json->{'alternate_text_wrap_span_after.af2_rtl_layout'} = array($form_text_input_border_radius_);
          $new_json->af2_ad_trans_tabel = array($form_answer_card_text_weight, $form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile);
          $new_json->af2_html_content_summary_object_title_ = array($form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile);
          $new_json->af2_html_content_summary_object_answer_ = array($form_answer_card_text_weight, $form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile);
          
          $new_json->range_text_box_label = array($form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile, $form_answer_card_text_weight);
          
          $new_json->af2_response_error = array($form_contact_form_label_size, $form_contact_form_label_weight);

          $new_json->{'af2-select2-container input.select2-search__field'} = array($form_fontfc, $form_border_colorfc, $form_box_shadow_colorfc, $form_answer_card_text_weightfc, $form_text_input_border_radiusfc);
          $new_json->{'af2-select2-container.desktop input.select2-search__field'} = array($form_answer_card_text_size_desktop_fc);
          $new_json->{'af2-select2-container.af2_mobile input.select2-search__field'} = array($form_answer_card_text_size_mobile_fc);

          $new_json->{'af2-select2-container.select2-selection.select2-selection--single'} = array($form_fontfc, $form_border_colorfc, $form_box_shadow_colorfc, $form_answer_card_text_weightfc);
          $new_json->{'af2-select2-container.desktop.select2-selection.select2-selection--single'} = array($form_answer_card_text_size_desktop_fc);
          $new_json->{'af2-select2-container.af2_mobile.select2-selection.select2-selection--single'} = array($form_answer_card_text_size_mobile_fc);
          
          $new_json->{'select2-results__option.select2-results__option--selectable'} = array($form_fontfc, $form_answer_card_text_weightfc);
          $new_json->{'af2-select2-container.desktop .select2-results__option.select2-results__option--selectable'} = array($form_answer_card_text_size_desktop_fc);
          $new_json->{'af2-select2-container.af2_mobile .select2-results__option.select2-results__option--selectable'} = array($form_answer_card_text_size_mobile_fc);

          $new_json->{'af2-select2-container .select2-results__option.select2-results__option--selectable.select2-results__option--highlighted'} = array($form_contact_form_button_background_color_fc);
        
          $new_json->{'af2_terminbuchung_heading'} = array($form_font, $form_answer_card_text_size_desktop, $form_answer_card_text_size_mobile, $form_question_description_color);
          $new_json->{'af2_terminbuchung_time'} = array($form_contact_form_button_background_color_rgb);
          $new_json->{'af2_terminbuchung_duration'} = array($form_contact_form_button_background_color_rgb);
          $new_json->{'af2_notification'} = array($form_contact_form_button_color_rgb, $form_contact_form_button_background_color_rgb);

          $new_json->{'af2_terminbuchungs_wrap #select2-af2_zeitzone-container.select2-selection__rendered'} = array($form_contact_form_button_background_color_rgb);
          $new_json->{'af2_calender_wait--loading'} = array($form_contact_form_button_background_color_rgb);
          
          return $new_json;
    }

    /**
     * Returns the type of the Dataid
     *
     * -> element = Frage / Kontaktformular
     * -> redirect = redirect
     * -> interface = klicktipp / Deals and Projects / ...
     *
     * @param $dataid
     * @return string
     */
    private function af2_check_data_type($dataid) {
        return $dataid === null ? 'undefined' : ( is_numeric($dataid) ? 'element' :
                ( strpos($dataid, 'redirect') === false ? 'interface' : 'redirect' ) );
    }

    /**
     * Checking all input, that there is nothing bad in it
     * 	And returning the post, to reuse it.
     *
     * @param $dataid
     * @return string/post
     */
    private function af2_check_params_for_getting_content($dataid) {
        /** Validate the Content * */
        if (!is_numeric($dataid)) {
            return 'ERROR';
        }

        /** SQL CHECK * */
        if (sql_check_it($dataid) === 'ERROR') {
            echo 'ERROR';
            die();
        }

        /** Getting the Post * */
        $base_post = get_post($dataid);

        /** Check that the post exists * */
        if ($base_post == null) {
            return 'ERROR';
        }

        /** Check that the post is really a Frage, a Kontaktformular, or a Formular * */
        $post_type = get_post_field('post_type', $base_post);             // Type of the Post

        if (( $post_type != 'af2_frage' ) && ( $post_type != 'af2_kontaktformular' ) && ( $post_type != 'af2_formular' )) {
            return 'ERROR';
        }

        return $base_post;
    }

    /**
     * Checking, if any error is given
     *
     * @param $json
     * @return string
     */
    private function af2_check_for_errors($json) {
        /*
         * INCOMING
         *
         * READING OUT OF DB
         */

        if (isset($json->error) && $json->error == true) {
            return 'ERROR';
        }
        return '';
    }

}

$frontend_view = new FrontendView();

add_shortcode('anfrageformular2', array($frontend_view, 'af2_generate_frontend'));/** SHORTCODE -> Generate Frontend */
add_shortcode('funnelforms', array($frontend_view, 'af2_generate_frontend_'));/** SHORTCODE -> Generate Frontend */
add_action('wp_ajax_nopriv_af2_request_data', array($frontend_view, 'af2_get_data'));/** ACTION -> Getting Data */
add_action('wp_ajax_af2_request_data', array($frontend_view, 'af2_get_data'));

add_action('wp_ajax_nopriv_af2_send_error_mail', 'send_error_mail');
add_action('wp_ajax_af2_send_error_mail', 'send_error_mail');


function af2_save_actual_post() {
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        die();
    }

    $post_id = $_POST['id'];
    $content = $_POST['content'];
    $dsgvoid = $_POST['dsgvoid'];

    $base_post = get_post($post_id);                                                   // The post of it out of DB
    require_once AF2_MISC_FUNCTIONS_PATH;
    $base_json = af2_get_post_content($base_post);             

    $base_json = json_decode(json_encode($base_json));

    if(!(isset($base_json->dsgvo) && $base_json->dsgvo == 'true')) {
        echo 'false';
        wp_die();
    }

    $processed_content = array('form_id' => $post_id, 'questions' => array(), 'contact_form' => array());

    if(sizeof($content) > 0) $processed_content = af2_create_answers_json($processed_content, 0, 0, 0, $content, $base_json, -1, false, 1);
    else {
        echo '';
        wp_die();
    }


    if(!isset($dsgvoid) || $dsgvoid == null || $dsgvoid == '') {
        $post_content = urlencode(serialize($processed_content));
        $id = wp_insert_post(array('post_content' => $post_content, 'post_type' => REQUEST_POST_TYPE_, 'post_status' => 'draft'));

        echo $id;
        wp_die();
    }
    else {
        $post_content = urlencode(serialize($processed_content));
        wp_update_post( array('ID' => $dsgvoid, 'post_content' => $post_content) );
        echo $dsgvoid;
        wp_die();
    }

    wp_die();
}

add_action('wp_ajax_nopriv_af2_send_actual_post', 'af2_save_actual_post');
add_action('wp_ajax_af2_send_actual_post', 'af2_save_actual_post');

function send_error_mail() {
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        die();
    }
    wp_die();
}

function af_create_timestamp() {
    $tz = 'Europe/Amsterdam';
    $timestamp = time();
    $dt = new DateTime("now", new DateTimeZone($tz));
    $dt->setTimestamp($timestamp);

    return $dt->format('YmdH');
}


/**
 * Function to do a check, if an sql injection is getting done;
 *
 * @param $var
 * @return string
 */
function sql_check_it($var) {
    if (is_array($var)) {
        foreach ($var as $el) {
            if (sql_check_it($el) === 'ERROR') {
                return 'ERROR';
            }
        }

        return '';
    }
    if (strpos(strtolower(strval($var)), 'select') !== false) {
        return 'ERROR';
    } else if (strpos(strtolower(strval($var)), 'update') !== false) {
        return 'ERROR';
    } else if (strpos(strtolower(strval($var)), 'insert') !== false) {
        return 'ERROR';
    } else if (strpos(strtolower(strval($var)), 'drop') !== false) {
        return 'ERROR';
    } else if (strpos(strtolower(strval($var)), 'delete') !== false) {
        return 'ERROR';
    }

    return '';
}

//////////////////////////////////////
/// ///////////////////////
///
///
///
///
///
///
///
///
///
/// /////////////////////////////
///
///
///
///

function af2_send_mail() {
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        die();
    }

    $sec = $_POST['sec'];
    $cont = $_POST['cont'];
    $dataid = $_POST['dataid'];
    $answers = $_POST['answers'];
    $attachment_ids = isset($_POST['attachment_ids']) ? $_POST['attachment_ids'] : null;

    // SQL CHECKS
    $var = sql_check_it($sec);
    $var2 = sql_check_it($cont);
    $var3 = sql_check_it($dataid);
    $var4 = sql_check_it($answers);

    if ($var === 'ERROR' || $var2 === 'ERROR' || $var3 === 'ERROR' || $var4 === 'ERROR') {
        echo 'ERROR';
        die();
    }

    // VALIDATE THE NUMERICS
    if (!(is_numeric($sec) && is_numeric($cont) && is_numeric($dataid) )) {
        echo 'ERROR';
        die();
    } else {
        require_once AF2_MISC_FUNCTIONS_PATH;
        $base_post_structure = get_post($dataid);
        $structure_base_json = af2_get_post_content($base_post_structure);                         

        $jsonm = json_decode(json_encode($structure_base_json));

        $formular_id = $dataid;

        // CHECKING THAT POST IS A FORMULAR
        if ($base_post_structure == null) {
            echo 'ERROR';
            die();
        }
        if (get_post_field('post_type', $base_post_structure) != 'af2_formular') {
            echo 'ERROR';
            die();
        }

        $form_id = $jsonm->sections[$sec]->contents[$cont]->data;
        $form_post = get_post($form_id);
        $form_content = af2_get_post_content($form_post);
        $form_content = json_decode(json_encode($form_content));

        $i = 0;
        foreach ($answers as $answer) {
            if ($i < sizeof($answers) - 1) {
                if (is_array($answer) && ($answer['date'] == null && $answer['time'] == null && $answer['duration'] == null)) {
                    foreach ($answer as $a) {
                        if (!is_numeric($a)) {
                            echo 'ERROR';
                            die();
                        }
                    }
                }
            } else {
                // VALIDATING CONTACT FORM CONTENTS
                // VALIDATING REQUIREDS

                $form_questions = $form_content->questions;
                $answer_block = $answers[sizeof($answers) - 1];
                $x = 0;
                foreach ($form_questions as $form_question) {
                    
                    if ($form_question->typ == 'html_content')
                        continue;
                    
                    if ($form_question->required == 'true') {
                        if (is_numeric(strpos($form_question->typ, 'text_type_'))) {
                            if (trim($answer_block[$x]) == '') {
                                echo '<div class="af2_response_error" data-id="' . $x . '">'.__('This field is a required field!', 'af2_multilanguage').'</div>';
                                
                                die();
                            }
                        } else if (is_numeric(strpos($form_question->typ, 'salutation'))) {
                            if (trim($answer_block[$x]) == 'keine Angabe') {
                                echo '<div class="af2_response_error" data-id="' . $x . '">'.__('This field is a required field!', 'af2_multilanguage').'</div>';

                                die();
                            }
                        } else {
                            if (strval($answer_block[$x]) == 'false') {
                                echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The checkbox must be active!', 'af2_multilanguage').'</div>';

                                die();
                            }
                        }
                    }

                    //VALIDATE PHONE
                    if ($form_question->typ == 'text_type_phone') {
                        if(!validate_phone_number($answer_block[$x], $form_question->required) && $answer_block[$x] != '') {
                            echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The phone number is not valid!', 'af2_multilanguage').'</div>';

                            die();
                        }
                    }
                    //VALIDATE PHONE
                    if ($form_question->typ == 'text_type_phone_verification') {
                        if(!validate_phone_number_country($answer_block[$x])) {
                            echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The mobile number is not valid! (Format: +1 702 12345678)', 'af2_multilanguage').'</div>';

                            die();
                        } else {
                            $smsCode = $_POST['verificationSMS'][0];
                            $smsNumber = $_POST['verificationSMS'][1];
                            if(!af2_gotValidationCode($smsCode, $smsNumber))
                            {
                                echo 'NOT VALIDATED';
                                die();
                            }
                        }

                        // VERIFICATION
                    }

                    //VALIDATE EMAIL
                    if ($form_question->typ == 'text_type_mail') {
                        $cf_mail = trim($answer_block[$x]);
                        if (!filter_var($cf_mail, FILTER_VALIDATE_EMAIL) && $cf_mail != '') {
                            echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The e-mail address is not valid!', 'af2_multilanguage').'</div>';

                            die();
                        }
                    }

                    $x++;
                }
            }

            $i++;
        }

        

    $terminbuchungsobject = json_decode(json_encode($_POST['terminbuchungsobjekt']));
    if($terminbuchungsobject == null) ; // DO SOMETHING SPECIAL


        // BUILD UP ANSWERS AND PROECESS
        $m_answers = '';
        $m_answers_autoresponder = '';
        if(sizeof($answers) > 1) $m_answers = af2_create_answers_with_hidden_fields($m_answers, 0, 0, 0, $answers, $jsonm, '');
        if(sizeof($answers) > 1) $m_answers_autoresponder = af2_create_answers($m_answers_autoresponder, 0, 0, 0, $answers, $jsonm);
        
        $api_answers = '';
        if(sizeof($answers) > 1) $api_answers = af2_create_api_answers($api_answers, 0, 0, 0, $answers, $jsonm);


        // Init the Zapier JSON
        $zapier_json = array('form_id' => $formular_id, 'questions' => array(), 'contact_form' => array());

        // Init the filling of questions and contact form
        if(sizeof($answers) > 1) $zapier_json = af2_create_answers_json($zapier_json, 0, 0, 0, $answers, $jsonm, -1, true, 2);
        $zapier_json = af2_create_cf_json($zapier_json, $answers[sizeof($answers) - 1], $form_content);

        //finished zapier_json




        // CHECK FOR DNP INTERACE
        // BUILDING UP DNP INTERFACE
        // CHECK FOR REDIRECT
        // BUILD UP REDIRECT
        $redirect = 'false';
        $blank = 'false';

       

        
        $terminbuchungactive = false;
        if(isset($terminbuchungsobject->date) && isset($terminbuchungsobject->time) && isset($terminbuchungsobject->duration)) {
            $terminbuchungactive = true;
        }

        // SAVE DATA
        $queryStringData = array("id" => 'queryString', "value" => $_POST['af2_queryString']);
        $urlData = array("id" => 'url', "value" => $_POST['af2_url']);
        $zapier_json['analyticsData'] = array($queryStringData, $urlData);

        $terminbuchungs_json = $zapier_json;

        $save_json = urlencode(serialize($zapier_json));

        $dsgvoid = $_POST['dsgvoid'];

        $lead_id = null;
        if(!isset($dsgvoid) || $dsgvoid == null || $dsgvoid == '') {
            $lead_id = wp_insert_post(array('post_content' => $save_json, 'post_type' => REQUEST_POST_TYPE, 'post_status' => 'privat'));
        }
        else {
            $lead_id = wp_update_post(array('ID' => $dsgvoid, 'post_content' => $save_json, 'post_type' => REQUEST_POST_TYPE, 'post_status' => 'privat'));
        }



        $conns = $jsonm->sections[$sec]->contents[$cont]->connections;
        
        $active_dealsnprojects = null;
        $active_activecampaign = null;
        $active_getresponse = null;
        $active_pipedrive = null;
        $active_hubspot = null;
        $active_fincrm = null;
        $active_klicktipp = null;

        $webhook = null;

        $contact_form_answers = $_POST['contactFormAnswers'];

        foreach ($conns as $conn) {
            $to_sec = $conn->to_section;
            $to_cont = $conn->to_content;

            $dat = $jsonm->sections[$to_sec]->contents[$to_cont]->data;
            if (strpos($dat, 'redirect:') !== false) {
                $redirect = $dat;
                // APPLY REDIRECT PARAMS
                if($form_content->redirect_params != null) {
                    $redirect .= '?';
                    foreach ($form_content->redirect_params as $param) {
                        $text = $param->text;
                        $field = $param->field;
                        // Das ist für die übergabe der antworten als query param (bei Redirect angehänt)
                        if($field == '[antworten]') {
                            $field = af_base64UrlEncode(serialize($zapier_json));
                        }
                        else {
                            $x = 0;
                            foreach($form_questions as $form_question) {
                                $field = str_ireplace('[' . $form_question->id . ']', $answer_block[$x], $field);
                                $x++;
                            }
                        }
                        $redirect .= $text . '=' . urlencode($field).'&';
                    }
                }
                $blank = strval($jsonm->sections[$to_sec]->contents[$to_cont]->newtab);
            }
            else if(strpos($dat, 'webhook:') !== false) {
                $webhook = substr($dat, 8);
            }
            else if (strpos($dat, 'dealsnprojects:') !== false) {
                $active_dealsnprojects = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            else if (strpos($dat, 'activecampaign:') !== false) {
                $active_activecampaign = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            else if (strpos($dat, 'getresponse:') !== false) {
                $active_getresponse = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            else if (strpos($dat, 'pipedrive:') !== false) {
                $active_pipedrive = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            else if (strpos($dat, 'hubspot:') !== false) {
                $active_hubspot = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            else if (strpos($dat, 'fincrm:') !== false) {
                $active_fincrm = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            else if (strpos($dat, 'klicktipp:') !== false) {
                $active_klicktipp = $jsonm->sections[$to_sec]->contents[$to_cont]->api_values;
            }
            
        }
		
		executePushNotification();

        require_once AF2_MISC_FUNCTIONS_PATH;
        // CHECK FOR MAIL
        // BUILD UP MAIL
        $mailto = $form_content->mailto;
        $mailfrom = $form_content->mailfrom;
        $mailsubject = af2_replace_tags($form_questions,$answer_block,$form_content->mailsubject);
        $mailtext = $form_content->mailtext;
        $mailfrom_name = $form_content->mailfrom_name;
        //$mail_sendtext = $form_content->mail_sendtext;
        $mailcc = $form_content->mailcc;
        $mailbcc = $form_content->mailbcc;
        if(!empty($form_content->mail_replyto)){
            $mail_replyto = af2_replace_tags($form_questions,$answer_block,$form_content->mail_replyto);
            // check if its a valid email
            $mail_replyto = is_email($mail_replyto);
        }else{
            $mail_replyto = $form_content->mailfrom;
        }
        
        $use_autoresponder = $form_content->use_autorespond;
        $autoresponder_field = '';
        $autoresponder_text = '';
        $autoresponder_subject = '';
        $autoresponder_attachment_url = null;

        if ($use_autoresponder === true || $use_autoresponder === 'true') {
            $autoresponder_field = $form_content->autoresponder_field;
            $autoresponder_text = $form_content->autoresponder_nachricht;
            $autoresponder_attachment_url = $form_content->attachment_url != '' && $form_content->attachment_url != null ? $form_content->attachment_url : null;

            if($autoresponder_attachment_url == null) {
                $autoresponder_attachment_url = array();
            } else {
                $a_autoresponder_attachment_url = explode(site_url(), $autoresponder_attachment_url)[1];
                $a_autoresponder_attachment_url_local = explode('wp-content', $a_autoresponder_attachment_url)[1];
                $autoresponder_attachment_url = array(WP_CONTENT_DIR . $a_autoresponder_attachment_url_local);
            }

            $autoresponder_text = str_ireplace(__('[ANSWERS]', 'af2_multilanguage'), $m_answers_autoresponder, $autoresponder_text);

            if($terminbuchungactive == true) {
                $__id = $terminbuchungsobject->id;
                $__post = get_post($__id);
                $__post_content = af2_get_post_content($__id);
                $__post_content = json_decode(json_encode($__post_content));

                $__terminbuchungsid = $__post_content->terminbuchungsid;
                
                $__terminbuchung = get_post($__terminbuchungsid);
                $__terminbuchung_title = $__terminbuchung->post_title;

                $expl = explode('/', $terminbuchungsobject->date);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), $expl[1].'.'.$expl[0].'.'.$expl[2], $autoresponder_text);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), $terminbuchungsobject->duration, $autoresponder_text);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), $__terminbuchung_title, $autoresponder_text);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), $terminbuchungsobject->time, $autoresponder_text);
            }
            else {
                $autoresponder_text = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), '', $autoresponder_text);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), '', $autoresponder_text);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), '', $autoresponder_text);
                $autoresponder_text = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), __('No appointment has been booked!', 'af2_multilanguage'), $autoresponder_text);
            }
            $autoresponder_subject = af2_replace_tags($form_questions,$answer_block,$form_content->autoresponder_subject);

            if($terminbuchungactive == true) {
                $__id = $terminbuchungsobject->id;
                $__post = get_post($__id);
                $__post_content = af2_get_post_content($__id);
                $__post_content = json_decode(json_encode($__post_content));

                $__terminbuchungsid = $__post_content->terminbuchungsid;
                
                $__terminbuchung = get_post($__terminbuchungsid);
                $__terminbuchung_title = $__terminbuchung->post_title;

                $expl = explode('/', $terminbuchungsobject->date);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), $expl[1].'.'.$expl[0].'.'.$expl[2], $autoresponder_subject);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), $terminbuchungsobject->duration, $autoresponder_subject);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), $__terminbuchung_title, $autoresponder_subject);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), $terminbuchungsobject->time, $autoresponder_subject);
            }
            else {
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), '', $autoresponder_subject);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), '', $autoresponder_subject);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), '', $autoresponder_subject);
                $autoresponder_subject = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), __('No appointment has been booked!', 'af2_multilanguage'), $autoresponder_subject);
            }
        }

        $mailtext = str_ireplace(__('[ANSWERS]', 'af2_multilanguage'), $m_answers, $mailtext);
        $mailtext = str_ireplace('[queryString]', $_POST['af2_queryString'], $mailtext);
        $mailtext = str_ireplace('[url]', $_POST['af2_url'], $mailtext);
        $mailtext = str_ireplace('[ID]', $lead_id, $mailtext);


        if($terminbuchungactive == true) {
            $__id = $terminbuchungsobject->id;
                $__post = get_post($__id);
                $__post_content = af2_get_post_content($__id);
                $__post_content = json_decode(json_encode($__post_content));

                $__terminbuchungsid = $__post_content->terminbuchungsid;
                
                $__terminbuchung = get_post($__terminbuchungsid);
                $__terminbuchung_title = $__terminbuchung->post_title;

                $expl = explode('/', $terminbuchungsobject->date);
            $mailtext = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), $expl[1].'.'.$expl[0].'.'.$expl[2], $mailtext);
            $mailtext = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), $terminbuchungsobject->duration, $mailtext);
            $mailtext = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), $__terminbuchung_title, $mailtext);
            $mailtext = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), $terminbuchungsobject->time, $mailtext);

            $mailsubject = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), $expl[1].'.'.$expl[0].'.'.$expl[2], $mailsubject);
            $mailsubject = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), $terminbuchungsobject->duration, $mailsubject);
            $mailsubject = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), $__terminbuchung_title, $mailsubject);
            $mailsubject = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), $terminbuchungsobject->time, $mailsubject);
        }
        else {
            $mailtext = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), '', $mailtext);
            $mailtext = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'), '', $mailtext);
            $mailtext = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), '', $mailtext);
            $mailtext = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), __('No appointment has been booked!', 'af2_multilanguage'), $mailtext);

            

            $mailsubject = str_ireplace(__('[APPOINTMENTDATE]', 'af2_multilanguage'), '', $mailsubject);
            $mailsubject = str_ireplace(__('[APPOINTMENTDURATION]', 'af2_multilanguage'),'', $mailsubject);
            $mailsubject = str_ireplace(__('[APPOINTMENTNAME]', 'af2_multilanguage'), '', $mailsubject);
            $mailsubject = str_ireplace(__('[APPOINTMENTTIME]', 'af2_multilanguage'), __('No appointment has been booked!', 'af2_multilanguage'), $mailsubject);
        }


        $smtp_do = $form_content->use_smtp;
        $wp_mail_do = $form_content->use_wp_mail;

        $smtp_host = '';
        $smtp_username = '';
        $smtp_password = '';
        $smtp_port = '';
        $smtp_from_name = '';
        $smtp_type = '';

        if ($smtp_do === true || $smtp_do === 'true') {
            $smtp_host = $form_content->smtp_host;
            $smtp_username = $form_content->smtp_username;
            $smtp_password = $form_content->smtp_password;
            $smtp_port = $form_content->smtp_port;
            $smtp_type = $form_content->smtp_type;
        }

        if ($smtp_host === '' || $smtp_username === '' || $smtp_password === '' || $smtp_port === '' || $smtp_type === '') {
            $smtp_do = false;
        }

        $autoresponder_to = '';

        $x = 0;
        foreach ($form_questions as $form_question) {
            
            if ($form_question->typ == 'html_content')
                continue;
            
            $mailtext = str_ireplace('[' . $form_question->id . ']', $answer_block[$x], $mailtext);

            if ($use_autoresponder === true || $use_autoresponder === 'true') {
                if ('[' . $form_question->id . ']' === $autoresponder_field) {
                    $autoresponder_to = $answer_block[$x];
                }
                $autoresponder_text = str_ireplace('[' . $form_question->id . ']', $answer_block[$x], $autoresponder_text);
            }

            $x++;
        }
        
        $headers = 'Content-Type: text/html; charset=UTF-8'. "\r\n";
        $headers .= 'From: ' . $mailfrom_name . ' <' . $mailfrom . '>' . "\r\n";
        $headers .= 'CC: ' . $mailcc . "\r\n";
        $headers .= 'BCC: ' . $mailbcc . "\r\n";
        $headers .= 'Reply-To: ' . $mail_replyto . "\r\n";

        // FILE SIZE PROBLEM
        $attachments = array();
        // CREATING ATTACHMENTS
        if( $attachment_ids != null && sizeof( $attachment_ids ) > 0 ) {
            foreach($attachment_ids as $attachment_id) {
                $attachment_url = wp_get_attachment_url( $attachment_id );
                $attachment_url_loc = explode(site_url(), $attachment_url)[1];
                $attachment_url_local = explode('wp-content', $attachment_url_loc)[1];
                $attachment_url_final = WP_CONTENT_DIR . $attachment_url_local;
                array_push( $attachments, $attachment_url_final );
            }
        }

        //echo json_encode($attachments);
        //die();
        $sumSize = 0;
        foreach($attachments as $attachment) {
            $realSize = round( realFileSize($attachment) / 1024 / 1024, 1, PHP_ROUND_HALF_UP );
            $sumSize = $sumSize + $realSize;
        }

        if($sumSize >= 10) {
            $attachments = false;
        }

        //check if the email address is invalid $secure_check
        $secure_check = sanitize_my_email($mailfrom);
        if ($secure_check == false) {
            echo '<div class="af2_response_error">'.__('An error has occurred!', 'af2_multilanguage').'</div>';

            die();
        } else { // SEND EMAIL
            // E-Mail
            //EMAIL TEXT FROM CF
            //$messag = '';
            //if($mail_sendtext === '' || $mail_sendtext === null || $mail_sendtext === 'undefined')
            //{ 
                $messag = __('FORM SENT', 'af2_multilanguage'); 
            //}
            //else {
              //  $messag = $mail_sendtext;
            //}
            $mailtext =  nl2br($mailtext);
            if ($smtp_do === true || $smtp_do === 'true') {
                $cc_list = explode(',', $mailcc);
                $bcc_list = explode(',', $mailbcc);
                $res = smtp_mail($smtp_host, $smtp_username, $smtp_password, $smtp_port, $smtp_type, $mailto, $mailfrom, $mailfrom_name, $mailsubject, $mailtext, $cc_list, $bcc_list,$mail_replyto, $attachments);

                if ($res->status != 'Success') {
                    $messag = __('An error has occurred!', 'af2_multilanguage');
                }
            } else {

                if ($wp_mail_do === true || $wp_mail_do === 'true') {
                    if($attachments === false) {
                        $mailtext = $mailtext . '<br><br>'.__('The files were not sent as e-mail attachments due to the file size!', 'af2_multilanguage');
                        $m = wp_mail($mailto, $mailsubject, $mailtext, $headers);
                    }
                    else $m = wp_mail($mailto, $mailsubject, $mailtext, $headers, $attachments);
                } else {
                    $m = mail($mailto, $mailsubject, $mailtext, $headers);
                }
            }

            if ($use_autoresponder === true || $use_autoresponder === 'true') {
                $autoresponder_text =  nl2br($autoresponder_text);
                if ($smtp_do === true || $smtp_do === 'true') {
                    $res = smtp_mail2($smtp_host, $smtp_username, $smtp_password, $smtp_port, $smtp_type, $autoresponder_to, $mailfrom, $mailfrom_name, $autoresponder_subject, $autoresponder_text, $autoresponder_attachment_url);

                    if ($res->status != 'Success') {
                        $messag = __('An error has occurred!', 'af2_multilanguage');
                    }
                } else {

                    $autoresponder_headers = 'Content-Type: text/html; charset=UTF-8'. "\r\n";
                    $autoresponder_headers .= 'From: ' . $mailfrom_name . ' <' . $mailfrom . '>';
                    
                    if ($wp_mail_do === true || $wp_mail_do === 'true') {
                        $m = wp_mail($autoresponder_to, $autoresponder_subject, $autoresponder_text, $autoresponder_headers, $autoresponder_attachment_url);
                    } else {
                        $m = mail($autoresponder_to, $autoresponder_subject, $autoresponder_text, $autoresponder_headers);
                    }
                }
            }

            if($terminbuchungactive) {
                $id = $terminbuchungsobject->id;
                $post = get_post($id);

                $post_content = af2_get_post_content($post);
                $post_content = json_decode(json_encode($post_content));

                $terminbuchungsid = $post_content->terminbuchungsid;
                
                $terminbuchung = get_post($terminbuchungsid);
                $terminbuchung_content = af2_get_post_content($terminbuchung);
                $terminbuchung_content = json_decode(json_encode($terminbuchung_content));

                $terminbuchungs_json['dauer'] = $terminbuchungsobject->duration;
                $terminbuchungs_json['min'] = $terminbuchungsobject->duration_min;
                $terminbuchungs_json['std'] = $terminbuchungsobject->duration_std;
                $terminbuchungs_json['zeit'] = $terminbuchungsobject->time;
                $expl = explode('/',  $terminbuchungsobject->date);
                $terminbuchungs_json['datum'] = $expl[1].'.'.$expl[0].'.'.$expl[2];
                $terminbuchungs_json['titel'] = $terminbuchung_content->title;
                $terminbuchungs_json['lead_id'] = $lead_id;
                $terminbuchungs_json['terminbuchungsid'] = $terminbuchung->ID;
                $terminbuchungs_save_json = urlencode(serialize($terminbuchungs_json));
                $id = wp_insert_post(array('post_content' => $terminbuchungs_save_json, 'post_type' => TERMIN_POST_TYPE, 'post_status' => 'privat'));
    
    
                if($terminbuchung_content->cronofy_token_data == null) {
                    
                }
                else {
                    $urlparts = parse_url(home_url());
                    $domain = $urlparts['host'];
                    $key = get_option('af2_license_key');

                    $url = 'https://member.funnelforms.io/wp-json/cronofy/v1/addEvent';
                    $params = '?';
                    $params .= 'license_key='.$key;
                    $params .= '&domain='.$domain;

                    $token = $terminbuchung_content->cronofy_token_data;
                    $tdate = explode('/', $terminbuchungsobject->date);

                    $descriptionJson = json_decode(json_encode($zapier_json));

                    $description = '';

                    foreach($descriptionJson->contact_form as $datainput) {
                        $description .= $datainput->id . ': '.$datainput->input."\r\n";
                    }


                    $params .= '&token='.af_base64UrlEncode(json_encode($token));
                    $params .= '&calendar_id='.$terminbuchung_content->calendar_typ;

                    $title = $terminbuchung_content->title;
                    $params .= '&summary_='.af_base64UrlEncode($title);

                    $params .= '&tzid='.'Europe/Amsterdam';//$terminbuchung_content->timezone;
                    $params .= '&description='.af_base64UrlEncode($description);

                    $startDateTime = af2_dateTime_getDateTimeByStringArray($tdate, $terminbuchungsobject->time, 'Europe/Amsterdam');
                    $startDateTime = af2_dateTime_convertDateTimeTimezone($startDateTime, 'GMT0');
                    $startDateTimeString = af2_dateTime_getDateTimeFormattedStringByDateTime($startDateTime);

                    $params .= '&start='.$startDateTimeString;

                    $endDateTime = $startDateTime->modify('+'.$terminbuchungsobject->duration_min.' minutes');
                    $endDateTime = $endDateTime->modify('+'.$terminbuchungsobject->duration_std.' hours');
                    $endDateTimeString = af2_dateTime_getDateTimeFormattedStringByDateTime($endDateTime);

                    $params .= '&end='.$endDateTimeString;

                    
                    //$attendees = array(array('email' => 'fabio.woelker@anfrageformular.com', 'display_name' => 'Fabio Wölker'));
                    //$reminders = array(array('minutes' => 30), array('minutes' => 1440)); 
                    
                    $termin_mails = array();

                    $ixt = 0;
                    foreach($form_content->questions as $t_question) {
                        if($t_question->typ == 'text_type_mail') {
                            $answer_block = $answers[sizeof($answers) - 1];
                            
                            array_push($termin_mails, array('email' => $answer_block[$ixt]));
                        }
                        $ixt++;
                    }

                    $attendeee = af_base64UrlEncode(serialize($termin_mails));
                    $params .= '&attendees='.$attendeee;

                    if($terminbuchung_content->reminder != null) {

                        $reminders = array();

                        foreach($terminbuchung_content->reminder as $remind) {
                            $number = $remind->number;
                            $unit = $remind->unit;

                            if($unit == 'days') $number = $number * 24 * 60;
                            if($unit == 'hours') $number = $number * 60;

                            array_push($reminders, array('minutes' => intval($number)));
                        }

                        $params .= '&reminders='.af_base64UrlEncode(serialize($reminders));

                    }
                    //$term_terminjson = json_decode('{"starttime":"", "endtime":"", "timezone":""}');
                    //$tdate = explode('/', $terminbuchungs_json->datum);
                    //$term_terminjson->starttime = $tdate[2] . '-' . $tdate[0] . '-' . $tdate[1].'T'.$terminbuchungs_json->zeit.':00';
                    //$startDate = new DateTime($term_terminjson->starttime);
                    //$term_terminjson->endtime = $startDate->modify('+'.$terminbuchungs_json->min.' minutes');
                    //$term_terminjson->endtime = $term_terminjson->endtime->modify('+'.$terminbuchungs_json->std.' hours');
                    //$term_terminjson->endtime = $term_terminjson->endtime->format('Y-m-d').'T'.$term_terminjson->endtime->format('H:i').':00';
                    //$term_terminjson->timezone = $terminbuchung_content->timezone;
                    //$term_terminjson->title = $terminbuchung->post_title;

                    //$term_terminjson = af_base64UrlEncode(json_encode($term_terminjson));
    
                    $ch = curl_init();
                    $headers = array(
                        'Accept: text/plain',
                        'Content-Type: text/plain',
                    );
                    curl_setopt($ch, CURLOPT_URL, $url.$params);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                
                    $resp = json_decode(curl_exec($ch));
                
                    curl_close($ch);
            
                    $cont = $resp;//json_decode($resp);

                    if($resp != null && $cont->error == 0 && $cont->autherror == 0) {
                            
                            if(isset($cont->token)) {
                                $_post = get_post($terminbuchungsid);

                                $_post_title_ = $_post->post_title;
                                $_post_content_ = json_decode($_post->post_content);
                                $_post_content_->cronofy_token_data->access_token = $cont->token->access_token;
                                $_post_content_->cronofy_token_data->refresh_token = $cont->token->refresh_token;

                                wp_update_post(array('ID' => $terminbuchungsid, 'post_status' => 'privat', 'post_title' => $_post_title_, 'post_content' => json_encode($_post_content_)));
                            }
                    }else {
            
                       // $token = $resp->msg;
                        //$terminbuchung_content->google_data = $token;
                
                            //wp_update_post(array('ID' => $terminbuchungsid, 'post_status' => 'privat', 'post_title' => $terminbuchung->post_title, 'post_content' => json_encode($terminbuchung_content)));
                     //}
                    }
                }
            }

            if($webhook != null) {
                af2_executeWebhook($webhook, $zapier_json, $lead_id);
            }

            if ($active_dealsnprojects != null) {
                require_once AF2_INTEGRATION_HANDLER_DEALSNPROJECTS;
                $dnp = new DealsNProjects_Integration();

                if($dnp->is_active()) {
                    $dnp->parse_form_questions_to_values($active_dealsnprojects, $contact_form_answers, $m_answers);
                    $dnp->send_to_api();
                }

            }

            if ($active_activecampaign != null) {
                require_once AF2_INTEGRATION_HANDLER_ACTIVECAMPAIGN;
                $ac = new ActiveCampaign_Integration();

                if($ac->is_active()) {
                    $ac->parse_form_questions_to_values($active_activecampaign, $contact_form_answers, $m_answers);
                    $ac->send_to_api();
                }

            }

            if ($active_getresponse != null) {
                require_once AF2_INTEGRATION_HANDLER_GETRESPONSE;
                $gr = new GetResponse_Integration();

                if($gr->is_active()) {
                    $gr->parse_form_questions_to_values($active_getresponse, $contact_form_answers, $m_answers);
                    $gr->send_to_api();
                }

            }

            if ($active_pipedrive != null) {
                require_once AF2_INTEGRATION_HANDLER_PIPEDRIVE;
                $pipedrive = new PipeDrive_Integration();

                if($pipedrive->is_active()) {
                    $pipedrive->parse_form_questions_to_values($active_pipedrive, $contact_form_answers, $m_answers);
                    $pipedrive->send_to_api();
                }

            }

            if ($active_hubspot != null) {
                require_once AF2_INTEGRATION_HANDLER_HUBSPOT;
                $hubspot = new HubSpot_Integration();

                if($hubspot->is_active()) {
                    $hubspot->parse_form_questions_to_values($active_hubspot, $contact_form_answers, $m_answers);
                    $hubspot->send_to_api();
                }

            }

            if ($active_fincrm != null) {
                require_once AF2_INTEGRATION_HANDLER_FINCRM;
                $fincrm = new FinCRM_Integration();

                if($fincrm->is_active()) {
                    $fincrm->parse_form_questions_to_values($active_fincrm, $contact_form_answers, $m_answers);
                    $fincrm->send_to_api();
                }

            }

            if ($active_klicktipp != null) {
                require_once AF2_INTEGRATION_HANDLER_KLICKTIPP;
                $klicktipp_obj = new Klicktipp_Integration();

                if($klicktipp_obj->is_active()) {
                    $klicktipp_obj->parse_form_questions_to_values($active_klicktipp, $contact_form_answers, $m_answers);
                    $klicktipp_obj->send_to_api();
                }
            }


            $trackingafter = $form_content->tracking_code_after;

            //echo json_encode($attachments);
            echo '<div class="af2_response_success" data-tracking-after="'.base64_encode($trackingafter).'" data-redirect="' . $redirect . '" data-bl="' . $blank . '">' . $messag . '</div>';
            die();
        }
    }

    wp_die();
}





/**
* Return file size (even for file > 2 Gb)
* For file size over PHP_INT_MAX (2 147 483 647), PHP filesize function loops from -PHP_INT_MAX to PHP_INT_MAX.
*
* @param string $path Path of the file
* @return mixed File size or false if error
*/
function realFileSize($path)
{
    if (!file_exists($path))
        return false;

    $size = filesize($path);
   
    if (!($file = fopen($path, 'rb')))
        return false;
   
    if ($size >= 0)
    {//Check if it really is a small file (< 2 GB)
        if (fseek($file, 0, SEEK_END) === 0)
        {//It really is a small file
            fclose($file);
            return $size;
        }
    }
   
    //Quickly jump the first 2 GB with fseek. After that fseek is not working on 32 bit php (it uses int internally)
    $size = PHP_INT_MAX - 1;
    if (fseek($file, PHP_INT_MAX - 1) !== 0)
    {
        fclose($file);
        return false;
    }
   
    $length = 1024 * 1024;
    while (!feof($file))
    {//Read the file until end
        $read = fread($file, $length);
        $size = bcadd($size, $length);
    }
    $size = bcsub($size, $length);
    $size = bcadd($size, strlen($read));
   
    fclose($file);
    return $size;
}

function executePushNotification() {
    $url = 'https://member.funnelforms.io/wp-json/af2_push_service/v1/sendNotification';
    $params = '?';
    $params .= 'fcm_token='.urlencode(get_option('af2_registered_app_fcm')).'&';
    $params .= 'body='.urlencode(__('You received a new lead on your website', 'af2_multilanguage')).'&';
    $params .= 'title='.urlencode(__('New Lead', 'af2_multilanguage')).'';
    $ch = curl_init();
    $headers = array(
        'Accept: text/plain',
        'Content-Type: text/plain',
    );
    curl_setopt($ch, CURLOPT_URL, $url.$params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $resp = curl_exec($ch);

    curl_close($ch);
}



function af2_save_c_data($json, $answers, $form) {
    $json->contact = [];

    $i = 0;
    foreach ($answers[sizeof($answers) - 1] as $answer) {
        $json->contact[$i]->id = $form->questions[$i]->id;
        $json->contact[$i]->text = $answer;
        $i++;
    }

    return $json;
}

/*function af2_save_contact($save_json, $section, $content, $answers, $answer_block, $jsonm) {
    $sel = $jsonm->sections[$section]->contents[$content];
    $post_cont = get_post($sel->data);
    $post_json = json_decode(get_post_field('post_content', $post_cont));
    if ($post_json->error == false) {
        if ($post_json->answers != null) {
            $save_json->questions[$answers]->name = $post_json->name;
            $save_json->questions[$answers]->answers = [];
            if ($post_json->typ == 'af2_select') {
                $save_json->questions[$answers]->answers[0]->text = $post_json->answers[$answer_block[$answers]]->text;
            } else {
                $i = 0;
                foreach ($answer_block[$answers] as $ans) {
                    $save_json->questions[$answers]->answers[$i]->text = $post_json->answers[$ans]->text . "\n";
                    $i++;
                }
            }
        }

        if ($answers == sizeof($answer_block) - 2) {
            return $save_json;
        } else {
            $pos = false;
            $sec = false;
            $cont = false;
            if ($post_json->typ == 'af2_select') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            } else {
                $sec = $jsonm->sections[$section]->contents[$content]->connections[0]->to_section;
                $cont = $jsonm->sections[$section]->contents[$content]->connections[0]->to_content;
            }

            return af2_save_contact($save_json, $sec, $cont, $answers + 1, $answer_block, $jsonm);
        }
    } else {
        echo '<div class="af2_response_error">Ein Fehler ist aufgetreten!</div>';
        die();
    }
}*/

function af2_create_cf_json($zapier_json, $array, $cf_json) {
    $i = 0;
    $questions = array();
    if(!empty($cf_json)){
        $restricted_types = array('html_content','google_recaptcha');
        foreach ($cf_json->questions as $question ){
            if(!in_array($question->typ, $restricted_types)){
                $questions[] = $question;
            }
        }
        $cf_json->questions = $questions;
    }
    foreach ($array as $answer) {
        $zapier_json['contact_form'][$i] = array();
        $zapier_json['contact_form'][$i]['id'] = $cf_json->questions[$i]->id;
        $zapier_json['contact_form'][$i]['label'] = $cf_json->questions[$i]->label;
        $zapier_json['contact_form'][$i]['input'] = trim($answer);
        $zapier_json['contact_form'][$i]['typ'] = $cf_json->questions[$i]->typ;

        $i++;
    }

    return $zapier_json;
}

function validate_phone_number($phone, $mandatory) {
    $filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
    // Remove "-" from number
    $phone_to_check = str_replace("-", "", $filtered_phone_number);
    // Check the lenght of number
    // This can be customized if you want phone number from a specific country
    if ($mandatory == 'true' && (strlen($phone_to_check) < 7 || strlen($phone_to_check) > 20)) return false;
    return true;
}

function validate_phone_number_country($phone) {
    $filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
    // Remove "-" from number
    $phone_to_check = str_replace("-", "", $filtered_phone_number);
    // Check the lenght of number
    // This can be customized if you want phone number from a specific country
    if (strlen($phone_to_check) < 7 || strlen($phone_to_check) > 20) return false;
    if(strpos($phone_to_check, '+') === false) return false;
    return true;
}

function create_phone_number_country($phone) {
    $filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
    // Remove "-" from number
    $phone_to_check = str_replace("-", "", $filtered_phone_number);

    return $phone_to_check;
}

// CREATING THE ANSWER JSON DEPENDING ON CONDITIONALS
function af2_create_answers_json($answer_text, $section, $content, $answers, $answer_block, $jsonm, $z, $webhook, $offset) {
    $z++;
    $sel = $jsonm->sections[$section]->contents[$content];
    $post_cont = get_post($sel->data);

    $post_json = af2_get_post_content($post_cont);
    $post_json = json_decode(json_encode($post_json));

    if ($post_json->error == false) {
        /**
         * ER MUSS ERKENNEN, OB FRAGE ODER KONTAKTFORMULAR -> TRIGGERT NUR BEI FRAGE
         */
        if (!isset($post_json->use_autorespond)) {
            if ($post_json->typ == 'af2_select') {
                $frage = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = $frage;
                $answer_text['questions'][$z]['antwort'] = $post_json->answers[$answer_block[$answers]]->text;

                // Hidden fields
                $hidden_field = $post_json->answers[$answer_block[$answers]]->hidden_field;

                // Check that hidden fields are not empty
                if($hidden_field != null && trim($hidden_field) != '') {
                    $answer_text['hidden_fields'][$frage] = $hidden_field;
                }

            } else if ($post_json->typ == 'af2_textfeld') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = $answer_block[$answers];
            } else if ($post_json->typ == 'af2_textbereich') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $ans = str_replace("\n", "<br>", $answer_block[$answers]);
                $answer_text['questions'][$z]['antwort'] = $ans;
            } else if ($post_json->typ == 'af2_datum') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = $answer_block[$answers];
            } else if ($post_json->typ == 'af2_slider') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = $answer_block[$answers];
            } else if ($post_json->typ == 'af2_content') {
                
            } else if ($post_json->typ == 'af2_multiselect') {
                $frage = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = $frage;
                $answer_text['questions'][$z]['antwort'] = array();
                $y = 0;
                $str = '';
                foreach ($answer_block[$answers] as $ans) {
                    $hidden_field = $post_json->answers[$ans]->hidden_field;
                    if($hidden_field != null && trim($hidden_field) != '') {
                        if($answer_text['hidden_fields'][$frage] == null) $answer_text['hidden_fields'][$frage] = array();
                        array_push($answer_text['hidden_fields'][$frage], $hidden_field);
                    }

                    if(isset($webhook) && $webhook) 
                    {
                        if( $y > 0 )
                        {
                            $str .= ';';
                        }
                        $str .= $post_json->answers[$ans]->text;

                        $answer_text['questions'][$z]['antwort'] = $str;
                    }
                    else array_push($answer_text['questions'][$z]['antwort'], $post_json->answers[$ans]->text);

                    $y++;
                }

            } else if ($post_json->typ == 'af2_dateiupload') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = array();
                foreach ($answer_block[$answers] as $ans) {
                    if(wp_get_attachment_url($ans))
                        array_push($answer_text['questions'][$z]['antwort'], wp_get_attachment_url($ans));
                }
            } else if ($post_json->typ == 'af2_dropdown') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = $post_json->dropdown_options[$answer_block[$answers]]->value;
            } else if ($post_json->typ == 'af2_adressfeld') {
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = $answer_block[$answers];
            } else if ($post_json->typ == 'af2_terminbuchung') {
                $expl = explode('/', $answer_block[$answers]['date']);
                $answer_text['questions'][$z] = array();
                $answer_text['questions'][$z]['frage'] = addslashes(strip_tags($post_json->name));
                $answer_text['questions'][$z]['antwort'] = $expl[1].'.'.$expl[0].'.'.$expl[2]." - ".$answer_block[$answers]['time']." - ".$answer_block[$answers]['duration'];
            } 
        }
        if ($answers == sizeof($answer_block) - $offset) {
            return $answer_text;
        } else {
            $pos = false;
            $sec = false;
            $cont = false;
            if ($post_json->typ == 'af2_select') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }
            //Slider conditions
            else if ($post_json->typ == 'af2_slider') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections; //Getting connections
                //Loop through all connections
                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == '-1') {    //Allgemein - SET
                        if ($sec === false) {                    //If nothing else found until yet
                            //Set contents
                            $sec = $conns[$i]->to_section;
                            $cont = $conns[$i]->to_content;
                            continue;
                        }
                    }



                    //Check that they are defined
                    if (isset($conns[$i]->operator) && isset($conns[$i]->number)) {
                        //Get Operators and values
                        $operator = $conns[$i]->operator;
                        $value = $conns[$i]->number;
                        //Switch the operator and fill all cases
                        switch ($operator) {
                            case '<': {
                                    if (intval($answer_block[$answers]) < intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '>': {
                                    if (intval($answer_block[$answers]) > intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '=': {
                                    if (intval($answer_block[$answers]) == intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                        }
                    }
                }
            } else if($post_json->typ == 'af2_dropdown') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            } 
            else {
                $sec = $jsonm->sections[$section]->contents[$content]->connections[0]->to_section;
                $cont = $jsonm->sections[$section]->contents[$content]->connections[0]->to_content;
            }
            return af2_create_answers_json($answer_text, $sec, $cont, $answers + 1, $answer_block, $jsonm, $z, $webhook, $offset);
        }
    } else {
        echo '<div class="af2_response_error">'.__('An error has occurred!', 'af2_multilanguage').'</div>';
        die();
    }
}
function af2_create_answers($answer_text, $section, $content, $answers, $answer_block, $jsonm) {
    $sel = $jsonm->sections[$section]->contents[$content];
    $post_cont = get_post($sel->data);

    $post_json = af2_get_post_content($post_cont);
    $post_json = json_decode(json_encode($post_json));

    /**
     * TO DO CHECK FOR CF
     */
    if ($post_json->error == false) {
        $lines = '_________________________';
        if (!isset($post_json->use_autorespond)) {
            if($post_json->typ != 'af2_content')
                $answer_text .= '<b>'.$post_json->name . "</b>\n";
            if ($post_json->typ == 'af2_select') {
                $answer_text .= $post_json->answers[$answer_block[$answers]]->text . "\n";

            } else if ($post_json->typ == 'af2_textfeld') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_textbereich') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_datum') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_slider') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_content') {
                
            } else if ($post_json->typ == 'af2_multiselect') {
                foreach ($answer_block[$answers] as $ans) {
                    $answer_text .= $post_json->answers[$ans]->text . "\n";

                }
            } else if ($post_json->typ == 'af2_dateiupload') {
                foreach ($answer_block[$answers] as $ans) {
                    $answer_text .= wp_get_attachment_url($ans) . "\n";
                }
            } else if ($post_json->typ == 'af2_dropdown') {
                //$answer_text .= $answer_block[$answers] . "\n";
                $answer_text .= $post_json->dropdown_options[$answer_block[$answers]]->value . "\n";
            } else if ($post_json->typ == 'af2_adressfeld') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_terminbuchung') {
                $expl = explode('/', $answer_block[$answers]['date']);
                $answer_text .= $expl[1].'.'.$expl[0].'.'.$expl[2]." - ".$answer_block[$answers]['time']." - ".$answer_block[$answers]['duration']."\n";
            }
        }
        $answer_text .= $lines;
        $answer_text .= "\n";
        $answer_text .= "\n";

        if ($answers == sizeof($answer_block) - 2) {
            $ret_val = $answer_text;
            return $ret_val;
        } else {
            $pos = false;
            $sec = false;
            $cont = false;
            if ($post_json->typ == 'af2_select') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }
            //Slider conditions
            else if ($post_json->typ == 'af2_slider') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections; //Getting connections
                //Loop through all connections
                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == '-1') { //Allgemein - SET
                        if ($sec === false) {     //If nothing else found until yet
                            //Set contents
                            $sec = $conns[$i]->to_section;
                            $cont = $conns[$i]->to_content;
                            continue;
                        }
                    }



                    //Check that they are defined
                    if (isset($conns[$i]->operator) && isset($conns[$i]->number)) {
                        //Get Operators and values
                        $operator = $conns[$i]->operator;
                        $value = $conns[$i]->number;
                        //Switch the operator and fill all cases
                        switch ($operator) {
                            case '<': {
                                    if (intval($answer_block[$answers]) < intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '>': {
                                    if (intval($answer_block[$answers]) > intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '=': {
                                    if (intval($answer_block[$answers]) == intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                        }
                    }
                }
            } else if($post_json->typ == 'af2_dropdown') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }  
            else {
                $sec = $jsonm->sections[$section]->contents[$content]->connections[0]->to_section;
                $cont = $jsonm->sections[$section]->contents[$content]->connections[0]->to_content;
            }

            return af2_create_answers($answer_text, $sec, $cont, $answers + 1, $answer_block, $jsonm);
        }
    } else {
        echo '<div class="af2_response_error">'.__('An error has occurred!', 'af2_multilanguage').'</div>';
        die();
    }
}
function af2_create_answers_with_hidden_fields($answer_text, $section, $content, $answers, $answer_block, $jsonm, $hidden_fields) {
    $sel = $jsonm->sections[$section]->contents[$content];
    $post_cont = get_post($sel->data);

    $post_json = af2_get_post_content($post_cont);
    $post_json = json_decode(json_encode($post_json));

    /**
     * TO DO CHECK FOR CF
     */
    if ($post_json->error == false) {
        $lines = '_________________________';
        if (!isset($post_json->use_autorespond)) {
            if($post_json->typ != 'af2_content')
                $answer_text .= '<b>'.$post_json->name . "</b>\n";
            if ($post_json->typ == 'af2_select') {
                $answer_text .= $post_json->answers[$answer_block[$answers]]->text . "\n";

                $hidden_field = $post_json->answers[$answer_block[$answers]]->hidden_field;
                if($hidden_field != null && trim($hidden_field) != '') {
                    $hidden_fields .= '<b>'.$post_json->name . "</b>\n";
                    $hidden_fields .=  $hidden_field . "\n";
                }
            } else if ($post_json->typ == 'af2_textfeld') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_textbereich') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_datum') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_slider') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_content') {
                
            } else if ($post_json->typ == 'af2_multiselect') {
                $added_name = false;
                foreach ($answer_block[$answers] as $ans) {
                    $answer_text .= $post_json->answers[$ans]->text . "\n";

                    $hidden_field = $post_json->answers[$ans]->hidden_field;
                    if($hidden_field != null && trim($hidden_field) != '') {
                        if(!$added_name) $hidden_fields .= '<b>'.$post_json->name . "</b>\n";
                        $added_name = true;
                        $hidden_fields .=  $hidden_field . "\n";
                    }
                }
            } else if ($post_json->typ == 'af2_dateiupload') {
                foreach ($answer_block[$answers] as $ans) {
                    $answer_text .= wp_get_attachment_url($ans) . "\n";
                }
            } else if ($post_json->typ == 'af2_dropdown') {
                //$answer_text .= $answer_block[$answers] . "\n";
                $answer_text .= $post_json->dropdown_options[$answer_block[$answers]]->value . "\n";
            } else if ($post_json->typ == 'af2_adressfeld') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_terminbuchung') {
                $expl = explode('/', $answer_block[$answers]['date']);
                $answer_text .= $expl[1].'.'.$expl[0].'.'.$expl[2]." - ".$answer_block[$answers]['time']." - ".$answer_block[$answers]['duration']."\n";
            }
        }
        $answer_text .= $lines;
        $answer_text .= "\n";
        $answer_text .= "\n";

        if($hidden_fields != null && trim($hidden_fields) != '') {
            $hidden_fields .= $lines;
            $hidden_fields .= "\n";
            $hidden_fields .= "\n";
        }

        if ($answers == sizeof($answer_block) - 2) {
            $ret_val = $answer_text;
            if($hidden_fields != null && trim($hidden_fields) != '') {
                $ret_val .= "\n\n\n<b>".__('Hidden fields', 'af2_multilanguage').":</b>\n\n".$hidden_fields;
            }
            return $ret_val;
        } else {
            $pos = false;
            $sec = false;
            $cont = false;
            if ($post_json->typ == 'af2_select') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }
            //Slider conditions
            else if ($post_json->typ == 'af2_slider') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections; //Getting connections
                //Loop through all connections
                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == '-1') { //Allgemein - SET
                        if ($sec === false) {     //If nothing else found until yet
                            //Set contents
                            $sec = $conns[$i]->to_section;
                            $cont = $conns[$i]->to_content;
                            continue;
                        }
                    }



                    //Check that they are defined
                    if (isset($conns[$i]->operator) && isset($conns[$i]->number)) {
                        //Get Operators and values
                        $operator = $conns[$i]->operator;
                        $value = $conns[$i]->number;
                        //Switch the operator and fill all cases
                        switch ($operator) {
                            case '<': {
                                    if (intval($answer_block[$answers]) < intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '>': {
                                    if (intval($answer_block[$answers]) > intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '=': {
                                    if (intval($answer_block[$answers]) == intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                        }
                    }
                }
            } else if($post_json->typ == 'af2_dropdown') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }  
            else {
                $sec = $jsonm->sections[$section]->contents[$content]->connections[0]->to_section;
                $cont = $jsonm->sections[$section]->contents[$content]->connections[0]->to_content;
            }

            return af2_create_answers_with_hidden_fields($answer_text, $sec, $cont, $answers + 1, $answer_block, $jsonm, $hidden_fields);
        }
    } else {
        echo '<div class="af2_response_error">'.__('An error has occurred!', 'af2_multilanguage').'</div>';
        die();
    }
}

function af2_create_api_answers($answer_text, $section, $content, $answers, $answer_block, $jsonm) {
    $sel = $jsonm->sections[$section]->contents[$content];
    $post_cont = get_post($sel->data);

    $post_json = af2_get_post_content($post_cont);
    $post_json = json_decode(json_encode($post_json));

    /**
     * TO DO CHECK FOR CF
     */
    if ($post_json->error == false) {
        $lines = '_________________________';
        if (!isset($post_json->use_autorespond)) {
            if($post_json->typ != 'af2_content')
                $answer_text .= ''.$post_json->name . "\n";
            if ($post_json->typ == 'af2_select') {
                $answer_text .= $post_json->answers[$answer_block[$answers]]->text . "\n";
            } else if ($post_json->typ == 'af2_textfeld') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_textbereich') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_datum') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_slider') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_content') {
                
            } else if ($post_json->typ == 'af2_multiselect') {
                foreach ($answer_block[$answers] as $ans) {
                    $answer_text .= $post_json->answers[$ans]->text . "\n";
                }
            } else if ($post_json->typ == 'af2_dateiupload') {
                foreach ($answer_block[$answers] as $ans) {
                    $answer_text .= wp_get_attachment_url($ans) . "\n";
                }
            } else if ($post_json->typ == 'af2_dropdown') {
                //$answer_text .= $answer_block[$answers] . "\n";
                $answer_text .= $post_json->dropdown_options[$answer_block[$answers]]->value . "\n";
            } else if ($post_json->typ == 'af2_adressfeld') {
                $answer_text .= $answer_block[$answers] . "\n";
            } else if ($post_json->typ == 'af2_terminbuchung') {
                $expl = explode('/', $answer_block[$answers]['date']);
                $answer_text .= $expl[1].'.'.$expl[0].'.'.$expl[2]." - ".$answer_block[$answers]['time']." - ".$answer_block[$answers]['duration']."\n";
            }
        }
        $answer_text .= $lines;
        $answer_text .= "\n";
        $answer_text .= "\n";

        if ($answers == sizeof($answer_block) - 2) {
            return $answer_text;
        } else {
            $pos = false;
            $sec = false;
            $cont = false;
            if ($post_json->typ == 'af2_select') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }
            //Slider conditions
            else if ($post_json->typ == 'af2_slider') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections; //Getting connections
                //Loop through all connections
                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == '-1') { //Allgemein - SET
                        if ($sec === false) {     //If nothing else found until yet
                            //Set contents
                            $sec = $conns[$i]->to_section;
                            $cont = $conns[$i]->to_content;
                            continue;
                        }
                    }



                    //Check that they are defined
                    if (isset($conns[$i]->operator) && isset($conns[$i]->number)) {
                        //Get Operators and values
                        $operator = $conns[$i]->operator;
                        $value = $conns[$i]->number;
                        //Switch the operator and fill all cases
                        switch ($operator) {
                            case '<': {
                                    if (intval($answer_block[$answers]) < intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '>': {
                                    if (intval($answer_block[$answers]) > intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                            case '=': {
                                    if (intval($answer_block[$answers]) == intval($value)) {
                                        $sec = $conns[$i]->to_section;
                                        $cont = $conns[$i]->to_content;
                                    }
                                    break;
                                }
                        }
                    }
                }
            } else if($post_json->typ == 'af2_dropdown') {
                $conns = $jsonm->sections[$section]->contents[$content]->connections;

                for ($i = 0; $i < sizeof($conns); $i++) {
                    if (strval($conns[$i]->from) == strval($answer_block[$answers])) {
                        $sec = $conns[$i]->to_section;
                        $cont = $conns[$i]->to_content;
                    } else if ($conns[$i]->from == '-1' || $conns[$i]->from == -1) {
                        $pos = $i;
                    }
                }

                if ($sec == false) {
                    $sec = $conns[$pos]->to_section;
                    $cont = $conns[$pos]->to_content;
                }
            }  
            else {
                $sec = $jsonm->sections[$section]->contents[$content]->connections[0]->to_section;
                $cont = $jsonm->sections[$section]->contents[$content]->connections[0]->to_content;
            }

            return af2_create_api_answers($answer_text, $sec, $cont, $answers + 1, $answer_block, $jsonm);
        }
    } else {
        echo '<div class="af2_response_error">'.__('An error has occurred!', 'af2_multilanguage').'</div>';
        die();
    }
}

function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

function af2_test_verification() {
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        die();
    }

    $sec = $_POST['sec'];
    $cont = $_POST['cont'];
    $dataid = $_POST['dataid'];
    $answers = $_POST['answers'];
    $attachment_ids = isset($_POST['attachment_ids']) ? $_POST['attachment_ids'] : null;

    $verifictationDataId = $_POST['verifictationDataId'];

    // SQL CHECKS
    $var = sql_check_it($sec);
    $var2 = sql_check_it($cont);
    $var3 = sql_check_it($dataid);
    $var4 = sql_check_it($answers);

    if ($var === 'ERROR' || $var2 === 'ERROR' || $var3 === 'ERROR' || $var4 === 'ERROR') {
        echo 'ERROR';
        die();
    }

    // VALIDATE THE NUMERICS
    if (!(is_numeric($sec) && is_numeric($cont) && is_numeric($dataid) )) {
        echo 'ERROR';
        die();
    } else {

        $base_post_structure = get_post($dataid);
        $structure_base_json = af2_get_post_content($base_post_structure);
        $jsonm = json_decode(json_encode($structure_base_json));

        $formular_id = $dataid;

        // CHECKING THAT POST IS A FORMULAR
        if ($base_post_structure == null) {
            echo 'ERROR';
            die();
        }
        if (get_post_field('post_type', $base_post_structure) != 'af2_formular') {
            echo 'ERROR';
            die();
        }

        $form_id = $jsonm->sections[$sec]->contents[$cont]->data;

        $form_post = get_post($form_id);
        $form_content = af2_get_post_content($form_post);
        $form_content = json_decode(json_encode($form_content));

        $i = 0;
        foreach ($answers as $answer) {
            if ($i < sizeof($answers) - 1) {
                if (is_array($answer) && ($answer['date'] == null && $answer['time'] == null && $answer['duration'] == null)) {
                    foreach ($answer as $a) {
                        if (!is_numeric($a)) {
							
                            echo 'ERROR';
                            die();
                        }
                    }
                }
            } else {
                // VALIDATING CONTACT FORM CONTENTS
                // VALIDATING REQUIREDS

                $form_questions = $form_content->questions;
                $answer_block = $answers[sizeof($answers) - 1];
                $x = 0;
                foreach ($form_questions as $form_question) {
                    
                    if ($form_question->typ == 'html_content')
                        continue;
                    
                    if ($form_question->required == 'true') {
                        if (is_numeric(strpos($form_question->typ, 'text_type_'))) {
                            if (trim($answer_block[$x]) == '') {
                                echo '<div class="af2_response_error" data-id="' . $x . '">'.__('This field is a required field!', 'af2_multilanguage').'</div>';

                                die();
                            }
                        } else if (is_numeric(strpos($form_question->typ, 'salutation'))) {
                            if (trim($answer_block[$x]) == 'keine Angabe') {
                                echo '<div class="af2_response_error" data-id="' . $x . '">'.__('This field is a required field!', 'af2_multilanguage').'</div>';

                                die();
                            }
                        } else {
                            if (strval($answer_block[$x]) == 'false') {
                                echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The checkbox must be active!', 'af2_multilanguage').'</div>';

                                die();
                            }
                        }
                    }

                    //VALIDATE PHONE
                    if ($form_question->typ == 'text_type_phone') {
                        if(!validate_phone_number($answer_block[$x], $form_question->required) && $answer_block[$x] != '') {
                            echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The phone number is not valid!', 'af2_multilanguage').'</div>';

                            die();
                        }
                    }
                    //VALIDATE PHONE
                    if ($form_question->typ == 'text_type_phone_verification') {
                        if(!validate_phone_number_country($answer_block[$x])) {
                            echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The mobile number is not valid! (Format: +1 702 12345678)', 'af2_multilanguage').'</div>';

                            die();
                        }
                        else $country_tel = create_phone_number_country($answer_block[$x]);
                    }

                    //VALIDATE EMAIL
                    if ($form_question->typ == 'text_type_mail') {
                        $cf_mail = trim($answer_block[$x]);
                        if (!filter_var($cf_mail, FILTER_VALIDATE_EMAIL) && $cf_mail != '') {
                            echo '<div class="af2_response_error" data-id="' . $x . '">'.__('The e-mail address is not valid!', 'af2_multilanguage').'</div>';

                            die();
                        }
                    }

                    $x++;
                }
            }

            $i++;
        }
    }

    if($country_tel == null) {
        echo 'empty';
    }
    else {
        $kontaktformulardata = json_decode(json_encode(af2_get_post_content(get_post($verifictationDataId))));
        $originator = $kontaktformulardata->smsSender;
        $message = $kontaktformulardata->smsText;
        $succ = af_sendVerifySMS($country_tel, $originator, $message);
        $succmessage = $succ[0];
        $succ_json = json_decode($succmessage);

        update_option('messagebird_error', 'false');
        update_option('messagebird_error_text', '');

        if($succ_json->err != null && isset($succ_json->err)) {
            $succ_json->code = $succ[1];
            $succ_json->number = $country_tel;
            $succmessage = json_encode($succ_json);

            update_option('messagebird_error', 'true');
            update_option('messagebird_error_text', strval($succ_json->err));
        }
        
        echo $succmessage;
    }

    die();

    wp_die();
}

function af_sendVerifySMS($country_tel, $originato, $message) {
    
    $originator = $originato;
    if(strlen($originato) > 11) $originator = 'Validierung';
    $recipient = $country_tel;
    $code = af2_random_code();

    while(true)
    {
        if(af2_gotValidationCode($code, $recipient)) {
            $code = af2_random_code();
        } else break;
    }

    //$text = $code.' lautet der Code zur DSGVO-konformen Nutzer-Verifizierung und der Freischaltung unserer kostenfreien Sicherheitscode Angebotes ';
    $text = $message;
    $text = str_ireplace('[code]', $code, $text);
    if(strlen($text) > 150) $text = $code.'lautet der Code zur DSGVO-konformen Nutzer-Verifizierung';
    af2_saveValidationCode($code, $country_tel);

	
	$json = json_decode('{"af2MessageBirdApiKey": "", "originator": "", "recipient": "", "text":"" }');
	
	$json->af2MessageBirdApiKey = get_option('af2_messagebird_key');
	$json->originator = $originator;
    $json->recipient = $recipient;
    $json->text = $text;
	
	$json = json_encode($json);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_URL, 'https://af-pushservice.com/sendSMS');
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);

    return  [$output, $code];
}

function af2_saveValidationCode($code, $number) {
    $id = intval(get_option('af2_verification_codes'));
    $codes_json = json_decode(get_post_field('post_content', $id));

    for($i = sizeof($codes_json->codes)-1; $i >= 0; $i--) {
        if(intval($codes_json->codes[$i]->timestamp) != intval(create_timestamp())) {
            array_splice($codes_json->codes, $i, 1);
        } else {
            if($codes_json->codes[$i]->number == $number) {
                array_splice($codes_json->codes, $i, 1);
            }
        }
    }

    $timestamp = af_create_timestamp();
    array_push($codes_json->codes, json_decode('{"code":"'.$code.'", "timestamp":"'.$timestamp.'", "number":"'.$number.'"}'));

    wp_update_post(array('ID' => $id, 'post_content' => json_encode($codes_json), 'post_type' => 'af2_ver_codes', 'post_status' => 'privat'));
}

function af2_gotValidationCode($code, $number) {
    $id = intval(get_option('af2_verification_codes'));
    $codes_json = json_decode(get_post_field('post_content', $id));

    foreach($codes_json->codes as $cod) {
        if($cod->code == $code && $cod->number == $number) {
            return true;
        }
    }
    return false;
}

function af2_gotValidationCodeDelete($code, $number) {
    $id = intval(get_option('af2_verification_codes'));
    $codes_json = json_decode(get_post_field('post_content', $id));

    for($i = 0; $i < sizeof($codes_json->codes); $i++) {
        if($codes_json->codes[$i]->code == $code && $codes_json->codes[$i]->number == $number) {
            array_splice($codes_json->codes, $i, 1);
            wp_update_post(array('ID' => $id, 'post_content' => json_encode($codes_json), 'post_type' => 'af2_ver_codes', 'post_status' => 'privat'));
            return true;
        }
    }
    return false;
}

function af2_random_code() {
    $digit1 = strval(random_int(0, 9));
    $digit2 = strval(random_int(0, 9));
    $digit3 = strval(random_int(0, 9));
    
    $digit4 = strval(random_int(0, 9));
    $digit5 = strval(random_int(0, 9));
    $digit6 = strval(random_int(0, 9));

    return $digit1.$digit2.$digit3.$digit4.$digit5.$digit6;
}


add_action('wp_ajax_nopriv_af2_send_mail', 'af2_send_mail');
add_action('wp_ajax_af2_send_mail', 'af2_send_mail');

add_action('wp_ajax_nopriv_af2_test_verification', 'af2_test_verification');
add_action('wp_ajax_af2_test_verification', 'af2_test_verification');

function smtp_mail($host, $user, $password, $port, $type, $to, $from, $from_nam, $subject, $body, $cc, $bcc,$replyto,$attachments) {

    $errors = '';

    //$swpsmtp_options = get_option('twm_smtp_options');

    require_once( ABSPATH . WPINC . '/class-smtp.php' );
    require_once( ABSPATH . WPINC . '/class-phpmailer.php' );
    $mail = new \PHPMailer();

    $charset = get_bloginfo('charset');
    $mail->CharSet = $charset;
    $mail->Timeout = 10;

    $from_name = $from_nam;
    $from_email = $from;

    $mail->IsSMTP();

    $mail->SMTPAuth = true;
    $mail->Username = $user;
    $mail->Password = $password;

    $mail->SMTPSecure = $type;

    /* PHPMailer 5.2.10 introduced this option. However, this might cause issues if the server is advertising TLS with an invalid certificate. */
    $mail->SMTPAutoTLS = false;

    /* Set the other options */
    $mail->Host = $host;
    $mail->Port = $port;

    $mail->SetFrom($from_email, $from_name);
    $mail->isHTML(true);
    $mail->Subject = $subject;
    //$mail->MsgHTML($body);
    if($attachments === false) {
        $mail->Body = $body . '<br><br>'.__('The files were not sent as e-mail attachments due to the file size!', 'af2_multilanguage');
    }
    else $mail->Body = $body;
    $mail->AddAddress($to);

    foreach ($cc as $c) {
        $c = trim($c);

        $mail->addCC($c);
    }

    foreach ($bcc as $bc) {
        $bc = trim($bc);

        $mail->addBCC($bc);
    }
    
    if(!empty($replyto)){
        $mail->addReplyTo(trim($replyto));
    }

    if ($attachments !== false) {
        $k = 0;
        foreach($attachments as $attachment)
        {
            $name_arr = explode('/', $attachment);
            $name_size = count($name_arr);
            $name = $name_arr[$name_size-1];
            $mail->AddAttachment($attachment, $name);
            $k++;
        }
        
    }

    global $debugMSG;
    $debugMSG = '';
    $mail->Debugoutput = function($str, $level) {
        global $debugMSG;
        $debugMSG .= $str;
    };
    $mail->SMTPDebug = 4;

    /* Send mail and return result */

    //$error = $mail->Send();

    if (!$mail->Send())
        $errors = $mail->ErrorInfo;

    $mail->ClearAddresses();
    $mail->ClearAllRecipients();
    $mail->clearCCs();
    $mail->clearBCCs();

    $cl = new \stdClass();
    $cl->debug = $debugMSG;

    if (!empty($errors)) {
        $cl->msg = $errors;
        $cl->status = 'Fail';
    } else {
        $cl->msg = 'Test mail was sent';
        $cl->status = 'Success';
    }

    return $cl;

    //return $error;
}

function smtp_mail2($host, $user, $password, $port, $type, $to, $from, $from_nam, $subject, $body, $attachments) {

    $errors = '';

    //$swpsmtp_options = get_option('twm_smtp_options');

    require_once( ABSPATH . WPINC . '/class-smtp.php' );
    require_once( ABSPATH . WPINC . '/class-phpmailer.php' );
    $mail = new \PHPMailer();

    $charset = get_bloginfo('charset');
    $mail->CharSet = $charset;
    $mail->Timeout = 10;

    $from_name = $from_nam;
    $from_email = $from;

    $mail->IsSMTP();

    $mail->SMTPAuth = true;
    $mail->Username = $user;
    $mail->Password = $password;

    $mail->SMTPSecure = $type;

    /* PHPMailer 5.2.10 introduced this option. However, this might cause issues if the server is advertising TLS with an invalid certificate. */
    $mail->SMTPAutoTLS = false;

    /* Set the other options */
    $mail->Host = $host;
    $mail->Port = $port;

    $mail->SetFrom($from_email, $from_name);
    $mail->isHTML(true);
    $mail->Subject = $subject;
    //$mail->MsgHTML($body);
    $mail->Body = $body;
    $mail->AddAddress($to);

    if ($attachments != array()) {
        $k = 0;
        foreach($attachments as $attachment)
        {
            $name_arr = explode('/', $attachment);
            $name_size = count($name_arr);
            $name = $name_arr[$name_size-1];
            $mail->AddAttachment($attachment, $name);
            $k++;
        }
    }

    global $debugMSG;
    $debugMSG = '';
    $mail->Debugoutput = function($str, $level) {
        global $debugMSG;
        $debugMSG .= $str;
    };
    $mail->SMTPDebug = 4;

    /* Send mail and return result */

    //$error = $mail->Send();

    if (!$mail->Send())
        $errors = $mail->ErrorInfo;

    $mail->ClearAddresses();
    $mail->ClearAllRecipients();
    $mail->clearCCs();
    $mail->clearBCCs();

    $cl = new \stdClass();
    $cl->debug = $debugMSG;

    if (!empty($errors)) {
        $cl->msg = $errors;
        $cl->status = 'Fail';
    } else {
        $cl->msg = 'Test mail was sent';
        $cl->status = 'Success';
    }

    return $cl;

    //return $error;
}



function af2_replace_tags($form_questions,$answer_block,$text){
    $x = 0;
    foreach ($form_questions as $form_question) {
        
        if ($form_question->typ == 'html_content')
            continue;
        
        $text = str_ireplace('[' . $form_question->id . ']', $answer_block[$x], $text);
        $x++;
    }
    return $text;
}

function wpaf2_custom_upload_dir( $dir_data ) {
    // $dir_data already you might want to use
    $custom_dir = 'af2';
    return [
        'path' => $dir_data[ 'basedir' ] . '/' . $custom_dir,
        'url' => $dir_data[ 'url' ] . '/' . $custom_dir,
        'subdir' => '/' . $custom_dir,
        'basedir' => $dir_data[ 'error' ],
        'error' => $dir_data[ 'error' ],
    ];
}

add_action('wp_ajax_af2_handel_file_upload', 'af2_handel_file_upload');
add_action('wp_ajax_nopriv_af2_handel_file_upload', 'af2_handel_file_upload');
function af2_handel_file_upload(){
    $resp = array();
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        echo 'ERROR';
        die();
    }

    add_filter( 'upload_dir', 'wpaf2_custom_upload_dir' );
    // uploading
    $media_id = media_handle_upload( 'af2_file', 0 );
    // remove so it doesn't apply to all uploads
    remove_filter( 'upload_dir', 'wpaf2_custom_upload_dir' );

    if ( is_wp_error( $media_id ) ) {
        $resp['success'] = false;
        $resp['error'] = $media_id->get_error_message();
        $resp['media_id'] = 0;
    }else{
        $resp['success'] = true;
        $resp['media_id'] = $media_id;
        $resp['media_url'] = wp_get_attachment_url($media_id);
    }
    
    echo json_encode($resp);
    die();
}     

add_action('wp_ajax_af2_handel_file_remove', 'af2_handel_file_remove');
add_action('wp_ajax_nopriv_af2_handel_file_remove', 'af2_handel_file_remove');

function af2_handel_file_remove(){
    $resp = array();
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        echo 'ERROR';
        die();
    }
    $resp['success'] = false;
    if(isset($_POST['attachment_id'])){
        $resp['success'] = true;
        wp_delete_attachment($_POST['attachment_id'],true);
    }
    echo json_encode($resp);
    die();
}

function af2_get_supported_mime_types(){
    $supported_types = array();
    $restricted_types = array('application/javascript','text/css','text/html','application/java','application/ttaf+xml','application/vnd.ms-access','application/vnd.ms-project','application/vnd.oasis.opendocument.database');
    $wp_mime_types = get_allowed_mime_types();
    foreach ($wp_mime_types as $ext=>$type){
        if(!in_array($type, $restricted_types)){
            $supported_types[] = $type;
        }
    }
    
    return $supported_types;
}


function af2_get_terminbuchungs_data() {
    if (!( check_ajax_referer('af2_FE_nonce', '_ajax_nonce') )) {
        die();
    }
	

    $id = $_GET['id'];
    $post = get_post($id);
    $post_content = af2_get_post_content($post);
    $post_content = json_decode(json_encode($post_content));

	$terminbuchungsid = $post_content->terminbuchungsid;
	
	$terminbuchung = get_post($terminbuchungsid);
	$terminbuchung_content = af2_get_post_content($terminbuchung);
    $terminbuchung_content = json_decode(json_encode($terminbuchung_content));
	
	if($terminbuchung_content->cronofy_token_data == null ||$terminbuchung_content->error == true) {
		echo 'null';
		wp_die();
    }
    else {
        $urlparts = parse_url(home_url());
        $domain = $urlparts['host'];
        $key = get_option('af2_license_key'); 
        $ch = curl_init();
        $headers = array(
            'Accept: text/plain',
            'Content-Type: text/plain',
        );
        $token = $terminbuchung_content->cronofy_token_data;
        $idsstring = '';
        $xxxa = 0;
        foreach($terminbuchung_content->calendar_conflict as $conflict) {
            if(isset($conflict)) {
                if($xxxa == 0) $idsstring = $conflict;
                else $idsstring = $idsstring.'x,X,,,X,x'.$conflict;
                $xxxa++;
            }
            
        }
        $calendar_ids =  $idsstring;
        $tzid = 'Europe/Amsterdam';//$terminbuchung_content->timezone;
        
        curl_setopt($ch, CURLOPT_URL, 'https://member.funnelforms.io/wp-json/cronofy/v1/getFreeTime/?license_key='.$key.'&domain='.$domain.'&token='.af_base64UrlEncode(json_encode($token)).'&calendar_ids='.$calendar_ids.'&tzid='.$tzid);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
        $resp = json_decode(curl_exec($ch));
                
        curl_close($ch);

        $cont = $resp;//json_decode($resp);

        if($resp != null && $cont->error == 0 && $cont->autherror == 0) {
                            
            if(isset($cont->token)) {
                $_post = get_post($terminbuchungsid);

                $_post_title_ = $_post->post_title;
                $_post_content_ = json_decode($_post->post_content);
                $_post_content_->cronofy_token_data->access_token = $cont->token->access_token;
                $_post_content_->cronofy_token_data->refresh_token = $cont->token->refresh_token;

                wp_update_post(array('ID' => $terminbuchungsid, 'post_status' => 'privat', 'post_title' => $_post_title_, 'post_content' => json_encode($_post_content_)));
            }
        }else {

        // $token = $resp->msg;
            //$terminbuchung_content->google_data = $token;

                //wp_update_post(array('ID' => $terminbuchungsid, 'post_status' => 'privat', 'post_title' => $terminbuchung->post_title, 'post_content' => json_encode($terminbuchung_content)));
        //}
        }

        // get last date valid for


        $retecho = array();
        if(isset($resp->content) && is_array($resp->content) && !empty($resp->content)) $retecho = $resp->content;
        $retecho = json_encode(["lastTerminbuchungsTimeslotsAllEvents" => $retecho]);
        echo $retecho;//json_encode('[]');//$resp->events);

        wp_die();
    }
}

add_action('wp_ajax_nopriv_af2_get_terminbuchungs_data', 'af2_get_terminbuchungs_data');
add_action('wp_ajax_af2_get_terminbuchungs_data', 'af2_get_terminbuchungs_data');

function af2_dateTime_getDateTimeByStringArray($dateStringArray, $time, $defaultTimeZone) {
    date_default_timezone_set($defaultTimeZone);

    $date = $dateStringArray[2] . '-' . $dateStringArray[0] . '-' . $dateStringArray[1].'T'.$time.':00';
    return new DateTime($date);
}

function af2_dateTime_getDateTimeFormattedStringByDateTime($dateTime) {
    return $dateTime->format('Y-m-d').'T'.$dateTime->format('H:i').':00Z';
}

function af2_dateTime_convertDateTimeTimezone($dateTime, $timezoneString) {
    $valueDateTime = $dateTime;
    $valueDateTime = $valueDateTime->setTimeZone(new DateTimeZone($timezoneString));
    return $valueDateTime;
}

class AF2_HubSpot_API {
    private $hapikey; //get_option('hubspot_key');
    private $contact_properties;
    private $deal_properties;
    private $contact;

    function __construct($hapikey, $contact_properties) {
        $this->hapikey = $hapikey;
        $this->contact_properties = $contact_properties;
    }

    function hubspot_create_contact() {
        if(!isset($this->hapikey)) return false;
        if(!isset($this->contact_properties)) return false;

        $post_json = json_encode($this->contact_properties);
        $hapikey = $this->hapikey;
        
        $endpoint = 'https://api.hubapi.com/contacts/v1/contact?hapikey=' . $hapikey;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_errors = curl_error($ch);
        curl_close($ch);
        
        if(($curl_errors == "" || $curl_errors ==  null) && $status_code == 200) {
            $this->contact = json_decode($response);
            return true;
        }
        else if(($curl_errors == "" || $curl_errors ==  null) && $status_code == 409) {
            $this->contact = json_decode($response)->identityProfile;
            $this->hubspot_update_contact();
        }
        return false;
    }

    function hubspot_update_contact() {
        if(!isset($this->hapikey)) return false;
        if(!isset($this->contact_properties)) return false;
        if(!isset($this->contact)) return false;

        $post_json = json_encode($this->contact_properties);
        $hapikey = $this->hapikey;
        
        $endpoint = 'https://api.hubapi.com/contacts/v1/contact/vid/'.$this->contact->vid.'/profile?hapikey=' . $hapikey;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_errors = curl_error($ch);
        curl_close($ch);
        
        if(($curl_errors == "" || $curl_errors ==  null) && $status_code == 204) {
            return true;
        }
        return false;
    }

    function hubspot_create_deal() {
        if(!isset($this->hapikey)) return false;
        if(!isset($this->contact)) return false;

        $post_json = json_encode($this->deal_properties);
        $hapikey = $this->hapikey;
        
        $endpoint = 'https://api.hubapi.com/deals/v1/deal?hapikey=' . $hapikey;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_errors = curl_error($ch);
        curl_close($ch);
        
        if(($curl_errors == "" || $curl_errors ==  null) && $status_code == 200) {
            $this->contact = json_decode($response);
            return true;
        }
        return false;
    }

    function hubspot_set_deal_json($deal_property) {
        $this->deal_properties =  array(
            'associations' => array(
                'associatedVids' => array(
                    $this->contact->vid
                )
            ),
            'properties' => $deal_property
        );
    }

    static function hubspot_create_deal_property($dealname, $description, $dealstage, $pipeline, $dealtype) {
        return array(
            array(
                'value' => $dealname,
                'name' => 'dealname'
            ),
            array(
                'value' => $description,
                'name' => 'description'
            ),
            array(
                'value' => $dealstage,
                'name' => 'dealstage'
            ),
            array(
                'value' => $pipeline,
                'name' => 'pipeline'
            ),
            array(
                'value' => $dealtype,
                'name' => 'dealtype'
            ),
        );
    }

    
}

function af2_executeWebhook($url, $zapier_json, $lead_id) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

    $headers = array(
    "Accept: application/json",
    "Content-Type: application/json",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    //$data = json_encode(array("testzeug" => "abc", "testddd"=> "abbb"));
    $data = json_decode(json_encode($zapier_json));

    $finalData = array();

    $finalData['form_id'] = $data->form_id;
    $finalData['lead_id'] = $lead_id;
    $finalData['lead_timestamp'] = get_post_field('post_date', $lead_id );
    $finalData['analytics_data'] = array('query_string' => $data->analyticsData[0]->value, 'url' => $data->analyticsData[1]->value);
    $finalData['all_question_data'] = '';
    foreach($data->questions as $question) {
        $finalData['questions'][$question->frage] = $question->antwort;
        $finalData['all_question_data'] .=$question->frage."\n".$question->antwort."\n\n";
    }
    $finalData['all_contact_form_data'] = '';
    foreach($data->contact_form as $contact_form) {
        $finalData['contact_form'][$contact_form->id] = $contact_form->input;
        $finalData['all_contact_form_data'] .=$contact_form->id."\n".$contact_form->input."\n\n";
    }
    $finalData['hidden_fields'] = $zapier_json['hidden_fields'];

    $finalData = json_encode($finalData);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $finalData);

    $resp = curl_exec($curl);
    curl_close($curl);
}

?>
