<?php
global $wpdb;

$set_id = false;
$is_auto_active = false;
$paths = '';
$auto_ctas_ids = [];
$auto_groups_ids = [];

if ($_REQUEST['cta_set_id']) {
    $set_id = intval($_REQUEST['cta_set_id']);
    $cta_set = ftm_geo_target_getCtaSetById($set_id);
    if ($cta_set) {
        $is_auto_active = $cta_set->CtaActive;
        $paths = $cta_set->Paths;
        $auto_ctas_ids = explode(',', $cta_set->CtasIds);
        $auto_groups_ids = $cta_set->SiteGroupIds?explode(',', $cta_set->SiteGroupIds):[];
    }
}

if (isset($_POST['save'])) {
    $is_auto_active = ($_POST['is_active'] ?? 'false') !== 'false';
    $paths = $_POST['paths'] ?? '';
    $auto_ctas_ids = explode(',', $_POST['ctas_ordered_list']??'');
    $auto_groups_ids = explode(',', $_POST['groups_ordered_list']??'');
    $theme_id = $_POST['ddl_themes']??null;

    if ($set_id) {
        $wpdb->update($wpdb->prefix . 'ftm_geo_auto_ctas', [
            'CtaActive' => $is_auto_active?'1':'0',
            'Paths' => $paths,
            'CtasIds' => implode(',', $auto_ctas_ids),
            'SiteGroupIds' => implode(',', $auto_groups_ids),
            'CtaThemeId' => $theme_id,
        ], ['CtaSetId' => $set_id]);
    } else {
        $set_id = $wpdb->insert($wpdb->prefix . 'ftm_geo_auto_ctas', [
            'CtaActive' => $is_auto_active?'1':'0',
            'Paths' => $paths,
            'CtasIds' => implode(',', $auto_ctas_ids),
            'SiteGroupIds' => implode(',', $auto_groups_ids),
            'CtaThemeId' => $theme_id,
        ]);
        $cta_set = ftm_geo_target_getCtaSetById($set_id);
    }
}


