<?php

GLOBAL $wpdb;
GLOBAL $ftm_geo_target_plugin_path;
GLOBAL $groupData;
GLOBAL $groupCountries;
GLOBAL $countries;
GLOBAL $groupRegions;
GLOBAL $active_themes;
GLOBAL $groupSites;
GLOBAL $regions;
GLOBAL $sites;

$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
$groupID = null;
$groupCountries = null;
$groupRegions = null;
$groupSites = null;
$groupData = null;
$countries = null;
$active_themes = null;
$regions = null;
$sites = null;

// 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;

//ON UPDATE
if ( isset($_POST["groupid"]) ){

    $groupID = $_POST["groupid"];

    $gactive = false;
    if($_POST["gactive"] === "on"){
        $gactive = true;
    }


    $update = $wpdb->update($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 ('GroupId' =>  $groupID),
        array(
            '%s',
            '%s',
            '%s',
            '%d',
            '%d',
            '%d'
        )
    );


    if($update !== false){
        //Delete previous countries, regions and sites to add the current ones and maintain the order of the sites
        ftm_geo_target_deleteGroupCountries($groupID);
        ftm_geo_target_deleteGroupRegions($groupID);
        ftm_geo_target_deleteGroupSites($groupID);

        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'
                    )
                );
            }
        }

        // Clean sites in children
        $children = ftm_geo_target_getGroupChildren($groupID);
        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'
                    )
                );
            }

            if (is_array($children)) {
                // Fill up the sites in children
                foreach ($children as $child) {
                    ftm_geo_target_deleteGroupSites($child->GroupId);
                    foreach ($arr_sites as $site){
                        $count++;
                        $insert = $wpdb->insert($wpdb->prefix . "ftm_geo_target_sites_group",
                            array(
                                'GroupId'  => ($child->GroupId),
                                'SiteId'  => ($site),
                                'SiteOrder'  => ($count)
                            ),
                            array(
                                '%d',
                                '%d',
                                '%d'
                            )
                        );
                    }
                }
            }
        }
        $groupData = ftm_geo_target_getGroupById($groupID);
        do_action("ftm_geo_target_update_group", $groupData);

        $result = true;
    }
    else
    {
        $result = false;
    }
}


//ON LOAD
if(isset($_POST["gedit"])){
    $groupID = $_POST["gedit"];
}
else
{
    if ( isset($_POST["groupid"]) ) {
        $groupID = $_POST["groupid"];
    }
    else
    {
        echo "<script>window.location = '/wp-admin/admin.php?page=ftm-geo-target-site-groups';</script>";
    }
}


if($groupID != null){
    load_general_data($groupID);
}

function load_general_data($groupID){
    GLOBAL $groupData;
    GLOBAL $groupCountries;
    GLOBAL $groupRegions;
    GLOBAL $groupSites;
    GLOBAL $countries;
    GLOBAL $active_themes;
    GLOBAL $regions;
    GLOBAL $sites;

    $groupData = ftm_geo_target_getGroupById($groupID);
    $groupCountries = ftm_geo_target_getGroupCountries($groupID);
    $groupRegions = ftm_geo_target_getGroupRegions($groupID);
    $groupSites = ftm_geo_target_getGroupSites($groupID);
    $countries = ftm_geo_target_getCountries();
    $active_themes = ftm_geo_target_themes(true, 'target');
    $regions = ftm_geo_target_getRegions();
    $sites = ftm_geo_target_currentSites();
}
$groups  = ftm_geo_target_currentGroups();
$fields  = ftm_geo_target_getCurrentFields();

?>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function (){
        let availableSites = [
            <?php foreach($groups as $group): ?><?php echo '{ label: "'.$group->GroupName.'", value: "'.$group->GroupId.'"},' ?><?php endforeach; ?>
        ];

        let sites = [<?php foreach($groups as $group) : echo '"' .$group->GroupName . '",'; endforeach; ?>];

        let dropdown = document.querySelector('#gparent');

        const autoCompleteJS = new autoComplete({
            // selector: '#gparentsearch',
            placeHolder: "Search...",
            data: {
                src: sites
            },
            resultItem: {
                highlight: {
                    render: true
                }
            }
        });

        document.querySelector("#autoComplete").addEventListener("selection", function (event) {
            const selection = event.detail.selection.value;

            // Set the search value to the one selected by user
            this.value = selection;

            // Set DropDown value to the one selected by user
            const item = availableSites.find(item => item.label === selection);
            dropdown.value = item.value;

        });
    }, false);
</script>

<div class="modal fade" id="delete_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="btn btn-secondary button" class="close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Delete Confirmation</h4>
            </div>
            <div class="modal-body">
                <form id="delete_group_form" name="delete_group_form" action="/wp-admin/admin.php?page=ftm-geo-target-site-groups"  method="post">
                    <fieldset>
                        <div class="form-group">
                            <h4>Are you sure you want to delete this group?</h4>
                        </div>
                        <br>
                        <div class="form-group">
                            <p>By deleting this group, you will also delete it's geo targeting rules and settings. You could also deactivate it if not 100% sure you want to re-enter the data later on.</p>
                        </div>
                        <!-- Allow form submission with keyboard without duplicating the dialog button -->
                        <input type="hidden" name="group_delete_id" id="group_delete_id">
                        <input type="submit" id="diag_form_submit" tabindex="-1" style="position:absolute; top:-1000px">
                    </fieldset>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
                <button type="submit" form="delete_group_form" class="btn btn-primary">Delete Group</button>
            </div>
        </div>
    </div>
