<?php

GLOBAL $wpdb;
GLOBAL $ftm_geo_target_plugin_path;

$sucess_alert = '<div class="alert alert-success alert-dismissible show" role="alert">{MESSAGE}<button type="button" class="btn btn-secondary close" data-bs-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
$error_alert = '<div class="alert alert-danger alert-dismissible show" role="alert">{MESSAGE}<button type="button" class="btn btn-secondary close" data-bs-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
$result = "";

//NO POSTBACK, GENERAL LOAD
$countries  = ftm_geo_target_getCountries();
$regions = ftm_geo_target_getRegions();
$sites  = ftm_geo_target_currentSites();
$active_themes = ftm_geo_target_themes(true, 'all');
// Theme folder in the current theme folder
$folder_in_template = "/geo-target-themes/";
$template_path = get_template_directory_uri();
$in_template_themes = $template_path . $folder_in_template;

$groups  = ftm_geo_target_currentGroups();
$fields  = ftm_geo_target_getCurrentFields();


//GENERAL
if ( isset($_POST["gname"]) ){

    $gactive = false;
    if($_POST["gactive"] === "on"){
        $gactive = true;
    }
    $insert = $wpdb->insert($wpdb->prefix . "ftm_geo_target_groups",
        array(
            'GroupName'             => ($_POST["gname"]),
            'GroupDescription'      => ($_POST["gdesc"]),
            'GroupActive'           => ($gactive),
            'GroupThemeId'          => ($_POST["ddl_themes"]),
            'ParentGroupId'         => (isset($_POST['gparent'])?$_POST['gparent']:null),
            'ParentDependentField'  => (isset($_POST['gparentfield'])?$_POST['gparentfield']:null)
        ),
        array(
            '%s',
            '%s',
            '%s',
            '%d',
            '%d',
            '%d'
        )
    );


    if($wpdb->insert_id != false) {
        if ($wpdb->insert_id > 0) {
            $groupID = $wpdb->insert_id;

            if(!empty($_POST["allowed_countries_list"])){
                $arr_countries = explode(",",$_POST["allowed_countries_list"]);
                foreach ($arr_countries as $country){
                    $insert = $wpdb->insert($wpdb->prefix . "ftm_geo_target_countries_group",
                        array(
                            'GroupId'  => ($groupID),
                            'CountryCode'  => ($country)
                        ),
                        array(
                            '%d',
                            '%s'
                        )
                    );
                }
            }


            if(!empty($_POST["allowed_regions_list"])){
                $arr_regions = explode(",",$_POST["allowed_regions_list"]);
                foreach ($arr_regions as $region){
                    $insert = $wpdb->insert($wpdb->prefix . "ftm_geo_target_regions_group",
                        array(
                            'GroupId'  => ($groupID),
                            'RegionId'  => ($region)
                        ),
                        array(
                            '%d',
                            '%d'
                        )
                    );
                }
            }

            if(!empty($_POST["sites_ordered_list"])){
                $arr_sites = explode(",",$_POST["sites_ordered_list"]);
                $count = 0;
                foreach ($arr_sites as $site){
                    $count++;
                    $insert = $wpdb->insert($wpdb->prefix . "ftm_geo_target_sites_group",
                        array(
                            'GroupId'  => ($groupID),
                            'SiteId'  => ($site),
                            'SiteOrder'  => ($count)
                        ),
                        array(
                            '%d',
                            '%d',
                            '%d'
                        )
                    );
                }
            }
            $groupData = ftm_geo_target_getGroupById($groupID);
            do_action("ftm_geo_target_add_group", $groupData);
            $result = true;
        }
    }


    //SET INSERT STATUS RESULT MESSAGES
}

