<?php
/**
 * Plugin Name:     GravityForms & ReachEdge
 * Description:     Submit forms to ReachEdge for tracking purposes. Gravity Forms and ReachEdge plugins must be enabled and configured for this plugin to work.
 * Author:          ReachLocal
 * Author URI:      https://reachlocal.com
 * Domain Path:     /languages
 * Version:         0.1
 */

function get_field_value($grav_form, $user_entry) {
    $grav_id = $grav_form['id'];
    $label = $grav_form['label'];
    $value = $user_entry[$grav_id];
    return array(
        $label => $value
    );
}

function get_gmaid($tracking_uuid) {
    $uuid = str_replace('-', '', $tracking_uuid);
    $js_ref = substr_replace($uuid, '/', 9, 0);
    $js_ref = substr_replace($js_ref, '/', 6, 0);
    $js_ref = substr_replace($js_ref, '/', 3, 0);
    $request_return_val = wp_remote_get("http://cdn.rlets.com/capture_configs/$js_ref.js", array());

    if (is_wp_error($request_return_val)) {
        return '';
    } else {
        $capture_config = $request_return_val['body'];
        $config_json = substr($capture_config, strpos($capture_config, '{'));
        $config = json_decode($config_json);
        $gmaid = $config->globalMasterAdvertiserId;
        update_option('reachlocal_gmaid', $gmaid);
        return $gmaid;
    }
}

function post_to_third_party($entry, $form) {
    $tracking_id = get_option('reachlocal_tracking_code_id') ? get_option('reachlocal_tracking_code_id') : '';
    $gmaid = get_option('reachlocal_gmaid') ? get_option('reachlocal_gmaid') : get_gmaid($tracking_id);

    if (!empty($tracking_id) && !empty($gmaid)) {
        $post_data = [];
        foreach ($form['fields'] as $field) {
            if (!empty($field['inputs'])) {
                foreach ($field['inputs'] as $input) {
                    $input_pair = get_field_value($input, $entry);
                    $post_data = array_merge($post_data, $input_pair);
                }
            } else {
                $form_pair = get_field_value($field, $entry);
                $post_data = array_merge($post_data, $form_pair);
            }
        }

        $submission_data = array(
            'fname' => get_page_link(),
            'referrer' => wp_get_referer(),
            'formUri' => get_page_link(),
            'postbody' => http_build_query($post_data),
            'version' => '462a194b5c38bf66039366f35203e21ef9555373',
            "global_master_advertiser_id" => "USA_238250",
            'capture_version' => '462a194b5c38bf66039366f35203e21ef9555373',
            'hidden_fields' => 'gform_ajax%2Cis_submit_1%2Cgform_submit%2Cgform_unique_id%2Cstate_1%2Cgform_target_page_number_1%2Cgform_source_page_number_1%2Cgform_field_values',
            "page_name" => get_the_title(),
            'rl_eid' => 'trackPost-' . substr(uniqid(), 0, 7),
            "referrer_type" => "DIRECT",
        );
        $json_body = json_encode($submission_data, JSON_UNESCAPED_SLASHES);
        $post_url = 'https://' . $tracking_id . '.rlets.com/api/v1/posts';
        $return_value = wp_remote_post($post_url, array(
                'method' => 'POST',
                'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
                'body' => $json_body
            )
        );

        if (is_wp_error($return_value)) {
//            print_r($return_value);
        }
    }
}

add_action('gform_after_submission', 'post_to_third_party', 10, 2);