</div>


<div class="wrap ftm_geo_target">

    <div id="icon-options-general" class="icon32"></div>
    <h1><?php esc_attr_e( 'Edit 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 updated. Check out the <a href='/wp-admin/admin.php?page=ftm-geo-target-groups/'>groups list</a> or <a href='/wp-admin/admin.php?page=ftm-geo-target-group-add'>add a new one</a>.", $sucess_alert);
                    }elseif ($result === false){
                        echo str_replace("{MESSAGE}","<strong>Oops!</strong> The group wasn't updated. Plase contact support", $error_alert);
                    }
                    ?>

                    <form id="edit_group_form" method="post" action="">
                        <input type="hidden" id="groupid" name="groupid" value="<?php echo $groupID; ?>">

                        <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" value="<?php echo $groupData[0]->GroupName; ?>"/></div>
                                <hr>
                                <div>Description:&nbsp;<input type="text" class="ftm_geo_target_big_input" name="gdesc" size="100" value="<?php echo $groupData[0]->GroupDescription; ?>"/></div>
                                <hr>
                                <div>Active:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" <?php if( $groupData[0]->GroupActive == "1"){ print 'checked="checked"';}?> name="gactive" size="60"/></div>
                                <hr>
                                <div>Parent:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
                                            id="autoComplete">
                                    <select name="gparent" id="gparent">
                                        <option value=""><?php echo _e('None') ?></option>
                                        <?php foreach($groups as $available_group): ?>
                                            <option value="<?php echo $available_group->GroupId ?>" <?php if($groupData[0]->ParentGroupId == $available_group->GroupId): ?>selected<?php endif;?>
                                            ><?php echo $available_group->GroupName ?></option>
                                        <?php endforeach; ?>
                                    </select></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 if($groupData[0]->ParentDependentField == $field->optionid): ?>checked<?php endif;?>
                                            /> <?php echo $field->fieldname ?> <br/>
                                        <?php endforeach; ?>
                                    </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){
                                            $selected = "";
                                            if( $groupData[0]->GroupThemeId ===  $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 . $groupData[0]->ThemeName; ?>/preview.png" />
                                </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" data-placeholder="Choose a Country..." class="chosen-select">
                                        <option value=""></option>
                                        <?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">
                                    <?php
                                    if($groupCountries) {
                                        $countries_tmp = array();
                                        $cont = 0;
                                        foreach ($groupCountries as $country) {
                                            $countries_tmp[$cont] = $country->iso_3166_2;
                                            $cont++;
                                            echo '<div class="sitem" data-text="' . $country->iso_3166_2 . '"><span><img src="'. plugins_url() .'/ftm-geo-target/flags/'. $country->iso_3166_2 .'.png" />' . $country->name . '</span><div class="btn btn-danger btn-lg" onclick="remove_sitem_output(jQuery(this),' . 'allowed_countries_list' . ');"><span class="glyphicon glyphicon-trash"></span></div></div>';
                                        }
                                    }
                                    ?>
                                </div>
                                <input type="hidden" name="allowed_countries_list" value="<?php if($groupCountries) { echo implode(',',$countries_tmp);}?>" 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">
                                    <?php
                                    if($groupRegions) {
                                        $regions_tmp = array();
                                        $cont = 0;
                                        foreach ($groupRegions as $region) {
                                            $regions_tmp[$cont] = $region->regionid;
                                            $cont++;
                                            echo '<div class="sitem" data-text="' . $region->regionid . '"><span>' . $region->regionname . '</span><div class="btn btn-danger btn-lg" onclick="remove_sitem_output(jQuery(this),' . 'allowed_regions_list' . ');"><span class="glyphicon glyphicon-trash"></span></div></div>';
                                        }
                                    }
                                    ?>
                                </div>
                                <input type="hidden" name="allowed_regions_list" value="<?php if($groupRegions) { echo implode(',',$regions_tmp);}?>" 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">
                                    <?php
                                    if($groupSites) {
                                        $sites_tmp = array();
                                        $cont = 0;
                                        foreach ($groupSites as $site) {
                                            $sites_tmp[$cont] = $site->siteid;
                                            $cont++;
                                            echo '<div class="sitem" data-text="' . $site->siteid . '"><span>' . $site->name . ' <em>'.$site->site_description.'</em></span><div class="btn btn-danger btn-lg" onclick="remove_sitem_output(jQuery(this),' . 'sites_ordered_list' . ');"><span class="glyphicon glyphicon-trash"></span></div></div>';
                                        }
                                    }
                                    ?>
                                </div>
                                <input type="hidden" name="sites_ordered_list" value="<?php if($groupSites) { echo implode(',',$sites_tmp);}?>" id="sites_ordered_list" />
                            </div>
                        </div>
                        <!-- .postbox -->
                    </form>
                    <script type="text/javascript">
                        jQuery(document).ready(function ($) {
                            $.validator.addMethod( "alphanumeric", function( value, element ) {
                                return this.optional( element ) || /^[a-zA-Z0-9_ ]+$/i.test( value );
                            }, "Alphanumeric values only please" );

                            if ($.validator) {
                                $("#edit_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 = "edit";
            require_once $ftm_geo_target_plugin_path . '/includes/sidebar-groups-add.php'
            ?>

        </div>

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

    <!-- #poststuff -->

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