?>
<div class="wrap ftm_geo_target">

    <div id="icon-options-general" class="icon32"></div>
    <h1><?php esc_attr_e( 'Add New Group', '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">

                    <?php
                        if($result === true){
                            echo str_replace("{MESSAGE}","<strong>Cool!</strong> The group has been inserted. Check out the <a href='" . FTM_WP_INSTALL_PREFIX . "/wp-admin/admin.php?page=ftm-geo-target-groups/'>groups list</a> or <a href='". FTM_WP_INSTALL_PREFIX ."/wp-admin/admin.php?page=ftm-geo-target-group-add'>add another one</a>.", $sucess_alert);
                        }elseif ($result === false){
                            echo str_replace("{MESSAGE}","<strong>Oops!</strong> The group wasn't inserted. Plase contact support", $error_alert);
                        }
                    ?>

                    <form id="add_group_form" method="post" action="">

                        <div class="postbox">
                            <h2 class="hndle"><span><b><?php esc_attr_e( 'Step 1. ', 'wp_admin_style' ); ?></b></span>General group details </h2>
                            <div class="inside">
                                    <div>Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" class="ftm_geo_target_big_input" name="gname" id="gname" size="60"/></div>
                                    <hr>
                                    <div>Description:&nbsp;<input type="text" class="ftm_geo_target_big_input" name="gdesc" size="100"/></div>
                                    <hr>
                                    <div>Active:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" checked="checked" name="gactive" size="60"/></div>
                                    <hr>
                                    <div>Parent:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select name="gparent">
                                            <option value=""><?php echo _e('None') ?></option>
                                            <?php foreach($groups as $available_group): ?>
                                            <option value="<?php echo $available_group->GroupId ?>"><?php echo $available_group->GroupName ?></option>
                                            <?php endforeach; ?>
                                        </select></div>
                            </div>
                        </div>
                        <!-- .postbox -->

                        <div class="postbox">
                            <h2 class="hndle"><span><b><?php esc_attr_e( 'Step 2. ', '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');">
                                            <?php
                                            foreach ($active_themes as $theme){
                                                echo ("<option value='". $theme->ThemeId ."'>" . $theme->ThemeName . "</option>");
                                            }
                                            ?>
                                        </select>
                                        <img id="theme_preview_new" src="<?php echo $in_template_themes . $groupData[0]->ThemeName; ?>/preview.png" />
                                    </div>
                                <!--
                                <div>Field to update when parent updates:
                                    <br />
                                    <input type="radio" value="" name="gparentfield" /> <?php echo _e('None') ?> <br/>
                                    <?php foreach($fields as $field): ?>
                                        <input type="radio" name="gparentfield" value="<?php echo $field->optionid ?>"
                                        /> <?php echo $field->fieldname ?> <br/>
                                    <?php endforeach; ?>
                                </div>
                                -->
                            </div>
                        </div>

                        <!-- .postbox -->

                        <div class="postbox">
                            <h2 class="hndle"><span><b><?php esc_attr_e( 'Step 3. ', 'wp_admin_style' ); ?></b></span>Select allowed countries</h2>
                            <div class="inside">
                                    <div>
                                        Country:&nbsp;
                                        <select name="ddl_countries" id="ddl_countries" title="Countries">
                                        <?php
                                        foreach ($countries as $country){
                                            echo ("<option value='". $country->iso_3166_2 ."' data-class='flag' data-style='background-image:url(". plugins_url() ."/ftm-geo-target/flags/". $country->iso_3166_2 .".png);' >" . $country->name . "</option>");
                                        }
                                        ?>
                                        </select>
                                        <input class="btn btn-primary" onclick="add_sortable_item_list_wflag('allowed_countries',jQuery('#ddl_countries').val(),jQuery('#ddl_countries option:selected').text(),'allowed_countries_list');" type="button" name="add_coutry" id="add_coutry" value="<?php esc_attr_e( 'Add', 'wp_admin_style' ); ?>">
                                    </div>
                                    <hr>
                                    <div id="allowed_countries" class="sortable_list">

                                    </div>
                                    <input type="hidden" name="allowed_countries_list" id="allowed_countries_list" />
                            </div>
                        </div>
                        <!-- .postbox -->

                        <div class="postbox">
                            <h2 class="hndle"><span><b><?php esc_attr_e( 'Step 4. ', 'wp_admin_style' ); ?></b></span>Select allowed regions (optional)</h2>
                            <div class="inside">
                                    <div>
                                        Region:&nbsp;&nbsp;
                                        <select name="ddl_regions" id="ddl_regions" title="Regions">
                                            <?php
                                            foreach ($regions as $region){
                                                echo ("<option value='". $region->regionid ."' data-countrycode='". $region->countrycode ."' >" . $region->regionname . "</option>");
                                            }
                                            ?>
                                        </select>
                                        <input class="btn btn-primary" onclick="add_sortable_item_list('allowed_regions',jQuery('#ddl_regions').val(),jQuery('#ddl_regions option:selected').text(),'allowed_regions_list');" type="button" name="edits" value="<?php esc_attr_e( 'Add', 'wp_admin_style' ); ?>">
                                    </div>
                                    <hr>
                                    <div id="allowed_regions" class="sortable_list">

                                    </div>
                                    <input type="hidden" name="allowed_regions_list" id="allowed_regions_list" />
                            </div>
                        </div>
                        <!-- .postbox -->

                        <div class="postbox">
                            <h2 class="hndle"><span><b><?php esc_attr_e( 'Step 5. ', 'wp_admin_style' ); ?></b></span>Add sites to the group, you can drag and drop sites to set the order.</h2>
                            <div class="inside">
                                    <div>
                                        Site:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                        <select name="ddl_sites" id="ddl_sites" title="Regions">
                                            <?php
                                            foreach ($sites as $site){
                                                echo ("<option value='". $site->siteid ."'>" . $site->name . (strlen($site->site_description)?' [' . $site->site_description.']':'') . "</option>");
                                            }
                                            ?>
                                        </select>
                                        <input class="btn btn-primary" onclick="add_sortable_item_list('sites_ordered',jQuery('#ddl_sites').val(),jQuery('#ddl_sites option:selected').text().replace(/\[/,'<em>').replace(/\]/,'</em>'),'sites_ordered_list');" type="button" name="edits" value="<?php esc_attr_e( 'Add', 'wp_admin_style' ); ?>">
                                    </div>
                                    <hr>
                                    <div id="sites_ordered" class="sortable_list">

                                    </div>
                                    <input type="hidden" name="sites_ordered_list" id="sites_ordered_list" />
                            </div>
                        </div>
                        <!-- .postbox -->
                    </form>
                    <script type="text/javascript">
                        jQuery(document).ready(function ($) {
                            if ($.validator) {
                                $.validator.addMethod( "alphanumeric", function( value, element ) {
                                    return this.optional( element ) || /^[a-zA-Z0-9_ ]+$/i.test( value );
                                }, "Alphanumeric values only please" );
                            }

                            $("#add_group_form").validate({
                                debug: true,
                                rules: {
                                    gname: {
                                        required: true,
                                        alphanumeric: true
                                    },
                                    gdesc: "required"
                                },
                                submitHandler: function (form) {
                                    console.log("Submitted!");
                                    form.submit();
                                }
                            });
                        });
                    </script>
                </div>
                <!-- .meta-box-sortables .ui-sortable -->

            </div>
            <!-- post-body-content -->

            <!-- sidebar -->
            <?php
            $sidebar_action = "add";
            require_once $ftm_geo_target_plugin_path . '/includes/sidebar-groups-add.php'
            ?>

        </div>

        <br class="clear">
    </div>

    <!-- #poststuff -->

</div> <!-- .wrap -->