$ctas = ftm_geo_target_currentCtas();
$groups  = ftm_geo_target_currentGroups();
//$auto_ctas = ftm_geo_target_currentCtasAuto();
$auto_ctas = [];
foreach($auto_ctas_ids as $auto_cta_id) {
    $auto_ctas[] = ftm_geo_target_getCtaById($auto_cta_id);
}
$auto_groups = [];
foreach($auto_groups_ids as $auto_group_id) {
    $group_info = ftm_geo_target_getGroupById($auto_group_id);
    if (count($group_info) > 0) {
        $auto_groups[] = $group_info[0];
    }
}
$active_themes = ftm_geo_target_themes(true, 'cta');
$folder_in_template = "/geo-cta-themes/";
$template_path = get_template_directory_uri();
$in_template_themes = $template_path . $folder_in_template;
?>
<div class="wrap ftm_geo_target">

    <div id="icon-options-general" class="icon32"></div>
    <h1><?php esc_attr_e( 'Auto Include CTA', 'wp_admin_style' ); ?></h1>

    <div id="poststuff">

        <div id="post-body" class="metabox-holder columns-2">

            <!-- main content -->
            <div id="post-body-content">

                <div class="ftm_geo_target">

                    <form id="auto_cta_form" method="post" action="">
                        <?php if ($set_id): ?>
                        <input type="hidden" name="cta_set_id" value="<?php echo $set_id ?>">
                        <?php endif; ?>
                        <div class="postbox">
                            <h2 class="hndle"><span><b>Auto show the CTA in the site </b></span></h2>
                            <div class="inside">
                                <div>Active:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" <?php if( $is_auto_active ){ print 'checked="checked"';}?> name="is_active" id="is_active" value="1" /></div>
                                <hr>
                                <div>Paths:&nbsp;<textarea class="ftm_geo_target_big_input" cols="50" rows="5" name="paths" ><?php echo $paths; ?></textarea></div>
                                <br/>
                                Enter a path for each line where you want the CTA to show in. Or enter just an asterisk "*" to show it in every page.<br />
                                If you need to match only a parent path, but not the sub paths use "/path/?$". <br />
                                If you need to match the sub paths, but not the parent path use "/path/.+"
                            </div>
                        </div>

                        <div class="postbox">
                            <h2 class="hndle"><span><b><?php esc_attr_e( 'Theme (Optional) ', 'wp_admin_style' ); ?></b></span>Select the display theme.</h2>
                            <div class="inside">
                                <div>
                                    Theme:&nbsp;&nbsp;
                                    <select name="ddl_themes" id="ddl_themes" title="Themes" onchange="update_theme_preview('<?php echo plugins_url(); ?>','ddl_themes','theme_preview');">
                                        <option>----</option>
                                        <?php
                                        foreach ($active_themes as $theme){
                                            $selected = "";
                                            if( isset($cta_set) && $cta_set->CtaThemeId ===  $theme->ThemeId){
                                                $selected = 'selected';
                                            }
                                            echo ("<option value='". $theme->ThemeId ."' ". $selected ." >" . $theme->ThemeName . "</option>");
                                        }
                                        ?>
                                    </select>
                                    <img id="theme_preview_new" src="<?php echo $in_template_themes . (isset($cta_set)?$cta_set->ThemeName:'-'); ?>/preview.png" />
                                </div>
                            </div>
                        </div>

                        <div class="postbox">
                            <h2 class="hndle"><span><b>Add the CTAs you want to be considered and in which order</b></span>.</h2>
                            <div class="inside">
                                <div>
                                    CTA:
                                    <select name="ddl_sites" id="ddl_sites" title="Regions">
                                        <?php
                                        foreach ($ctas as $cta){
                                            echo ("<option value='". $cta->CtaId ."'>" . $cta->CtaName . (strlen($cta->CtaDescription)?' [' . $cta->CtaDescription.']':'') . "</option>");
                                        }
                                        ?>
                                    </select>
                                    <input class="btn btn-primary" onclick="add_sortable_item_list('ctas_ordered',jQuery('#ddl_sites').val(),jQuery('#ddl_sites option:selected').text().replace(/\[/,'<em>').replace(/\]/,'</em>'),'ctas_ordered_list');" type="button" name="edits" value="<?php esc_attr_e( 'Add CTA', 'wp_admin_style' ); ?>">
                                </div>
                                <hr>
                                <div id="ctas_ordered" class="sortable_list">
                                    <?php
                                    if(!empty($auto_ctas)) {
                                        $sites_tmp = array();
                                        $cont = 0;
                                        foreach ($auto_ctas as $auto_cta) {
                                            $sites_tmp[$cont] = $auto_cta->CtaId;
                                            $cont++;
                                            echo '<div class="sitem" data-text="' . $auto_cta->CtaId . '"><span>' . $auto_cta->CtaName . ' <em>'.$auto_cta->CtaDescription.'</em></span><div class="btn btn-danger btn-lg" onclick="remove_sitem_output(jQuery(this),' . 'ctas_ordered_list' . ');"><span class="glyphicon glyphicon-trash"></span></div></div>';
                                        }
                                    }
                                    ?>
                                </div>
                                <br />
                                Enter and sort the list of CTAs that you want to be considered when auto adding or using the auto shortcode.
                                <input type="hidden" name="ctas_ordered_list" value="<?php if($auto_ctas) { echo implode(',',$sites_tmp);}?>" id="ctas_ordered_list" />
                            </div>
                        </div>

                        <div class="postbox">
                            <h2 class="hndle"><span><b>Add existing site groups you want to be considered and in which order</b></span>.</h2>
                            <div class="inside">
                                <div>
                                    Site Group:
                                    <select name="ddl_groups" id="ddl_groups" title="Groups">
                                        <?php
                                        foreach ($groups as $group){
                                            echo ("<option value='". $group->GroupId ."'>" . $group->GroupName . (strlen($group->GroupDescription)?' [' . $group->GroupDescription.']':'') . "</option>");
                                        }
                                        ?>
                                    </select>
                                    <input class="btn btn-primary" onclick="add_sortable_item_list('groups_ordered',jQuery('#ddl_groups').val(),jQuery('#ddl_groups option:selected').text().replace(/\[/,'<em>').replace(/\]/,'</em>'),'groups_ordered_list');" type="button" name="edits" value="<?php esc_attr_e( 'Add Group', 'wp_admin_style' ); ?>">
                                </div>
                                <hr>
                                <div id="groups_ordered" class="sortable_list">
                                    <?php
                                    $sites_tmp = array();
                                    if(!empty($auto_groups)) {
                                        $cont = 0;
                                        foreach ($auto_groups as $auto_group) {
                                            $sites_tmp[$cont] = $auto_group->GroupId;
                                            $cont++;
                                            echo '<div class="sitem" data-text="' . $auto_group->GroupId . '"><span>' . $auto_group->GroupName . ' <em>'.$auto_group->GroupDescription.'</em></span><div class="btn btn-danger btn-lg" onclick="remove_sitem_output(jQuery(this),' . 'groups_ordered_list' . ');"><span class="glyphicon glyphicon-trash"></span></div></div>';
                                        }
                                    }
                                    ?>
                                </div>
                                <br />
                                Enter and sort the list of Site Groups that you want to be considered when auto adding or using the auto shortcode.
                                <input type="hidden" name="groups_ordered_list" value="<?php if($auto_groups) { echo implode(',',$sites_tmp);}?>" id="groups_ordered_list" />
                            </div>
                        </div>


                        <div class="postbox">
                            <div class="inside">
                                <div>
                                    <input class="btn btn-primary" type="submit" name="save" value="<?php esc_attr_e( 'Save', 'wp_admin_style' ); ?>">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
