<?php

require_once AF2_MISC_FUNCTIONS_PATH;
require_once AF2_ADMIN_HELPER_PATH;

function af2_backend_zap_forms()
{
    if( get_option( 'af2_license_stat' ) != 'Die Domain ist aktiviert!' )
    {
        echo 'Domain not activated';
        die();
    }
    if( !isset( $_GET['key'] )
    || !isset( $_GET['domain'] ) || !isset( $_GET['password'] ) || !isset( $_GET['api_password'] ) )
    {
        echo 'Parameters missing';
        die();
    }

    $key = $_GET['key'];
    $domain = $_GET['domain'];
    $password = $_GET['password'];
    $api_password = $_GET['api_password'];

    do_auth( $api_password, $password, $key, $domain );

    return get_zap_forms_data();
}


function af2_backend_zap_requests()
{
    if( get_option( 'af2_license_stat' ) != 'Die Domain ist aktiviert!' )
    {
        echo 'Domain not activated';
        die();
    }
    if( !isset( $_GET['key'] )
    || !isset( $_GET['domain'] ) || !isset( $_GET['password'] ) || !isset( $_GET['api_password'] ) || !isset( $_GET['form_id'] ) )
    {
        echo 'Parameters missing';
        die();
    }

    $key = $_GET['key'];
    $domain = $_GET['domain'];
    $password = $_GET['password'];
    $api_password = $_GET['api_password'];
    $form_id = $_GET['form_id'];

    do_auth( $api_password, $password, $key, $domain );

    return get_zap_requests_data( $form_id );
}




function get_zap_requests_data( $form_id ) {
    $slug = 'af2_request';

    require_once AF2_MISC_FUNCTIONS_PATH;
    require_once AF2_ADMIN_HELPER_PATH;
    $AdminHelper = new Af2AdminHelper();
    $posts = $AdminHelper->af2_get_posts($slug, array('orderby' => 'post_date'), 'DESC');

    /*
    // Get all requests
    $posts = get_posts([
        'post_type' => $slug,
        'post_status' => 'privat',
        'numberposts' => -1,
        'orderby' => 'post_date',
        'order'    => 'DESC'
    ]);*/

    $requests = [];

    // Save all posts with the right form_id
    foreach( $posts as $post )
    {
        //$post_data = get_post_field( 'post_content',  );
        $content = af2_get_post_content($post);

        $content = json_decode(json_encode($content));

        /*if($content == null) {
            $parsed_content = str_replace('\\\\"', '\\"', $post_data);
            $parsed_content = str_replace("\\'", "", $parsed_content);
            $content = json_decode( $parsed_content );
        }*/

        if( isset($content->form_id) && $content->form_id == $form_id && sizeof($requests) <= 350 )
        {
            array_push( $requests, $post );
        }
    }


    // The output data
    $dat = [];

    // Iterate through
    foreach( $requests as $request )
    {
        $fragen = [];

        // Making the copied Element with the Formular ID
        $id = get_post_field('ID', $request );
		
		//$post_data = get_post_field( 'post_content', $request );
        $req = af2_get_post_content($request);

        $req = json_decode(json_encode($req));
		

        /*if($req == null) {
            $parsed_content = str_replace('\\\\"', '\\"', $post_data);
            $parsed_content = str_replace("\\'", "", $parsed_content);
            $req = json_decode( $parsed_content );
        }*/

        $pos = json_decode( '{"id":"'.$id.'", "request":""}' );
        $pos->request = $req;

        // Setting the output JSON and initializing id
        $new_json = json_decode('{}');
        $new_json->id = $pos->id;

        // All Question Data gets done
        $new_json->all_question_data = '';
        
        foreach( $pos->request->questions as $question )
        {
            // Getting Frage and Antwort
            $frage = $question->frage;
            $antwort = $question->antwort;

            // Doppelungen vermeiden!!!
            while( in_array( $frage, $fragen ) )
            {
                $frage .= '_';
            }

            // For Multiselects
            if( is_array( $antwort ) )
            {
                $str = '';
                $i = 0;
                foreach( $antwort as $part )
                {
                    if( $i > 0 )
                    {
                        $str .= ';';
                    }
                    $str .= $part;
                    $i++;
                }

                $antwort = $str;
            }

            // Adding the Question to the array
            array_push( $fragen, $frage );

            // Setting Frage -> Antwort
            $new_json->$frage = $antwort;

            // Adding to AllQuestionsData
            $new_json->all_question_data.=$frage."\n".$antwort."\n\n";
        }

        // All Contactform Data gets done
        $new_json->all_contactform_data = '';

        foreach( $pos->request->contact_form as $form )
        {
            // Getting Frage and Antwort
            $frage = $form->id;
            $antwort = $form->input;

            // Doppelungen vermeiden!!!
            while( in_array( $frage, $fragen ) )
            {
                $frage .= '_';
            }

            // Adding to Array
            array_push( $fragen, $frage );

            // Setting Feld -> Antwort
            $new_json->$frage = $antwort;

            // Adding to AllQuestionsData
            $new_json->all_contactform_data.=$frage."\n".$antwort."\n\n";
        }


        /* TS */

        $timestamp = get_post_field('post_date', $request );
        $strOne = substr( $timestamp, 0, 10 );
        $strTwo = substr( $timestamp, 11, 8 );

        $new_json->lead_timestamp = $strOne . 'T' . $strTwo . 'Z';


        /* TS */

        /* Add missing questions!!! -> AS EMPTY QUESTIONS*/
        $the_form = af2_get_post_content($form_id);

        $the_form = json_decode(json_encode($the_form));

        foreach( $the_form->sections as $section )
        {
            foreach( $section->contents as $content )
            {
                $data = $content->data;
                
                if( is_numeric( $data ) )
                {
                    $data = intval( $data );


                    $step = af2_get_post_content($data);

                    $step = json_decode(json_encode($step));

                    // check if contactform
                    if( isset( $step->show_bottombar) )
                    {
                        // Iterate through the questions
                        foreach( $step->questions as $ques )
                        {
                            $newname = $ques->id;
                            // NUR WENN NOCH NICHT GESETZT
                            if( !isset( $new_json->$newname ) )
                            {
                                $new_json->$newname = 'N/A';
                            }
                        }
                    }
                    else //is question
                    {
                        $newname = $step->name;
                        // NUR WENN NOCH NICHT GESETZT
                        if( !isset( $new_json->$newname ) )
                        {
                            $new_json->$newname = 'N/A';
                        }
                    }
                }
            } 
        }

        
        // Bonus Data - Analytics Data

        foreach($pos->request->analyticsData as $analytics) {
            $str = 'analytics_'.$analytics->id;
            $new_json->$str = $analytics->value;
        }


        $new_json->hidden_fields = $pos->request->hidden_fields;

        array_push( $dat, $new_json );
    }


    return $dat;
}

