<?php

//PLUGIN SHORTCODES
function ftm_content_shortcode($atts, $content = null)
{
    $a = shortcode_atts(array(
        'g' => '',
    ), $atts);

    if($a['g'] != ""){
        //GEO TARGET
        $content_selected = ftm_process_shortcode_select_content($a['g'], []);
        ////////////////////////
        if (empty($content_selected)) {
            return '';
        }
        // We render based on the group matched
        $script = ftm_gt_render_content($content_selected?$content_selected->ContentId:null);
        return $script;
    }
    return "";
}

function ftm_gt_shortcode($atts, $content = null){
    $a = array_merge([
        'g' => '',
        'theme' => '',
        'split_percentage' => '',
        'track' => ''], $atts);
    $a['ctas'] = '';
    $a['groups'] = $a['g'];

    return ftm_process_shortcode($a, 'geo_target_post_process', false, 'group');
}

function ftm_cta_shortcode($atts, $content = null){
    $a = array_merge([
        'g' => '',
        's' => '',
        'theme' => '',
        'track' => '',
    ], $atts);
    $a['ctas'] = $a['g'];
    $a['groups'] = $a['s'];

    return ftm_process_shortcode($a, 'geo_cta_post_process', true, 'cta');
}

function ftm_cta_auto_shortcode($atts, $content = null) {
    global $wp;
    $a = array_merge([
        'theme' => '',
        'track' => '',
    ], $atts);

    $is_auto_active = boolval(get_option( 'ftmgt_cta_active', 'false' ));
    if ($is_auto_active) {
        $cta_sets = ftm_geo_target_getCtaSets(true);
        foreach ($cta_sets as $cta_set) {
            $paths = explode("\n", $cta_set->Paths);
            $should_display = '*'===$cta_set->Paths;
            $current_url = $wp->request;

            if (substr($current_url, 1) !== '/') {
                $current_url = '/' . $current_url;
            }
            if (substr($current_url, -1) !== '/') {
                $current_url = $current_url . '/';
            }

            if(($current_url == "/" && in_array("/", array_map('trim',$paths))) || ($current_url == "/" && in_array("/?$", array_map('trim',$paths)))){
                $should_display = true;
            }else{

                foreach ($paths as $path) {
                    if(trim($path) == "/" || trim($path) == "/?$"){continue;}
                    $path = str_replace('/', '\\/', $path);
                    if (preg_match('/' . trim($path) . '/i', $current_url)) {
                        $should_display = true;
                    }
                }
            }
            if ($should_display) {
                $a['ctas'] = $cta_set->CtasIds; // CTAs
                $a['groups'] = $cta_set->SiteGroupIds; // Site Groups
                if (strlen($a['theme']) === 0 && $cta_set->CtaThemeId) {
                    $a['theme'] = $cta_set->ThemeName;
                }
                return ftm_process_shortcode($a, 'geo_cta_post_process', true, 'cta');
            }
        }
    }
}

function ftm_process_shortcode($atts, $post_process_filter, $process_single_site, $type = 'group') {
    $script = '';
    if (!isset($atts['groups']) && !isset($atts['ctas']) && isset($atts['g'])) {
        $atts['groups'] = $atts['g'];
    }
    if($atts['groups'] !== "" || $atts['ctas'] !== "") {
        // find additional parameters
        $params = ftm_gt_extract_parameters_for_template($atts);

        //GEO TARGET
        $group_selected = ftm_process_shortcode_select_content($atts['groups'], $atts['ctas']);

        if (empty($group_selected)) {
            return '';
        }
        $themes = ftm_gt_create_themes_structure($atts);
        $should_track = isset($atts['track']) && ($atts['track'] === '1' || strtolower($atts['track']) === 'yes');
        // We render based on the group matched
        $script = ftm_gt_render_group($group_selected, $themes, $params, $should_track, $process_single_site, $type);
        if (strlen($script)>0) {

            if (stripos($script, '<?php') !== false) {
                //PHP RENDER FILE
                $script = str_replace("<?php", "", $script);
                $script = str_replace("?>", "", $script); // <?php
                try {
                    $script = eval($script);
                } catch(Throwable $e) {
                    error_log( "GEOTARGET:ERROR- Failed to evaluate template: " . $script);
                    error_log($e->getMessage());
                    return '<div>Error processing table!</div><!-- '.$script.' -->';
                }
            }
        }
    }
    $script = apply_filters($post_process_filter, $script, $atts);

    // Clean any placeholder not used
    return preg_replace('/\[[0-9a-zA-Z_ -]+\]/', '', $script);
}

function ftm_process_shortcode_select_content($groups, $ctas)
{
    $ftm_geo_target_plugin_url = WP_PLUGIN_URL . '/ftm-geo-target';
    $ftm_geo_target_plugin_path = WP_PLUGIN_DIR . '/ftm-geo-target';
    $settings = ftm_geo_target_getSettings();

    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }

    list($cc, $rc) = ftm_gt_getGeoCodes("", true);

    if ($settings[0]->DebugStatus === "1" || isset($_GET['debug'])) {
        var_dump($_GET['debug_ip']);
        var_dump($_SERVER['REMOTE_ADDR']);
        var_dump($cc);
        var_dump($rc);
        var_dump($groups);
        var_dump($ctas);
    }

    $groups_list = explode(',', $groups);
    // If no group selected we return empty
    $content_id_selected = ftm_gt_find_match_group($groups_list, $cc, $rc);
    if ($settings[0]->DebugStatus === "1" || isset($_GET['debug'])) {
        var_dump($groups_list);
        var_dump($content_id_selected);
    }
    if ($content_id_selected) {
        $selected = ftm_geo_target_getGroupById($content_id_selected);
        if (is_array($selected) && count($selected) > 0)
        return $selected[0];
    }

    $ctas_list = explode(',', $ctas);
    $content_id_selected = ftm_gt_find_match_group_cta($ctas_list, $cc, $rc);
    //ONLY WHEN DEBUG IS ON
    if ($settings[0]->DebugStatus === "1" || isset($_GET['debug'])) {
        var_dump($ctas_list);
        var_dump($content_id_selected);
    }
    return ftm_geo_target_getCtaById($content_id_selected);;
}

add_shortcode("ftm_gt","ftm_gt_shortcode");
add_shortcode("ftm_cta","ftm_cta_shortcode");
add_shortcode("ftm_cta_auto","ftm_cta_auto_shortcode");
add_shortcode("ftm_cta-auto","ftm_cta_auto_shortcode"); // legacy for initial typo, don't use
add_shortcode("ftm_content","ftm_content_shortcode");