function get_zap_forms_data() {


    require_once AF2_MISC_FUNCTIONS_PATH;
    require_once AF2_ADMIN_HELPER_PATH;

    $slug = 'af2_formular';

    $posts = get_posts([
        'post_type' => $slug,
        'post_status' => 'privat',
        'numberposts' => -1,
        'order'    => 'ASC'
    ]);

    $forms = '{"array":[';

    $i = 0;
    foreach( $posts as $post )
    {
        $name = '';
        $id = get_post_field('ID', $post );

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

        if( $pos->error != true )
        {
            if( $i > 0 )
            {
                $forms .= ',';
            }
            $name = $pos->name;
            $json = '{"id":"'.$id.'","name":"'.$name.'"}';
            $forms .= $json;

            $i++;
        }
    }

    $forms .= ']}';

    $dat = json_decode( $forms )->array;

    return $dat;
}




/**************/
function do_auth( $api_password, $password, $key, $domain )
{
    $ch = curl_init();
    $headers = array(
        'Accept: text/plain',
        'Content-Type: text/plain',
    );
    curl_setopt($ch, CURLOPT_URL, 'https://licenseserver-anfrageformular.com/key_validation/plugin_validation/plu_interface.php?passkey=1-dj!Activate281ThedaieksMenu192!E&event=checkthedomainevent&password='.$password.'&key='.$key.'&domain='.$domain);
    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);

    if( strpos( $resp, 'ADK2918dSS') === false )
    {
        die();
    }

    if( $api_password !== get_option( 'af2_zapier_pw' ) )
    {
        echo 'Das Zapier API Passwort ist falsch! Bitte kontaktiere den Support!';
        die();
    }
    
    if( $key !== get_option( 'af2_license_key' ) )
    {
        echo 'Der Lizenzschlüssel ist ungültig! Bitte kontaktiere den Support!';
        die();
    }
    $urlparts = parse_url(home_url());
    $host = $urlparts['host'];
    if( $domain !== $host )
    {
        if( 'www.'.$domain !== $host && strpos( $domain, 'www.' ) === false )
        {
            echo 'Die Domain ist ungültig! Bitte kontaktiere den Support!';
            die();
        }
    }
}

add_action('rest_api_init', function() {
    register_rest_route('af2/v1', 'requests', [
        'methods' => 'GET',
        'callback' => 'af2_backend_zap_requests',
        'permission_callback' => '__return_true'
    ]);
    register_rest_route('af2/v1', 'forms', [
        'methods' => 'GET',
        'callback' => 'af2_backend_zap_forms',
        'permission_callback' => '__return_true'
    ]);
});