<?php
/**
 * WPOauth_Admin Class
 * Add admin functionkaity to the backend of WordPress
 */
class WPOAuth_Admin {

    /**
     * WO Options Name
     * @var string
     */
    protected $option_name = 'wo_options';

    /**
     * [_init description]
     * @return [type] [description]
     */
    public static function init() {
        add_action('admin_init', array(new self, 'admin_init'));
        add_action('admin_menu', array(new self, 'add_page'), 1);
    }

    /**
     * [admin_init description]
     * @return [type] [description]
     */
    public function admin_init() {
        register_setting('wo_options', $this->option_name, array($this, 'validate'));

        require_once(dirname(__FILE__). '/admin/page-server-status.php');
    }

    /**
     * [add_page description]
     */
    public function add_page() {
        add_menu_page('InflatableOffice', 'InflatableOffice', 'manage_options', 'wo_settings',array($this,'io_settings_page'), plugin_dir_url( __FILE__ ) . '../images/io_logo.png');

        add_submenu_page( 'wo_settings', 'InflatableOffice Setup', 'Setup', 'manage_options', 'wo_settings', array($this,'io_settings_page'));

        add_submenu_page( 'wo_settings', 'InflatableOffice Pricing', 'Pricing', 'manage_options', 'io_pricing', array($this,'io_pricing_page'));

        add_submenu_page( 'wo_settings', 'InflatableOffice Analytics', 'Analytics', 'manage_options', 'io_analytics', array($this,'io_analytics_page'));

        add_submenu_page( 'wo_settings', 'InflatableOffice Cart Settings', 'Cart Settings', 'manage_options', 'io_cart', array($this,'io_cart_page'));

        add_submenu_page( 'wo_settings', 'InflatableOffice Review Page Settings', 'Reviews', 'manage_options', 'io_reviews', array($this,'io_reviews_page'));

        //add_submenu_page( 'wo_settings', 'OAuth Server', 'OAuth Server', 'manage_options', 'wo_auth_settings#clients', array($this, 'options_do_page' ));

        //add_submenu_page( 'wo_settings', 'Server Status', 'Server Status', 'manage_options', 'wo_server_status', 'wo_server_status_page');

        add_submenu_page( 'wo_settings', 'InflatableOffice Shortcoder', 'Shortcoder', 'manage_options', 'shortcoder', 'sc_admin_page' );
    }

    public function io_settings_page(){

        $options = get_option($this->option_name);
        $this->admin_head();
        $scopes = apply_filters('WO_Scopes', null);
        error_reporting(0);
        add_thickbox();

        $io_updated = false;

        // Insert shortcode
        if (isset($_POST["io_form_main"]) && $_POST["io_form_main"] == '1' && check_admin_referer('io_create_form')){
            $sc_options = get_option('shortcoder_data');
            $sc_name = stripslashes($_POST['sc_name']);
            $_POST["io_pagename"] = stripslashes($_POST['io_pagename']);

            // Updating the DB
            update_option("io_username", $_POST['io_username']);
            update_option("io_excludeforms", $_POST['io_excludeforms']);

            if($_POST['io_multistep']==1){
                update_option("io_multistep", 'on');
            }else{
                update_option("io_multistep", 'off');
            }
            if($_POST['io_makeLeadsOnForms']==1){
                update_option("io_makeLeadsOnForms", 'on');
            }else{
                update_option("io_makeLeadsOnForms", 'off');
            }
            if($_POST['io_hidetimes']==1){
                update_option("io_hidetimes", 'on');
            }else{
                update_option("io_hidetimes", 'off');
            }

            if(isset($_POST['io_checkavail'])){
                update_option("io_checkavail", $_POST['io_checkavail']);
            }
            if($_POST['io_showCategoryLong']==1){
                update_option("io_showCategoryLong", 'on');
            }else{
                update_option("io_showCategoryLong", 'off');
            }
            if($_POST['io_disable_listview']==1){
                update_option("io_disable_listview", 'on');
            }else{
                update_option("io_disable_listview", 'off');
            }

            if($_POST['io_categoryVariantImages']==1){
                update_option("io_categoryVariantImages", 'on');
            }else{
                update_option("io_categoryVariantImages", 'off');
            }

            if($_POST['io_accessoriesSelect']==1){
                update_option("io_accessoriesSelect", 'on');
            }else{
                update_option("io_accessoriesSelect", 'off');
            }

            if($_POST['io_multisiteRedirect']==1){
                update_option("io_multisiteRedirect", 'on');
            }else{
                update_option("io_multisiteRedirect", 'off');
            }

            update_option("io_customer_geolocation", ($_POST['io_customer_geolocation'] == 1) ? 'on' : 'off');

            $seo_link_text = str_replace(array("\r\n", "\r", "\n"), "<br>", $_POST['io_seocitylinktext']);
            $seo_link_text = str_replace('\\\\\\', '\\', $seo_link_text);
            $sc_options = get_option('shortcoder_data');
            $sc_options['io_city_landing_page_links']['content'] = $seo_link_text;
            update_option("shortcoder_data", $sc_options);
            update_option( 'io_seocitylinktext', $seo_link_text );

            $location_id = empty($_POST['io_locationid']) ? 0 : $_POST['io_locationid'];
            update_option("io_locationid", $location_id);
            update_option("io_pagename", $_POST['io_pagename']);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$_POST['io_username'].'&location_id='.$location_id);
            if(strpos(get_site_url(), 'localhost') !== false){
                curl_setopt($ch, CURLOPT_URL, 'http://localhost/io/bugs/wp-plugin/get_pagelist.php');
            }else{
                curl_setopt($ch, CURLOPT_URL, 'https://rental.software/wp-plugin/get_pagelist.php');
            }
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $html = curl_exec($ch);
            update_option("io_pagelist", $html);

            $io_updated = true;

            // Insert Message
            if($io_updated == 'true'){
                echo '<div class="message updated fade"><p>' . __('Updated successfully !', 'io') . '</p></div>';
            }else{
                echo '<div class="message error fade"><p>' . __('Unable to save!', 'io') . '</p></div>';
            }
        }

        $io_username = get_option('io_username');
        $io_excludeforms = get_option('io_excludeforms');


        $io_multistep = get_option('io_multistep')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_hidetimes = get_option('io_hidetimes')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_makeLeadsOnForms = get_option('io_makeLeadsOnForms')=='off' ? '' : 'checked="checked"';//default if not set = on, in shortcode as well
        $io_locationid = get_option('io_locationid');
        $io_pagename = get_option('io_pagename');
        $io_pagelist = get_option('io_pagelist');
        $io_showCategoryLong = get_option('io_showCategoryLong')=='off' ? '' : 'checked="checked"';
        $io_disable_listview = get_option('io_disable_listview')=='on' ? 'checked="checked"' : '';
        $io_categoryVariantImages = get_option('io_categoryVariantImages')=='on' ? 'checked="checked"' : '';
        $io_accessoriesSelect = get_option('io_accessoriesSelect');
        $io_accessoriesSelect_check = '';
        if($io_accessoriesSelect=='on') $io_accessoriesSelect_check = 'checked="checked"';
        if(get_option('io_brand') === "PW"){
            $defualt_io_seocitylinktext = 'Professional service for <span class="io_city_list">%%landing_pages%%</span> and surrounding areas. Please submit a quote or contact us to be sure we service your area.';
        }else {
            $defualt_io_seocitylinktext = 'Professional delivery to <span class="io_city_list">%%landing_pages%%</span> and surrounding areas. Please submit a quote or contact us to be sure we service your area.';
        }
        $io_seocitylinktext = $defualt_io_seocitylinktext;
        if(get_option("io_seocitylinktext") !== false){
            $io_seocitylinktext = get_option("io_seocitylinktext");
        }

        $io_checkavail_off = get_option('io_checkavail')=='off' ? 'checked="checked"' : '';
        $io_checkavail_warn = get_option('io_checkavail')=='warn' ? 'checked="checked"' : '';
        $io_checkavail_hide = get_option('io_checkavail')=='hide' ? 'checked="checked"' : '';

        $io_multisiteRedirect = get_option('io_multisiteRedirect');
        $io_multisiteRedirect_check = '';
        if(is_multisite() && $io_multisiteRedirect=='on') $io_multisiteRedirect_check = 'checked="checked"';

        $io_customer_geolocation = get_option('io_customer_geolocation')=='on' ? 'checked="checked"' : '';


        if(!empty($io_pagelist)){
            $arr = json_decode($io_pagelist);
            if(!in_array($io_pagename,$arr->pagenames)){
                $io_pagename = $arr->pagenames[0];
                update_option("io_pagename", $io_pagename);
            }
        }

        //echo 'io_loc:'.$io_locationid;
        //echo 'io_pn:'.$io_pagename;

        ?>

        <!-- Shortcoder Admin page -->

        <div class="sc_modal">
            <span class="sc_modal_close"></span>
            <div></div>
        </div>

        <div class="wrap">
            <?php sc_admin_buttons('fbrec'); ?>
            <h2>InflatableOffice Integration Setup</h2>


            <div id="content">

                <h3>
                    <b>Step 1</b>: Enter IO Username, click Save, Select Quote Page, click Save.
                </h3>

                <form method="post" id="sc_form">

                    <div class="sc_section">
                        <label for="io_username" class="io_fld_title" title="This is important. The username entered here is the main IO account of that user, not a worker account.">
                            <?php _e( "IO Username:", 'io' ); ?>&nbsp;ⓘ
                        </label>

                        <span class="io_name_wrap">
                            <input type="text" style="width:350px" name="io_username" id="io_username" value="<?php echo isset($io_username) ? $io_username : ''; ?>"
                                   placeholder="Enter your InflatableOffice account username here" class="widefat" required="required" title="Enter your IO Username"/>
                            <div id="io_code"></div>
                        </span>
                    </div>

                    <?php
                    $html = '';
                    if(!empty($io_pagelist))
                    {
                        $arr = json_decode($io_pagelist);
                        if(!empty($arr->locations))
                        {
                            $html .= 'Location: <select name="io_locationid">';
                            foreach($arr->locations as $k=>$v)
                            {
                                $sel = "";
                                if($k==$io_locationid) $sel = 'selected="selected"';
                                $html .= '<option value="'.$k.'" '.$sel.'>'.$v.'</option>';
                            }
                            $html .= '</select><br>';
                        }
                        if(!empty($arr->pagenames))
                        {
                            $html .= '
                                <div title="The default quote page for this website. This can be found in IO -> Settings -> Pages/Templates">
                                    Linked Quote Page: &nbsp;ⓘ
                                    <select name="io_pagename">';
                            foreach($arr->pagenames as $v)
                            {
                                $sel = "";
                                if($v==$io_pagename) $sel = 'selected="selected"';
                                $html .= '<option value="'.$v.'" '.$sel.'>'.$v.'</option>';
                            }
                            $html .= '</select>
                                </div>';
                        }

                    }
                    echo $html;
                    ?>
                    <div class="sc_section">
                        <span class="io_multistep_wrap"><input type="checkbox" name="io_multistep" id="io_multistep" value="1" <?php echo $io_multistep; ?>  class="widefat" /></span>
                        <label for="io_multistep"  class="io_fld_title"><?php _e( "Multi-step checkout", 'io' ); ?></label>
                    </div>

                    <div class="sc_section">
                        <span class="io_hidetimes_wrap"><input type="checkbox" name="io_hidetimes" id="io_hidetimes" value="1" <?php echo $io_hidetimes; ?>  class="widefat" /></span>
                        <label for="io_hidetimes" class="io_fld_title"><?php _e( "Hide times on cart", 'io' ); ?></label>
                    </div>

                    <div class="sc_section">
                        <span class="io_makeLeadsOnForms_wrap"><input type="checkbox" name="io_makeLeadsOnForms" id="io_makeLeadsOnForms" value="1" <?php echo $io_makeLeadsOnForms; ?>  class="widefat" onclick="jQuery('.io_excludeforms_wrap').toggle();" /></span>
                        <label for="io_makeLeadsOnForms" title="Elementor forms will automatically create leads in IO, but you can control which forms shouldn’t create leads in IO (such as an employment form). Enter any forms you would like to exclude here." class="io_fld_title"><?php _e( "Allow forms to make io leads", 'io' ); ?>&nbsp;ⓘ</label>
                        <span class="io_excludeforms_wrap"><br>Exclude forms: <input type="text"  style="width:420px" name="io_excludeforms" id="io_excludeforms" value="<?php echo isset($io_excludeforms) ? $io_excludeforms : ''; ?>" placeholder="Form names to exclude from io lead creation (comma seperator)" class="widefat" /></span>
                    </div>
                    <div class="sc_section">
                        <div>
                            <br>Item Availability Checking:<br>
                        </div>

                        <span class="io_checkavail_wrap"><input type="radio" name="io_checkavail" id="io_checkavail_off" value="off" <?php echo $io_checkavail_off; ?>  class="widefat" /></span>
                        <label for="io_checkavail_off" class="io_fld_title"><?php _e( "Off - all items appear available", 'io' ); ?></label>

                        <br>

                        <span class="io_checkavail_wrap"><input type="radio" name="io_checkavail" id="io_checkavail_warn" value="warn" <?php echo $io_checkavail_warn; ?>  class="widefat" /></span>
                        <label for="io_checkavail_warn" class="io_fld_title"><?php _e( "Show warning if unavailable", 'io' ); ?></label>

                        <br>

                        <span class="io_checkavail_wrap"><input type="radio" name="io_checkavail" id="io_checkavail_hide" value="hide" <?php echo $io_checkavail_hide; ?>  class="widefat" /></span>
                        <label for="io_checkavail_hide" class="io_fld_title"><?php _e( "Hide unavailable items", 'io' ); ?></label>

                        <br>
                    </div>

                    <div class="sc_section">
                        <br>Category Settings:<br>

                        <span class="io_showCategoryLong_wrap">
                            <input type="checkbox" name="io_showCategoryLong" id="io_showCategoryLong" value="1" <?php echo $io_showCategoryLong; ?> class="widefat" />
                        </span>
                        <label>
                            <span title="This will show the long category description from the active categories in IO -> Settings -> Categories." for="io_showCategoryLong" class="io_fld_title">
                                <?php _e( "Show Category Long Description", 'io' ); ?>&nbsp;ⓘ
                            </span>
                        </label>

                        <br>

                        <span class="io_disable_listview_wrap">
                            <input type="checkbox" name="io_disable_listview" id="io_disable_listview" value="1" <?php echo $io_disable_listview; ?> class="widefat" />
                        </span>
                        <label>
                            <span title="This will hide the list view content on category pages (description, details, etc.)" for="io_disable_listview" class="io_fld_title">
                                <?php _e( "Disable List View Content", 'io' ); ?>&nbsp;ⓘ
                            </span>
                        </label>

                        <br>
                    </div>

                    <div class="sc_section">
                        <div>
                            <br>Item Page Settings:<br>
                        </div>

                        <span class="io_accessoriesSelect_wrap"><input type="checkbox" name="io_accessoriesSelect" id="io_accessoriesSelect" value="1" <?php echo $io_accessoriesSelect_check; ?>  class="widefat" /></span>

                        <label for="io_accessoriesSelect" class="io_fld_title">
                            <?php _e( "Show package accessories as dropdown instead of selectable boxes", 'io' ); ?>
                        </label>
                        <br>
                        <span>
                            <input type="checkbox" name="io_categoryVariantImages" id="io_categoryVariantImages" value="1" <?php echo $io_categoryVariantImages; ?> class="widefat" />
                        </span>
                        <label>
                            <span title="This displays extra images that can be previewed on the item pages." for="io_categoryVariantImages" class="io_fld_title">
                                <?php _e( "Show Additional Images on Category Pages", 'io' ); ?>&nbsp;ⓘ
                            </span>
                        </label>
                        <br>
                    </div>
                    <div class="sc_section">
                        <br>

                        <label for="io_seocitylinktext"  class="io_fld_title">
                            <?php _e( "City Landing Page Text:", 'io' ); ?>
                        </label>

                        <br>

                        <span class="io_seocitylinktext_wrap">
                            <textarea name="io_seocitylinktext" id="io_seocitylinktext" cols="100" rows="2">
                                <?php echo ltrim($io_seocitylinktext); ?>
                            </textarea>
                        </span>

                        <br>

                        <button type="button" id="io_seocitylinktext_retore_button">
                            Restore Default
                        </button>

                        <script>
                            jQuery( document ).ready(function()
                            {
                                jQuery("#io_seocitylinktext_retore_button").click(function()
                                {
                                    jQuery("#io_seocitylinktext").val('<?php echo $defualt_io_seocitylinktext ?>');
                                });
                            });
                        </script>
                    </div>

                    <div class="sc_section">
                        <br>
                        <label for="io_customer_geolocation" class="io_fld_title">
                            <?php _e( "Customer Geolocation:", 'io' ); ?>
                        </label>
                        <br>
                        <span class="io_customer_geolocation_wrap">
                            <input type="checkbox" name="io_customer_geolocation" id="io_customer_geolocation" value="1" <?php echo $io_customer_geolocation; ?> class="widefat" />
                        </span>
                        <label for="io_customer_geolocation" class="io_fld_title">
                            <?php _e( "Enable customer geolocation", 'io' ); ?>
                        </label>
                    </div>
                    <?php
                     if(is_multisite())
                     { ?>
                         <div class="sc_section">
                             <div>
                                 <br>Multisite Settings:<br>
                             </div>
                             <span class="io_multisiteRedirect_wrap">
                                 <input type="checkbox" name="io_multisiteRedirect" id="io_multisiteRedirect" value="1" <?php echo $io_multisiteRedirect_check; ?>  class="widefat" />
                             </span>
                             <label for="io_multisiteRedirect" class="io_fld_title">
                                 <?php _e( "Warn users if they are on the wrong location.", 'io' ); ?>
                             </label>

                             <br>
                         </div>
                    <?php
                     } ?>

                    <div class="sc_section">
                        <br>
                        <table width="100%">
                            <tr>
                                <td>
                                    <p align="left"><input type="submit" name="io_submit" id="io_submit" class="button-primary" value="<?php _e('Save Changes')?>" /></p>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <?php wp_nonce_field('io_create_form'); ?>
                    <input name="io_form_main" type="hidden" value="1" />
                </form>

                <h3>
                    <b>Step 2</b>: Click Add New Client
                </h3>
                <a href="<?php echo site_url(); ?>?wpoauthincludes=create&_wpnonce=<?php echo wp_create_nonce( 'wpo-create-client' ); ?>&TB_iframe=true&width=600&height=420" class="add-new-h2 thickbox" title="Add New Client">
                    Add New Client
                </a>

                <?php
                $wp_list_table = new WO_Table();
                $wp_list_table->prepare_items();
                $wp_list_table->display();
                ?>

                <h3>
                    <b>Step 3</b>: Under Users (on the left menu), add a new user with Administrator Role
                </h3>

                <h3>
                    <b>Step 4</b>:<a href="https://rental.software/account/#/settings/wordpress" target="_blank">
                        Click here and add a new WP entry in InflatableOffice.
                    </a>
                </h3>

            </div><!-- Content -->
        </div><!-- Wrap -->

        <!-- Clean up username to prevent sign-in errors -->
        <script>
            var io_sc_form = document.getElementById("sc_form");
            var username_io = document.getElementById("io_username");
            io_sc_form.addEventListener("click", function(e)
            {
                var u_name = username_io.value;
                var u_name_array = u_name.split("");
                var index_array = [];
                for (var i = 0; i < u_name_array.length; i++)
                {
                    if (u_name_array[i] == " ") index_array.push(i);
                    else break;
                }
                if (index_array.length > 0)
                {
                    for (var j = 0; j < index_array.length; j++)
                    {
                        delete u_name_array[j];
                    }
                }
                username_io.value = u_name_array.join("");
            })
        </script>
        <?php
    }

    public function io_analytics_page(){

        $options = get_option($this->option_name);
        $this->admin_head();
        $scopes = apply_filters('WO_Scopes', null);
        error_reporting(0);

        $io_updated = false;

        // Insert shortcode
        if (isset($_POST["io_form_main"]) && $_POST["io_form_main"] == '1' && check_admin_referer('io_create_form')){

            // Updating the DB
            $io_analytics_active = 0;
            if($_POST['io_analytics_active']==1) $io_analytics_active=1;
            update_option("io_analytics_active", $io_analytics_active);


            $io_updated = true;
            // Insert Message
            if($io_updated == 'true'){
                echo '<div class="message updated fade"><p>' . __('Updated successfully !', 'io') . '</p></div>';
            }else{
                echo '<div class="message error fade"><p>' . __('Unable to save!', 'io') . '</p></div>';
            }
        }

        $io_analytics_active = get_option('io_analytics_active');
        $io_analytics_active_check = '';
        if($io_analytics_active==1) $io_analytics_active_check = 'checked="checked"';

        $io_analytics_code = get_option('io_analytics_code');
        ?>


        <div class="sc_modal">
            <span class="sc_modal_close"></span>
            <div></div>
        </div>

        <div class="wrap">
            <?php sc_admin_buttons('fbrec'); ?>
            <h2>InflatableOffice Analytics Integration</h2>
            <p>The following code is synced from your IO account. In IO, <a href="https://rental.software/account/#/settings/preferences?search=googletracking">update your analytics code</a>, then it will show up here. Be sure other analytic tracking WP plugins are not used at the same time.</p>

            <div id="content">

                <form method="post" id="sc_form">

                    <div class="sc_section">
                        <span class="io_prices_wrap"><input type="checkbox" name="io_analytics_active" id="io_analytics_active" value="1" <?php echo $io_analytics_active_check; ?> class="widefat" /></span>
                        <label for="io_analytics_active" class="io_fld_title"><?php _e( "Activate code below on site", 'io' ); ?></label>
                    </div>
                    <div class="sc_section">

                        <table width="100%"><tr>

                                <td><p align="left"><input type="submit" name="io_submit" id="io_submit" class="button-primary" value="<?php _e('Save Changes')?>" /></p></td>

                            </tr></table>

                    </div>

                    <div ><h2>Analytics code from IO</h2></div>
                    <p>Note: if empty, go to <a href="https://rental.software/account/#/settings/preferences?search=googletracking">IO analytics</a>, and save it, then reload this page.</p>
                    <div class="sc_section">
                        <textarea cols="116" rows="20" readonly><?php echo $io_analytics_code; ?></textarea>

                    </div>





                    <?php wp_nonce_field('io_create_form'); ?>
                    <input name="io_form_main" type="hidden" value="1" />
                </form>


            </div><!-- Content -->


        </div><!-- Wrap -->


        <?php
    }

    public function io_pricing_page(){

        $options = get_option($this->option_name);
        $this->admin_head();
        $scopes = apply_filters('WO_Scopes', null);
        error_reporting(0);
        add_thickbox();

        $io_updated = false;

        // Insert shortcode
        if (isset($_POST["io_form_main"]) && $_POST["io_form_main"] == '1' && check_admin_referer('io_create_form')){

            // Updating the DB
            $io_hide_prices = 0;
            if($_POST['io_hide_prices']==1) $io_hide_prices=1;
            update_option("io_hide_prices", $io_hide_prices);

            $io_hide_prices_catpages = 0;
            if($_POST['io_hide_prices_catpages']==1) $io_hide_prices_catpages=1;
            update_option("io_hide_prices_catpages", $io_hide_prices_catpages);

            if($_POST['io_info_required']==1){
                update_option("io_info_required", 'on');
            }else{
                update_option("io_info_required", 'off');
            }

            $io_info_required_data = Array();
            foreach($_POST as $k=>$p){
                $split = explode('_',$k);
                if($split[0] == 'io' && $split[1]=='info' && sizeof($split) == 4){
                    $io_info_required_data[$split[3]] = $p;
                }
            }
            if(empty($io_info_required_data)) update_option("io_info_required", "off");
            update_option("io_info_required_data", $io_info_required_data);

            $io_hide_live_prices = 0;
            if($_POST['io_hide_live_prices']==1) $io_hide_live_prices=1;
            update_option("io_hide_live_prices", $io_hide_live_prices);

            $io_hide_zero = 0;
            if($_POST['io_hide_zero']==1) $io_hide_zero=1;
            update_option("io_hide_zero", $io_hide_zero);

            if($_POST['io_always_display_live_price']==1){
                update_option("io_always_display_live_price", 'on');
            }else{
                update_option("io_always_display_live_price", 'off');
            }


            if($_POST['io_weekEndPrice']==1){
                update_option("io_weekEndPrice", 'on');
            }else{
                update_option("io_weekEndPrice", 'off');
            }

            $io_weekDayText = str_replace(array("\r\n", "\r", "\n"), "<br>", $_POST['io_weekDayText']);
            $io_weekDayText = str_replace('\\\\\\', '\\', $io_weekDayText);
            update_option( 'io_weekDayText',  $io_weekDayText);

            $io_weekEndText = str_replace(array("\r\n", "\r", "\n"), "<br>", $_POST['io_weekEndText']);
            $io_weekEndText = str_replace('\\\\\\', '\\', $io_weekEndText);
            update_option( 'io_weekEndText',  $io_weekEndText);

            update_option("io_weekendDefine", $_POST['io_weekendDefine']);

            if($_POST['io_accessory_price']==1){
                update_option("io_accessory_price", 'on');
            }else{
                update_option("io_accessory_price", 'off');
            }

            if($_POST['io_upsell_price']==1){
                update_option("io_upsell_price", 'on');
            }else{
                update_option("io_upsell_price", 'off');
            }

            $prices = Array('isset');//used to determine if we should show defaults (prior to them saving this page for backward compatability
            $prices['override_groups'] = Array();
            $delivery_prices = Array("default"=>Array(), "override"=>Array());
            $custom_prices = Array("default"=>Array(), "override"=>Array());
            $add_group = rand(1,9999999);
            $group = 0;
            foreach($_POST as $k=>$p){
                $split = explode('_',$k);
                if($split[0]=='io' && $split[1]=='product'){
                    $idc = '';
                    $id = $split[3];
                    if($id=='add') {//new ones
                        foreach ($_POST['io_price_add'] as $id) {
                            // IO-21808
                            $id = str_replace(":", "_", $id);
                            $prices[] = 'io_product_price_' . $split[3] . '_' . $id;
                        }
                    }elseif(sizeof($split)==5){//existing ones
                        foreach($_POST['io_price_'.$split[4]] as $id){
                            // IO-21808
                            $id = str_replace(":", "_", $id);
                            $prices[] = 'io_product_price_' . $split[3] . '_'.$id;
                        }
                    }else {//default ones
                        if (sizeof($split)==5) $idc = '_' . $id;
                        $prices[] = 'io_product_price_' . $split[3] . $idc;
                    }
                }elseif($split[0]=='io' && $split[1]=='price'){
                    if($split[2]=='add'){
                        $group = $add_group;
                    }else{
                        $group = $split[2];
                    }
                    foreach($p as $id) {
                        $prices['override_groups'][$group][$id] = 1;
                    }
                }elseif($split[0]=='io' && $split[1]=='delivery'){
                    $idc = '';
                    $del_id = $split[3];
                    if($del_id=='add') {//new ones
                        foreach ($_POST['io_price_add'] as $id) {
                            // IO-21808
                            $id = str_replace(":", "_", $id);
                            $prices[] = 'io_delivery_price_' . $split[3] . '_' . $id;
                            $delivery_prices['override'][$id][] = $del_id;
                        }
                    }elseif(sizeof($split)==5){//existing ones
                        foreach($_POST['io_price_'.$split[4]] as $id){
                            // IO-21808
                            $id = str_replace(":", "_", $id);
                            $prices[] = 'io_delivery_price_' . $split[3] . '_'.$id;
                            $delivery_prices['override'][$id][] = $del_id;
                        }
                    }else {//default ones
                        if (sizeof($split)==5) $idc = '_' . $del_id;
                        $prices[] = 'io_delivery_price_' . $split[3] . $idc;
                        $delivery_prices['default'][] = $del_id;
                    }
                }elseif($split[0]=='io' && $split[1]=='custom'){
                    $idc = '';
                    $cust_id = $split[3];
                    if($cust_id=='add') {//new ones
                        foreach ($_POST['io_price_add'] as $id) {
                            // IO-21808
                            $id = str_replace(":", "_", $id);
                            $prices[] = 'io_custom_price_' . $split[3] . '_' . $id;
                            $custom_prices['override'][$id][] = Array("name"=>$_POST[$k.'_name'], "duration"=>$_POST[$k.'_duration'], "id"=>$split[3]);
                        }
                    }elseif(sizeof($split) >= 5){//existing ones
                        if(sizeof($split) == 5){
                            foreach ($_POST['io_price_' . $split[4]] as $id) {
                                // IO-21808
                                $id = str_replace(":", "_", $id);
                                $prices[] = 'io_custom_price_' . $split[3] . '_' . $id;
                                $custom_prices['override'][$id][] = array("name" => $_POST[$k . '_name'], "duration" => $_POST[$k . '_duration'], "id" => $split[3]);
                            }
                        }
                    }else{//default ones
                        if (sizeof($split)==5) $idc = '_' . $cust_id;
                        $prices[] = 'io_custom_price_' . $split[3] . $idc;
                        $custom_prices['default'][] = Array("name"=>$_POST[$k.'_name'], "duration"=>$_POST[$k.'_duration'], "id"=>$split[3]);
                    }
                }
            }

            //print_r($_POST);
            //print_r($prices);
            update_option("io_prices", $prices);
            update_option("io_delivery_prices", $delivery_prices);
            update_option("io_custom_prices", $custom_prices);


            $io_updated = true;

            // Insert Message
            if($io_updated == 'true'){
                echo '<div class="message updated fade"><p>' . __('Updated successfully !', 'io') . '</p></div>';
            }else{
                echo '<div class="message error fade"><p>' . __('Unable to save!', 'io') . '</p></div>';
            }
        }

        $io_hide_live_prices = get_option('io_hide_live_prices');
        $io_hide_live_prices_check = '';
        if($io_hide_live_prices==1) $io_hide_live_prices_check = 'checked="checked"';

        $io_hide_zero = get_option('io_hide_zero');
        $io_hide_zero_check = '';
        if($io_hide_zero==1) $io_hide_zero_check = 'checked="checked"';

        $io_always_display_live_price = get_option('io_always_display_live_price');
        $io_always_display_live_price_check = '';
        if($io_always_display_live_price=="on") $io_always_display_live_price_check = 'checked="checked"';

        $io_hide_prices = get_option('io_hide_prices');
        $io_hide_prices_check = '';
        if($io_hide_prices==1) $io_hide_prices_check = 'checked="checked"';

        $io_hide_prices_catpages = get_option('io_hide_prices_catpages');
        $io_hide_prices_catpages_check = '';
        if($io_hide_prices_catpages==1) $io_hide_prices_catpages_check = 'checked="checked"';

        $io_info_required = get_option('io_info_required');
        $io_info_required_check = '';
        if($io_info_required=="on") $io_info_required_check = 'checked="checked"';

        $io_info_required_data = get_option('io_info_required_data');
        $io_info_required_checked = Array();
        foreach($io_info_required_data as $k=>$p){
            if($p == 1){
                $io_info_required_checked[$k] = 'checked="checked"';
            }
        }

        $io_weekEndPrice = get_option('io_weekEndPrice');
        $io_weekEndPrice_check = '';
        if($io_weekEndPrice=="on") $io_weekEndPrice_check = 'checked="checked"';

        $io_weekDayText = get_option('io_weekDayText');
        if(!$io_weekDayText) $io_weekDayText = 'Weekday price.';

        $io_weekEndText = get_option('io_weekEndText');
        if(!$io_weekEndText) $io_weekEndText = 'Weekend price.';

        $io_weekendDefine = get_option('io_weekendDefine');
        if(!$io_weekendDefine) $io_weekendDefine = "friday-sunday";


        $io_accessory_price = get_option('io_accessory_price');
        $io_accessory_price_check = '';
        if($io_accessory_price=="on") $io_accessory_price_check = 'checked="checked"';

        $io_upsell_price = get_option('io_upsell_price');
        $io_upsell_price_check = '';
        if($io_upsell_price=="on") $io_upsell_price_check = 'checked="checked"';


        $io_prices = get_option('io_prices');
        //$io_price_override_items = Array();
        foreach($io_prices as $v){
            if(is_array($v)) continue;
            $split = explode('_',$v);
            $hr = $split[3];
            $hr = rtrim($hr, 'h');
            $idc = '';
            $id = 0;
            if(sizeof($split)==5){
                $id = $split[4];
                $idc = '_'.$split[4];
                //$io_price_override_items[$id] = 1;
            }else if(sizeof($split)==6){
                //separate unit IO-21808
                $id = $split[4].":".$split[5];
                $idc = '_'.$split[4]."_".$split[5];
            }
            if($v=='io_product_price_'.$hr.'h'.$idc) {
                $io_prices_checked[$hr][$id] = 'checked="checked"';
            }
            else if($v=='io_product_price_'.$hr.$idc) {
                $io_prices_checked[$hr][$id] = 'checked="checked"';
            }else if($v=='io_delivery_price_'.$hr.$idc){
                $io_delivery_prices_checked[$hr][$id] = 'checked="checked"';
            }
        }
        ?>


        <div class="sc_modal">
            <span class="sc_modal_close"></span>
            <div></div>
        </div>

        <div class="wrap">
            <?php sc_admin_buttons('fbrec'); ?>
            <h2>InflatableOffice Pricing Setup</h2>


            <div id="content">

                <form method="post" id="sc_form">

                    <h2>Hide Pricing</h2>
                    <div class="sc_section">
                        <span class="io_prices_wrap"><input type="checkbox" name="io_hide_prices" id="io_hide_prices" value="1" <?php echo $io_hide_prices_check; ?> class="widefat" /></span>
                        <label for="io_hide_prices" class="io_fld_title"><?php _e( "Hide all prices (Override prices still show)", 'io' ); ?></label><br>
                        <span class="io_prices_wrap"><input type="checkbox" name="io_hide_prices_catpages" id="io_hide_prices_catpages" value="1" <?php echo $io_hide_prices_catpages_check; ?> class="widefat" /></span>
                        <label for="io_hide_prices_catpages" class="io_fld_title"><?php _e( "Hide price on category pages", 'io' ); ?></label><br>
                        <span class="io_prices_wrap"><input type="checkbox" name="io_hide_live_prices" id="io_hide_live_prices" value="1" <?php echo $io_hide_live_prices_check; ?> class="widefat" /></span>
                        <label for="io_hide_live_prices" title="Live pricing will provide the exact price for the date and time already selected." class="io_fld_title"><?php _e( "Hide live price on product page", 'io' ); ?>&nbsp;ⓘ</label><br>
                        <span class="io_prices_wrap"><input type="checkbox" name="io_hide_zero" id="io_hide_zero" value="1" <?php echo $io_hide_zero_check; ?> class="widefat" /></span>
                        <label for="io_hide_zero" class="io_fld_title"><?php _e( "Hide zero dollar prices on pages", 'io' ); ?></label><br>
                        <span class="io_prices_wrap"><input title="Default duration is 1 hour a price check without date or time set." type="checkbox" name="io_always_display_live_price" id="io_always_display_live_price" value="1" <?php echo $io_always_display_live_price_check; ?> class="widefat" /></span>
                        <label for="io_io_always_display_live_price" class="io_fld_title"><?php _e( "Allow live pricing to display if no date is set", 'io' ); ?></label><br>
                        <span class="io_prices_wrap"><input type="checkbox" name="io_info_required" id="io_info_required" value="1" <?php echo $io_info_required_check; ?> class="widefat" /></span>
                        <label for="io_info_required" class="io_fld_title"><?php _e( "Hide all pricing on page until information is provided.", 'io' ); ?></label>
                        <script>
                            jQuery( document ).ready(function() {
                                if ( jQuery("#io_info_required").is(':checked') ) {
                                    jQuery("#io_info_required_container").show();
                                } else {
                                    jQuery("#io_info_required_container").hide();
                                }
                                jQuery("#io_info_required").change(function() {
                                    if ( jQuery(this).is(':checked') ) {
                                        jQuery("#io_info_required_container").show();
                                    } else {
                                        jQuery("#io_info_required_container").hide();
                                    }
                                });
                            });
                        </script>
                        <div id="io_info_required_container">
                            <h4>Address Information</h4>
                            <span class="io_prices_wrap"><input type="checkbox" name="io_info_required_address" id="io_info_required_address" value="1" <?php echo $io_info_required_checked['address']; ?> class="widefat" /></span>
                            <label for="io_info_required_address" class="io_fld_title"><?php _e( "Street Address", 'io' ); ?></label>
                            <span class="io_prices_wrap"><input type="checkbox" name="io_info_required_city" id="io_info_required_city" value="1" <?php echo $io_info_required_checked['city']; ?> class="widefat" /></span>
                            <label for="io_info_required_city" class="io_fld_title"><?php _e( "City", 'io' ); ?></label>
                            <span class="io_prices_wrap"><input type="checkbox" name="io_info_required_zip" id="io_info_required_zip" value="1" <?php echo $io_info_required_checked['zip']; ?> class="widefat" /></span>
                            <label for="io_info_required_zip" class="io_fld_title"><?php _e( "Zip/Post Code", 'io' ); ?></label>
                        </div>
                    </div>

                    <div class="sc_section">
                        <?php if(get_option('io_brand')<>'PW'){ ?>
                            <div title="Define the default pricing time scale that will be displayed on product pages, ranging from 1 hour up to additional days or hours.
                                 Select the appropriate time scale by checking the corresponding box." style="font-size: 1.4em; font-weight: 400;">
                                <br>Default Product Page Prices<span style="font-size: 0.8em; vertical-align: top;">&nbsp;ⓘ</span></div><br>
                        <?php
                        for($hr=1;$hr<=16;$hr++){
                            echo $this->io_price_block($hr, $io_prices_checked[$hr][0]);
                        }
                        for($hr=24;$hr<=120;$hr+=24){
                            echo $this->io_price_block($hr, $io_prices_checked[$hr][0]);
                        }
                        for($hr=168;$hr<=720;$hr+=168){
                            echo $this->io_price_block($hr, $io_prices_checked[$hr][0]);
                        }
                        ?>
                            <span class="io_prices_wrap"><input type="checkbox" name="io_product_price_additionalday" id="io_product_price_additionalday" value="1" <?php echo $io_prices_checked['additionalday'][0] ?> class="widefat" /></span>
                            <label for="io_product_price_additionalday" class="io_fld_title" style="display:inline-block;width:85px;">Additional Day</label>
                            <span class="io_prices_wrap"><input type="checkbox" name="io_product_price_additionalhour" id="io_product_price_additionalhour" value="1" <?php echo $io_prices_checked['additionalhour'][0] ?> class="widefat" /></span>
                            <label for="io_product_price_additionalhour" class="io_fld_title" style="display:inline-block;width:95px;">Additional Hour</label>


                        <?php echo '<hr>';
                        echo '<h2>Dynamic Product Page Prices</h2>'; ?>
                            <div title="For custom price points, click on 'Create Custom Price Point' to set up unique pricing structures, such as for special events or promotions." style="font-size: 1.0em; font-weight: 400;">Custom Price Points<span style="font-size: .8em; vertical-align: top;">&nbsp;ⓘ</span></div><br>
                            <div id="customPriceContainer">
                                <?php
                                $custom_prices = get_option("io_custom_prices");
                                foreach($custom_prices['default'] as $custom_price){
                                    $html = "<span class='io_prices_wrap'>";
                                    $html .= "<input type='checkbox' name='io_custom_price_".$custom_price['id']."' id='io_custom_price_".$custom_price['id']."' value=1 class='widefat' checked='true'>";
                                    $html .= "<input style='display:none' name='io_custom_price_".$custom_price['id']."_duration' id='io_custom_price_".$custom_price['id']."_duration' value='".$custom_price['duration']."' readonly='true'>";
                                    $html .= "<input style='display:none' name='io_custom_price_".$custom_price['id']."_name' id='io_custom_price_".$custom_price['id']."_name' value='".$custom_price['name']."' readonly='true'>";
                                    $html .= "</span>";
                                    $html .= "<label for='io_custom_price_".$custom_price['id']."' class='io_fld_title' style='display:inline-block;width:152px;'>".$custom_price['name']."</label>";
                                    echo $html;
                                }
                                ?>
                            </div>
                            <a title="Create Custom Price Point" href="#TB_inline?width=200&height=400&inlineId=custom-price-modal" class="thickbox">Create Custom Price Point</a>
                            <div id="custom-price-modal" style="display:none;">
                                <p>Enter the name of the price point. This will display on item pages as "for [name]". For example if you enter "1/2 Hour" it will say "for 1/2 Hour" on item pages.</p>
                                <div style="display:flex">
                                    <label>Price name:</label> <input style="margin-left:5px" id="custom-price-name" type="text">
                                </div>
                                <br>
                                <p>Enter the duration of the price point. This is done in hours, so for example for an hour and thirty minutes you would enter 1.5, for forty five minutes enter .75.</p>
                                <div style="display:flex">
                                    <label>Price duration:</label> <input style="margin-left:5px" id="custom-price-duration" type="text">
                                </div>
                                <br>
                                <button onClick="create_new_price_point()">Create Price Point</button>
                            </div>
                            <script>
                                function create_new_price_point(group=null){
                                    if(group) {
                                        group = "_"+group;
                                    }else{
                                        group = "";
                                    }
                                    let price_name = jQuery("#custom-price-name"+group).val();
                                    let price_duration = jQuery("#custom-price-duration"+group).val();
                                    if(price_name && price_duration){
                                        let unique_number = 0
                                        do{
                                            unique_number = getRndInteger(0, 999999)
                                        }while(jQuery("#io_custom_price_"+unique_number+group).length > 0);
                                        id_name = "io_custom_price_"+unique_number+group;

                                        label = document.createElement("label");
                                        label.setAttribute("for", id_name);
                                        label.setAttribute("class", "io_fld_title");
                                        label.setAttribute("style", "display:inline-block;width:152px;");
                                        label.innerHTML = price_name;

                                        span = document.createElement("span");
                                        span.setAttribute("class", "io_prices_wrap");

                                        input = document.createElement("input");
                                        input.setAttribute("type", "checkbox");
                                        input.setAttribute("name", id_name);
                                        input.setAttribute("id", id_name);
                                        input.setAttribute("value", 1);
                                        input.setAttribute("class", "widefat");
                                        input.setAttribute("checked", true);

                                        hidden_duration_input = document.createElement("input");
                                        hidden_duration_input.setAttribute("style", "display:none");
                                        hidden_duration_input.setAttribute("id", id_name+"_duration");
                                        hidden_duration_input.setAttribute("name", id_name+"_duration");
                                        hidden_duration_input.setAttribute("value", price_duration);
                                        hidden_duration_input.setAttribute("readonly", true);

                                        hidden_name_input = document.createElement("input");
                                        hidden_name_input.setAttribute("style", "display:none");
                                        hidden_name_input.setAttribute("id", id_name+"_name");
                                        hidden_name_input.setAttribute("name", id_name+"_name");
                                        hidden_name_input.setAttribute("value", price_name);
                                        hidden_name_input.setAttribute("readonly", true);

                                        span.appendChild(input);
                                        span.appendChild(hidden_duration_input);
                                        span.appendChild(hidden_name_input);

                                        document.getElementById("customPriceContainer"+group).append(span);
                                        document.getElementById("customPriceContainer"+group).append(label);
                                    }
                                }
                                function getRndInteger(min, max) {
                                    return Math.floor(Math.random() * (max - min) ) + min;
                                }
                            </script>
                            <h4>Weekday/Weekend Pricing</h4>
                            <span class="io_prices_wrap"><input title="The time range for weekday and weekend prices are determined by the default start and end times in your cart settings." type="checkbox" name="io_weekEndPrice" id="io_weekEndPrice" value="1" <?php echo $io_weekEndPrice_check ?> class="widefat" /></span>
                            <label for="io_weekEndPrice" title="Check this box if you want to differentiate pricing for weekdays and weekends. The time range for weekday and weekend prices are determined by the default start and end times in your cart settings." class="io_fld_title" style="display:inline-block;width:195px;">Show&nbsp;Weekend/Weekday&nbsp;Pricing&nbsp;ⓘ</label>
                            <script>
                                jQuery( document ).ready(function() {
                                    if ( jQuery("#io_weekEndPrice").is(':checked') ) {
                                        jQuery("#io_weekEndPrice_container").show();
                                    } else {
                                        jQuery("#io_weekEndPrice_container").hide();
                                    }
                                    jQuery("#io_weekEndPrice").change(function() {
                                        if ( jQuery(this).is(':checked') ) {
                                            jQuery("#io_weekEndPrice_container").show();
                                        } else {
                                            jQuery("#io_weekEndPrice_container").hide();
                                        }
                                    });
                                });
                            </script>
                            <div id="io_weekEndPrice_container" style="margin-left: 25px; width: min-content">
                                <label style="cursor: auto"><?php _e( "Text to display next to Weekday price:", 'io' ); ?></label><br>
                                <span class="io_weekDayText_wrap"><textarea name="io_weekDayText" id="io_weekDayText" cols="50" rows="2"><?php echo $io_weekDayText; ?></textarea></span><br>
                                <label style="cursor: auto"><?php _e( "Text to display next to Weekend price:", 'io' ); ?></label><br>
                                <span class="io_weekEndText_wrap"><textarea name="io_weekEndText" id="io_weekEndText" cols="50" rows="2"><?php echo $io_weekEndText; ?></textarea></span><br>
                                <hr>
                                <script>
                                    jQuery( document ).ready(function() {
                                        var io_weekendDefine_radios = jQuery('input:radio[name=io_weekendDefine]');
                                        io_weekendDefine_radios.filter('[value=<?php echo $io_weekendDefine ?>]').prop('checked', true);
                                    });
                                </script>
                                <span class="io_weekendDefine_wrap">
                            <input type="radio" id="friday-sunday"
                                   name="io_weekendDefine" value="friday-sunday">
                            <label>Weekends are Friday-Sunday</label>
                            <br>
                            <input type="radio" id="saturday-sunday"
                                   name="io_weekendDefine" value="saturday-sunday">
                            <label>Weekends are Saturday and Sunday</label>
                            <br>
                            </span>
                            </div>
                        <?php } ?>
                        <?php echo $this->build_delivery_method_options($io_delivery_prices_checked); ?>
                        <hr>
                        <div title="Determine if you want to show live prices for accessories and upsell items. Check these options if you want these additional items to have their prices displayed dynamically."><h4>Show Accessory and Upsell Live Prices:&nbsp;ⓘ</h4></div>
                        <input type="checkbox" name="io_accessory_price" id="io_accessory_price" value="1" <?php echo $io_accessory_price_check ?> class="widefat" />
                        <label>Accessories</label>
                        <br>
                        <input type="checkbox" name="io_upsell_price" id="io_upsell_price" value="1" <?php echo $io_upsell_price_check ?> class="widefat" />
                        <label>Upsells</label>
                    </div>

                    <h2 title="If you need to set a special price for a particular item that is different from the default or dynamic pricing, click on 'Add Price Override'.
                    This option will show you a list of your products from which you can select and add custom price scales to."style="font-size: 1.4em; font-weight: 400;">Override Product Page Prices<span style="font-size: .8em; vertical-align: top;">&nbsp;ⓘ</h2>
                    <div class="sc_section">


                        <?php
                        foreach($io_prices['override_groups'] as $group => $items) {
                            ?>
                            <div id="io_price_<?php echo $group; ?>_wrap" style="border:solid black 1px;">
                                <label for="io_price_<?php echo $group; ?>"><?php _e('Hold Ctrl to select multiple', 'text_domain'); ?></label> <a onclick="jQuery('#io_price_<?php echo $group ; ?>').val([]);" style="cursor:pointer">Clear</a>
                                <table>
                                    <tr>
                                        <td>
                                            <select name="io_price_<?php echo $group; ?>[]" id="io_price_<?php echo $group; ?>" class="widefat" multiple style="height:200px">
                                                <?php
                                                $args = array('orderby' => 'name', 'order' => 'ASC', 'post_type' => 'page', 'posts_per_page' => -1);
                                                $loop = new WP_Query($args);
                                                $first_key = 0;
                                                while ( $loop->have_posts() ) : $loop->the_post();
                                                    //$pageid = get_the_id();//pageid
                                                    $name = get_the_title();
                                                    $content = get_the_content();
                                                    //get item id
                                                    $start = strpos($content, 'rental_id="') + 11;
                                                    if(strlen($content)<$start) continue;
                                                    $end = strpos($content, '"', $start);
                                                    $itemid = substr($content, $start, $end - $start);
                                                    //make sure it's an io page
                                                    if(strpos($content,'[sc :io_rental')!==FALSE) {
                                                        $select = !empty($items[$itemid]) ? $itemid : 0;
                                                        if($select>0) $first_key = $select;
                                                        echo '<option value="' . esc_attr($itemid) . '" id="' . esc_attr($itemid) . '" ' . selected($select, $itemid, false) . '>' . $name . '</option>';
                                                    }
                                                endwhile;
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <?php
                                            for ($hr = 0; $hr <= 16; $hr++) {
                                                echo $this->io_price_block($hr, $io_prices_checked[$hr][$first_key], $group);
                                            }
                                            for ($hr = 24; $hr <= 120; $hr += 24) {
                                                echo $this->io_price_block($hr, $io_prices_checked[$hr][$first_key], $group);
                                            }
                                            for ($hr = 168; $hr <= 720; $hr += 168) {
                                                echo $this->io_price_block($hr, $io_prices_checked[$hr][$first_key], $group);
                                            }
                                            ?>
                                            <span class="io_prices_wrap"><input type="checkbox" name="io_product_price_additionalday_<?php echo $group; ?>" id="io_product_price_additionalday_<?php echo $group; ?>" value="1" <?php echo $io_prices_checked['additionalday'][$first_key] ?> class="widefat" /></span>
                                            <label for="io_product_price_additionalday_<?php echo $group; ?>" class="io_fld_title" style="display:inline-block;width:85px;">Additional Day</label>
                                            <span class="io_prices_wrap"><input type="checkbox" name="io_product_price_additionalhour_<?php echo $group; ?>" id="io_product_price_additionalhour_<?php echo $group; ?>" value="1" <?php echo $io_prices_checked['additionalhour'][$first_key] ?> class="widefat" /></span>
                                            <label for="io_product_price_additionalhour_<?php echo $group; ?>" class="io_fld_title" style="display:inline-block;width:95px;">Additional Hour</label>
                                            <hr>
                                            <div id="customPriceContainer_<?php echo $group; ?>">
                                                <?php
                                                $custom_prices = get_option("io_custom_prices");
                                                foreach($io_prices['override_groups'][$group] as $item_id => $v){
                                                    foreach($custom_prices['override'][str_replace(":", "_", $item_id)] as $custom_price){
                                                        $html = "<span class='io_prices_wrap'>";
                                                        $html .= "<input type='checkbox' name='io_custom_price_".$custom_price['id']."_".$group."' id='io_custom_price_".$custom_price['id']."_".$group."' value=1 class='widefat' checked='true'>";
                                                        $html .= "<input style='display:none' name='io_custom_price_".$custom_price['id']."_".$group."_duration' id='io_custom_price_".$custom_price['id']."_".$group."_duration' value='".$custom_price['duration']."' readonly='true'>";
                                                        $html .= "<input style='display:none' name='io_custom_price_".$custom_price['id']."_".$group."_name' id='io_custom_price_".$custom_price['id']."_".$group."_name' value='".$custom_price['name']."' readonly='true'>";
                                                        $html .= "</span>";
                                                        $html .= "<label for='io_custom_price_".$custom_price['id']."_".$group."' class='io_fld_title' style='display:inline-block;width:152px;'>".$custom_price['name']."</lable>";
                                                        echo $html;
                                                    }
                                                    // Data is being saved poorly, need to break here to make sure we aren't outputting too much data.
                                                    break;
                                                }
                                                ?>
                                            </div>
                                            <a title="Create Custom Price Point" href="#TB_inline?width=200&height=400&inlineId=custom-price-modal_<?php echo $group; ?>" class="thickbox">Create Custom Price Point</a>
                                            <div id="custom-price-modal_<?php echo $group; ?>" style="display:none;">
                                                <p>Enter the name of the price point. This will display on item pages as "for [name]". For example if you enter "1/2 Hour" it will say "for 1/2 Hour" on item pages.</p>
                                                <div style="display:flex">
                                                    <label>Price name:</label> <input id="custom-price-name_<?php echo $group; ?>" type="text">
                                                </div>
                                                <br>
                                                <p>Enter the duration of the price point. This is done in hours, so for example for an hour and thirty minutes you would enter 1.5, for forty five minutes enter .75.</p>
                                                <div style="display:flex">
                                                    <label>Price duration:</label> <input id="custom-price-duration_<?php echo $group; ?>" type="text">
                                                </div>
                                                <button onClick="create_new_price_point(<?php echo $group; ?>)">Create Price Point</button>
                                            </div>
                                            <?php echo $this->build_delivery_method_options($io_delivery_prices_checked, $first_key, $group); ?>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <?php
                        }
                        //below is just for adding new
                        ?>

                        <?php if(get_option('io_brand')<>'PW'){ ?>
                            <input type="button" name="io_add_override" id="io_add_override" class="button-primary" onclick="jQuery('#io_price_add_wrap').show();jQuery(this).hide();" value="<?php _e('Add Price Override')?>" />
                        <?php } ?>
                        <div id="io_price_add_wrap" style="display:none;border:solid black 1px;">
                            <label for="io_price_add"><?php _e('Hold Ctrl to select multiple', 'text_domain'); ?></label> <a onclick="jQuery('#io_price_add').val([]);" style="cursor:pointer">Clear</a>
                            <table>
                                <tr>
                                    <td>
                                        <select name="io_price_add[]" id="io_price_add" class="widefat" multiple style="height:200px">
                                            <?php
                                            $args = array('orderby' => 'name', 'order' => 'ASC', 'post_type' => 'page', 'posts_per_page' => -1);
                                            $loop = new WP_Query($args);
                                            while ( $loop->have_posts() ) : $loop->the_post();
                                                //$pageid = get_the_id();
                                                $name = get_the_title();
                                                $content = get_the_content();
                                                //get item id
                                                $start = strpos($content, 'rental_id="') + 11;
                                                if(strlen($content)<$start) continue;
                                                $end = strpos($content, '"', $start);
                                                $itemid = substr($content, $start, $end - $start);
                                                //make sure it's an io page
                                                if(strpos($content,'[sc :io_rental')!==FALSE) {
                                                    //$select = in_array($itemid, $items) ? $itemid : 0;
                                                    echo '<option value="' . esc_attr($itemid) . '" id="' . esc_attr($itemid) . '">' . $name . '</option>';
                                                }
                                            endwhile;
                                            ?>
                                        </select>
                                    </td>
                                    <td>
                                        <?php
                                        for($hr=0;$hr<=16;$hr++){
                                            echo $this->io_price_block($hr,'','add');
                                        }
                                        for($hr=24;$hr<=120;$hr+=24){
                                            echo $this->io_price_block($hr,'','add');
                                        }
                                        for($hr=168;$hr<=720;$hr+=168){
                                            echo $this->io_price_block($hr,'','add');
                                        }
                                        ?>
                                        <span class="io_prices_wrap"><input type="checkbox" name="io_product_price_additionalday_add" id="io_product_price_additionalday_add" value="1" class="widefat" /></span>
                                        <label for="io_product_price_additionalday_add" class="io_fld_title" style="display:inline-block;width:85px;">Additional Day</label>
                                        <span class="io_prices_wrap"><input type="checkbox" name="io_product_price_additionalhour_add" id="io_product_price_additionalhour_add" value="1" class="widefat" /></span>
                                        <label for="io_product_price_additionalhour_add" class="io_fld_title" style="display:inline-block;width:95px;">Additional Hour</label>
                                        <hr>
                                        <div id="customPriceContainer_add">

                                        </div>
                                        <a title="Create Custom Price Point" href="#TB_inline?width=200&height=400&inlineId=custom-price-modal_add" class="thickbox">Create Custom Price Point</a>
                                        <div id="custom-price-modal_add" style="display:none;">
                                            <p>Enter the name of the price point. This will display on item pages as "for [name]". For example if you enter "1/2 Hour" it will say "for 1/2 Hour" on item pages.</p>
                                            <div style="display:flex">
                                                <label>Price name:</label> <input id="custom-price-name_add" type="text">
                                            </div>
                                            <br>
                                            <p>Enter the name of the price point. This will display on item pages as "for [name]". For example if you enter "1/2 Hour" it will say "for 1/2 Hour" on item pages.</p>
                                            <div style="display:flex">
                                                <label>Price duration:</label> <input id="custom-price-duration_add" type="text">
                                            </div>
                                            <button onClick="create_new_price_point('add')">Create Price Point</button>
                                        </div>
                                        <?php echo $this->build_delivery_method_options($io_delivery_prices_checked, 'add', 'add'); ?>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <div class="sc_section">
                        <table width="100%">
                            <tr>
                                <td><p align="left"><input type="submit" name="io_submit" id="io_submit" class="button-primary" value="<?php _e('Save Changes')?>" /></p></td>
                            </tr>
                        </table>
                    </div>

                    <?php wp_nonce_field('io_create_form'); ?>
                    <input name="io_form_main" type="hidden" value="1" />
                </form>

            </div><!-- Content -->
        </div><!-- Wrap -->


        <?php
    }

    public function io_cart_page(){

        $options = get_option($this->option_name);
        $this->admin_head();
        $scopes = apply_filters('WO_Scopes', null);
        error_reporting(0);
        add_thickbox();

        $io_updated = false;

        // Insert shortcode
        if (isset($_POST["io_form_main"]) && $_POST["io_form_main"] == '1' && check_admin_referer('io_create_form')){
            if($_POST['io_incartupsell']==1){
                update_option("io_incartupsell", 'on');
            }else{
                update_option("io_incartupsell", 'off');
            }

            if($_POST['io_distancecharge']==1){
                update_option("io_distancecharge", 'on');
            }else{
                update_option("io_distancecharge", 'off');
            }

            if($_POST['io_deliverymethod']==1){
                update_option("io_deliverymethod", 'on');
            }else{
                update_option("io_deliverymethod", 'off');
            }

            if($_POST['io_hideQuantityAvail']==1){
                update_option("io_hideQuantityAvail", 'on');
            }else{
                update_option("io_hideQuantityAvail", 'off');
            }

            if($_POST['io_cartPartyPlannerEmail']==1){
                update_option("io_cartPartyPlannerEmail", 'on');
            }else{
                update_option("io_cartPartyPlannerEmail", 'off');
            }
            update_option("io_cartPartyPlannerDestination", $_POST['io_cartPartyPlannerDestination']);

            $cart_message = str_replace(array("\r\n", "\r", "\n"), "<br>", $_POST['io_cartmessage']);
            $cart_message = str_replace('\\\\\\', '\\', $cart_message);
            update_option( 'io_cartmessage',  $cart_message);

            if($_POST['io_restricttimes']==1){
                update_option("io_restricttimes", 'on');
            }else{
                update_option("io_restricttimes", 'off');
            }

            if($_POST['io_cartForceBlank']==1)
                update_option("io_cartForceBlank", 'on');
            else
                update_option("io_cartForceBlank", 'off');

            if($_POST['io_cartHideEndTime']==1){
                update_option("io_cartHideEndTime", 'on');
            }
            else{
                update_option("io_cartHideEndTime", 'off');
            }


            if($_POST['io_cartAllowSameDay']==1){
                update_option("io_cartAllowSameDay", 'on');
            }else{
                update_option("io_cartAllowSameDay", 'off');
            }

            if($_POST['io_cartdayselect']=="multi_day" || $_POST['io_cartdayselect']=="dropdown_options"){
                update_option("io_multidayquote", 'on');
            }else{
                update_option("io_multidayquote", 'off');
            }
            update_option("io_cartdayselect", $_POST['io_cartdayselect']);

            $io_overnight_pickup_time = $_POST['io_overnightPickupTime'];
            if($_POST["io_timeformat"] == "g:i a") $io_overnight_pickup_time = date("g:i a", strtotime($io_overnight_pickup_time));
            else if($_POST["io_timeformat"] == "G:i") $io_overnight_pickup_time = date("G:i", strtotime($io_overnight_pickup_time));
            update_option('io_overnightPickupTime', $io_overnight_pickup_time);

            $start_restrict_time = $_POST['io_restrictTimeStart'];
            if($_POST["io_timeformat"] == "g:i a") $start_restrict_time = date("g:i a", strtotime($start_restrict_time));
            else if($_POST["io_timeformat"] == "G:i") $start_restrict_time = date("G:i", strtotime($start_restrict_time));
            update_option('io_restrictTimeStart', $start_restrict_time);
            $end_restrict_time = $_POST['io_restrictTimeEnd'];
            if($_POST["io_timeformat"] == "g:i a") $end_restrict_time = date("g:i a", strtotime($end_restrict_time));
            else if($_POST["io_timeformat"] == "G:i") $end_restrict_time = date("G:i", strtotime($end_restrict_time));
            update_option('io_restrictTimeEnd', $end_restrict_time);

            if (!empty($_POST['io_default_delivery_method'])) update_option('io_defaultDeliveryMethod', $_POST['io_default_delivery_method']);
            update_option('io_deliveryMethodRestrict', json_encode($_POST['io_delivery_method_restrict']));

            $io_updated = true;

            // Insert Message
            if($io_updated == 'true'){
                echo '<div class="message updated fade"><p>' . __('Updated successfully !', 'io') . '</p></div>';
            }else{
                echo '<div class="message error fade"><p>' . __('Unable to save!', 'io') . '</p></div>';
            }
        }
        $io_incartupsell = get_option('io_incartupsell')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_distancecharge = get_option('io_distancecharge')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_deliverymethod = get_option('io_deliverymethod')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_hideQuantityAvail = get_option('io_hideQuantityAvail')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_cartPartyPlannerEmail = get_option('io_cartPartyPlannerEmail')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_cartPartyPlannerDestination = get_option('io_cartPartyPlannerDestination');

        $io_cartAllowSameDay = get_option('io_cartAllowSameDay')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well

        $io_multidayquote = get_option('io_multidayquote');
        $io_cartdayselect = get_option('io_cartdayselect');
        if ($io_multidayquote == 'off') {// if multiday quote is off in IO account, force plugin to turn off as well
            $io_cartdayselect = 'single_day';
            update_option("io_cartdayselect", $io_cartdayselect);
        }
        if(!$io_cartdayselect) $io_cartdayselect = "single_day";

        $io_overnightPickupTime = "9:00 am";
        $io_overnight_pickup_time = get_option('io_overnightPickupTime');
        if($io_overnight_pickup_time !== false) $io_overnightPickupTime = $io_overnight_pickup_time;

        $io_restricttimes = get_option('io_restricttimes')=='on' ? 'checked="checked"' : '';//default if not set = off, in shortcode as well
        $io_restrictTimeStart = "11:00 am";
        $start_restrict_time = get_option('io_restrictTimeStart');
        if($start_restrict_time !== false) $io_restrictTimeStart = $start_restrict_time;
        $io_restrictTimeEnd = "3:00 pm";
        $end_restrict_time = get_option('io_restrictTimeEnd');
        if($end_restrict_time !== false) $io_restrictTimeEnd = $end_restrict_time;

        $io_cartForceBlank = get_option('io_cartForceBlank')=='on' ? 'checked="checked"' : ''; //default if not set = off, in shortcode as well

        $io_cartHideEndTime = get_option('io_cartHideEndTime')=='on' ? 'checked="checked"' : ''; //default if not set = off, in shortcode as well

        $io_cart_start_time = "11:00 am";
        $start_time = get_option('io_default_start_time');
        if($start_time !== false) $io_cart_start_time = $start_time;
        $io_cart_end_time = "3:00 pm";
        $end_time = get_option('io_default_end_time');
        if($end_time !== false) $io_cart_end_time = $end_time;

        $io_cart_time_format = "g:i a";
        $time_format = get_option('io_cart_time_format');
        if($time_format !== false) $io_cart_time_format = $time_format;

        $io_cart_date_format = "m/d/yy";
        $date_format = get_option('io_cart_date_format');
        if($date_format !== false) $io_cart_date_format = $date_format;

        $delivery_methods = json_decode(get_option('io_delivery_methods'));

        $io_cartmessage = "";
        if(get_option("io_cartmessage") !== false){
            $io_cartmessage = get_option("io_cartmessage");
        }

        $io_default_delivery_method = get_option("io_defaultDeliveryMethod");
        if (empty($io_default_delivery_method)) $io_default_delivery_method = '';

        $io_delivery_method_restrict = json_decode(get_option("io_deliveryMethodRestrict"));
        if(empty($io_delivery_method_restrict)) $io_delivery_method_restrict = Array();

        ?>

        <!-- Shortcoder Admin page -->

        <div class="sc_modal">
            <span class="sc_modal_close"></span>
            <div></div>
        </div>

        <div class="wrap">
            <?php sc_admin_buttons('fbrec'); ?>
            <h2>InflatableOffice Shopping Cart Settings</h2>

            <div id="content">
                <form method="post" id="sc_form">
                    <div class="sc_section">
                        <div>
                            <br>
                            <h4>
                                Shopping Cart Timepicker Settings:
                            </h4>
                        </div>

                    <!-- "Restrict all timepickers" -->
                        <span class="io_restricttime_wrap">
                            <input type="checkbox" name="io_restricttimes" id="io_restricttimes" value="1" <?php echo $io_restricttimes; ?>  class="widefat" />
                        </span>
                        <label for="io_restricttimes" title="Check this box if you wish to restrict the times customers can select based off of your times in the next item." class="io_fld_title">
                            <?php _e( "Restrict all timepickers", 'io' ); ?>&nbsp;ⓘ
                        </label>
                        <script>
                            jQuery( document ).ready(function() {
                                if ( jQuery("#io_restricttimes").is(':checked') ) {
                                    jQuery("#io_restrict_times_containter").show();
                                } else {
                                    jQuery("#io_restrict_times_containter").hide();
                                }
                                jQuery("#io_restricttimes").change(function() {
                                    if ( jQuery(this).is(':checked') ) {
                                        jQuery("#io_restrict_times_containter").show();
                                    } else {
                                        jQuery("#io_restrict_times_containter").hide();
                                    }
                                });
                                jQuery("input[name=io_restrictTimeStart]").change(function()
                                {
                                    end_timepicker = jQuery("[name='"+this.name.replace("Start", "End")+"']");
                                    debugger;
                                    end_timepicker.timepicker("option",{"minTime": jQuery(this).val()});
                                    end_timepicker.val("");
                                });
                            });
                        </script>
                        <br>

                        <div id="io_restrict_times_containter">
                        <!-- Restrict timepickers start -->
                            <label title="Earliest/latest available times available in the cart time selection when checking the box in the option above." class="io_fld_title" >
                                <?php _e( "Restrict timepickers start", 'io' ); ?>
                            </label>
                            <span class="io_restricttime_wrap">
                                <input type="text" name="io_restrictTimeStart" class="timepicker ui-timepicker-input" style="width:75px" value="<?php echo $io_restrictTimeStart;?>" />
                            </span>

                        <!-- Restrict timepickers end -->
                            <label class="io_fld_title">
                                <?php _e( "Restrict timepickers end", 'io' ); ?>
                            </label>
                            <span class="io_restricttime_wrap">
                                <input type="text" name="io_restrictTimeEnd" class="timepicker ui-timepicker-input" style="width:75px" value="<?php echo $io_restrictTimeEnd;?>" />
                            </span>
                            <br>
                        </div>
                        <script>
                            jQuery( document ).ready(function() {
                                jQuery(".timepicker").timepicker({
                                    startTime: new Date(0, 0, 0, 0, 0, 0),
                                    endTime: new Date(0, 0, 0, 23, 45, 0),
                                    timeFormat: "<?php echo $io_cart_time_format?>",
                                    separator: ":",
                                    className: "elementor-widget-text-editor",
                                    step: 15,
                                    disableTouchKeyboard: true
                                });
                                if(jQuery("input[name=io_restrictTimeStart]").val()){
                                    end_timepicker = jQuery("[name='io_restrictTimeEnd']");
                                    end_timepicker.timepicker("option", "minTime", jQuery("input[name=io_restrictTimeStart]").val())
                                        .timepicker("hide")
                                        .timepicker("show");
                                }
                            });
                        </script>

                    <!-- Force blank cart timepickers -->
                        <span class="io_cartForceBlank_wrap">
                            <input type="checkbox" name="io_cartForceBlank" id="io_cartForceBlank" value="1" <?php echo $io_cartForceBlank; ?>  class="widefat" />
                        </span>
                        <label for="io_cartForceBlank" title="Make timepickers in the cart have a blank default value forcing the customer to pick the times before checking out." class="io_fld_title">
                            <?php _e( "Force Blank Timepickers", 'io' ); ?>&nbsp;ⓘ
                        </label>
                        <br>

                    <!-- Hide end timepicker IO-30852-->
                        <div id="io_cartHideEndTime_container">
                            <span class="io_cartHideEndTime_wrap">
                                <input type="checkbox" name="io_cartHideEndTime" id="io_cartHideEndTime" value="1" <?php echo $io_cartHideEndTime; ?>  class="widefat" />
                            </span>
                            <label for="io_cartHideEndTime" title="Hide the end timepicker and end date in cart and checkout page. And end time must be set to when a user sets the start time in the cart this setting will set the hidden end time based off the duration set in IO general settings." class="io_fld_title">
                                <?php _e( "Hide End Timepicker In Cart", 'io' ); ?>&nbsp;ⓘ
                            </label>
                            <br>
                        </div>
                        <script>
                            jQuery( document ).ready(function() {
                                let io_cartdayselect_radios = jQuery('input:radio[name=io_cartdayselect]');
                                io_cartdayselect_radios.filter('[value=<?php echo $io_cartdayselect ?>]').prop('checked', true);
                                if ( jQuery("#single_day").is(':checked') ) {
                                    jQuery("#io_cartHideEndTime_container").show();
                                }
                                else {
                                    jQuery("#io_cartHideEndTime_container").hide();
                                    jQuery('#io_cartHideEndTime').prop('checked', false);
                                }
                                jQuery("[name='io_cartdayselect']").change(function() {
                                    if ( jQuery("#single_day").is(':checked') ) {
                                        jQuery("#io_cartHideEndTime_container").show();
                                    }
                                    else {
                                        jQuery("#io_cartHideEndTime_container").hide();
                                        jQuery('#io_cartHideEndTime').prop('checked', false);
                                    }
                                });
                            });
                        </script>

                    <!-- "Default cart start time" ->disabled because this is set in inflatable office IO-21277 !-->
                        <label title="Default times that you can have your cart start at and end at. This will not restrict times outside the window, it is only the default times. This setting is set in IO. General Prefrences -> Default Event Start Time" class="io_fld_title"><?php _e( "Default cart start time", 'io' ); ?></label>
                        <span class="io_prices_wrap">
                            <input type="text" name="io_timeStart" title="Default times that you can have your cart start at and end at.
                            This will not restrict times outside the window, it is only the default times. This setting is set in IO. General Prefrences -> Default Event Start Time"
                                   disabled class="timepicker ui-timepicker-input" style="width:75px" value="
                                   <?php
                                        if(get_option('io_cartForceBlank') != "on")
                                            echo $io_cart_start_time;
                                    ?>"
                            />
                        </span>
                        <label title="Default times that you can have your cart start at and end at. This will not restrict times outside the window, it is only the default times. This setting is set in IO. General Prefrences -> Default Event Start Time" class="io_fld_title"><?php _e( "Default cart end time", 'io' ); ?></label>

                    <!-- "Default cart end time" ->disabled because this is set in inflatable office IO-21277 !-->
                        <span class="io_prices_wrap">
                            <input type="text" name="io_timeEnd" title="Default times that you can have your cart start at and end at.
                            This will not restrict times outside the window, it is only the default times. This setting is set in IO. General Prefrences -> Default Event Start Time"
                                   disabled class="timepicker ui-timepicker-input" style="width:75px" value="
                                    <?php
                                        if(get_option('io_cartForceBlank') != "on")
                                            echo $io_cart_end_time;
                                    ?>"
                            />
                        </span>
                        <br>

                    <!-- disabled because this is set in inflatable office IO-21277 !-->
                        <label class="io_fld_title">
                            Time Format:
                        </label>
                        <span class="io_timeformat_wrap">
                            <select name="io_timeformat" title="This setting is set in IO. Account Prefrences -> Time Format" disabled value="<?php echo $io_cart_time_format;?>">
                                <option value="g:i a"<?php if($io_cart_time_format === 'g:i a'): ?> selected="selected" <?php endif ?>>
                                    12hr
                                </option>
                                <option value="G:i"<?php if($io_cart_time_format === 'G:i'): ?> selected="selected" <?php endif ?>>
                                    24hr
                                </option>
                            </select>
                            <br>
                        </span>
                    </div>

                    <div class="sc_section">
                        <div>
                            <br>
                            <h4>
                                Shopping Cart Calendar Settings:
                            </h4>
                        </div>

                        <label for="io_cartdayselect_wrap" class="io_fld_title">
                            <?php _e( "Calendar day select method:", 'io' ); ?>
                        </label>

                        <br>

                        <span title="You can choose which options to offer. This does not affect pricing; it only changes how many days your customer can choose in the shopping cart. If you offer overnight select the time that it will end the rental for on the day following the first day of the event." class="io_cartdayselect_wrap">
                            <input type="radio" id="single_day" name="io_cartdayselect" value="single_day">
                            <label for="contactChoice1">
                                Single day only or Company Timeslots&nbsp;ⓘ
                            </label>
                            <br>
                            <input type="radio" id="multi_day" name="io_cartdayselect" value="multi_day" <?php if (get_option('io_multidayquote') == 'off') echo 'disabled' ?>>
                            <label for="contactChoice2">
                                Allow multi-day select&nbsp;ⓘ
                            </label>
                            <br>
                            <input type="radio" id="single_overnight_multi" name="io_cartdayselect" value="dropdown_options" <?php if (get_option('io_multidayquote') == 'off') echo 'disabled' ?>>
                            <label for="contactChoice3">
                                Allow user to pick single day, overnight, or multiday&nbsp;ⓘ
                            </label>
                            <br>
                            <?php if (get_option('io_multidayquote') == 'on'): ?>
                                <div>
                                    <input type="radio" name="io_multidayquote" id="io_multidayquote" class="widefat" checked disabled/>
                                    Allow Multi-Day is <?php echo 'ON'; ?> in <a target="_blank" href="https://rental.software/account/#/settings/preferences/onlinequoting">Online Quoting</a>
                                </div>
                            <?php else: ?>
                                <div>
                                    <input type="radio" name="io_multidayquote" id="io_multidayquote" class="widefat" disabled/>
                                    Allow Multi-Day is <?php echo 'OFF'; ?> in <a target="_blank" href="https://rental.software/account/#/settings/preferences/onlinequoting">Online Quoting.</a> You'll need to turn it on to use multi day.
                                </div>
                            <?php endif; ?>
                        </span>
                        <script>
                            jQuery( document ).ready(function() {
                                let io_cartdayselect_radios = jQuery('input:radio[name=io_cartdayselect]');
                                io_cartdayselect_radios.filter('[value=<?php echo $io_cartdayselect ?>]').prop('checked', true);
                                if ( jQuery("#single_overnight_multi").is(':checked') ) {
                                    jQuery("#io_overnight_pickup_time_container").show();
                                }
                                else {
                                    jQuery("#io_overnight_pickup_time_container").hide();
                                }
                                jQuery("[name='io_cartdayselect']").change(function() {
                                    if ( jQuery("#single_overnight_multi").is(':checked') ) {
                                        jQuery("#io_overnight_pickup_time_container").show();
                                    }
                                    else {
                                        jQuery("#io_overnight_pickup_time_container").hide();
                                    }
                                });
                            });
                        </script>

                        <div id="io_overnight_pickup_time_container">
                            <label class="io_fld_title">
                                <?php _e( "Next day pickup time for overnight setting", 'io' ); ?>
                            </label>
                            <span class="io_overnightPickupTime_wrap">
                                <input type="text" name="io_overnightPickupTime" class="timepicker ui-timepicker-input" style="width:75px" value="<?php echo $io_overnightPickupTime;?>" />
                            </span>
                        </div>
                        <br>

                    <!-- Allow today's date as an option in the cart -->
                        <span class="io_cartAllowSameDay_wrap">
                            <input type="checkbox" name="io_cartAllowSameDay" id="io_cartAllowSameDay" value="1" <?php echo $io_cartAllowSameDay; ?>  class="widefat" />
                        </span>
                        <label for="io_cartAllowSameDay" title="Choose whether or not selecting today's date for an event is possible. If your account isn't setup to allow online bookings this will not change that." class="io_fld_title">
                            <?php _e( "Allow users to select today's date in cart calendar", 'io' ); ?>&nbsp;ⓘ
                        </label>
                        <br>

                    <!-- Date Format ->disabled because this is set in inflatable office IO-21277 !-->
                        <label class="io_fld_title">Date Format:</label>
                        <span class="io_dateformat_wrap">
                            <select name="io_dateformat" title="This setting is set in IO. Account Prefrences -> Date Format" disabled value="<?php echo $io_cart_date_format;?>">
                                <option value="m/d/yy" <?php if($io_cart_date_format === 'm/d/yy'): ?> selected="selected" <?php endif ?>>
                                    M/D/YY
                                </option>
                                <option value="d/m/yy" <?php if($io_cart_date_format === 'd/m/yy'): ?> selected="selected" <?php endif ?>>
                                    D/M/YY
                                </option>
                            </select>
                        </span><br>
                        <!-- <span class="io_multidayquote_wrap"><input type="checkbox" name="io_multidayquote" id="io_multidayquote" value="1" <?php //echo $io_multidayquote; ?>  class="widefat" /></span> -->

                    </div>

                    <div class="sc_section">

                        <br>

                        <div>
                            <h4>
                                Other Cart Settings:
                            </h4>
                        </div>

                        <span class="io_hideQuantityAvail_wrap"><input type="checkbox" name="io_hideQuantityAvail" id="io_hideQuantityAvail" value="1" <?php echo $io_hideQuantityAvail; ?>  class="widefat" /></span>
                        <label for="io_hideQuantityAvail" title="Hide the quantity of the item that the customer has in their cart." class="io_fld_title"><?php _e( "Hide quantity available", 'io' ); ?>&nbsp;ⓘ</label><br>
                        <span class="io_cartupsell_wrap"><input type="checkbox" name="io_incartupsell" id="io_incartupsell" value="1" <?php echo $io_incartupsell; ?>  class="widefat" /></span>
                        <label for="io_incartupsell" title="Displays the upsell carousel at the bottom of the cart pop-up window" class="io_fld_title"><?php _e( "Show upsell in cart", 'io' ); ?>&nbsp;ⓘ</label><br>
                        <span class="io_distancecharge_wrap"><input type="checkbox" name="io_distancecharge" id="io_distancecharge" value="1" <?php echo $io_distancecharge; ?>  class="widefat" /></span>
                        <label for="io_distancecharge" title="Show the distance charge if the customer has entered their delivery location. Enables/disables the Check Delivery button." class="io_fld_title"><?php _e( "Show distance charge", 'io' ); ?>&nbsp;ⓘ</label><br>
                            <div id="io_default_delivery_method_container" style="display: grid; margin-left: 30px;">
                            <label for="io_default_delivery_method"><b><?php _e('Pick a delivery method to set as the default:', 'text_domain'); ?></b></label>
                            <select name="io_default_delivery_method" id="io_default_delivery_method" class="widefat"></select>
                                <script>
                                    jQuery(document).ready(function () {
                                        if (jQuery("#io_distancecharge").is(':checked')) {
                                            jQuery("#io_default_delivery_method_container").show();
                                        } else {
                                            jQuery("#io_default_delivery_method_container").hide();
                                        }

                                        jQuery("#io_distancecharge").change(function () {
                                            if (jQuery(this).is(':checked')) {
                                                jQuery("#io_default_delivery_method_container").show();
                                            } else {
                                                jQuery("#io_default_delivery_method_container").hide();
                                            }
                                        });

                                        // Append options to select
                                        let default_delivery = jQuery("#io_default_delivery_method");
                                        <?php
                                        $options_html = '';
                                        foreach ($delivery_methods as $method => $data) {
                                            $options_html .= '<option value="' . esc_html($method) . '">' . esc_html($method) . '</option>';
                                                                            }
                                        ?>
                                        default_delivery.append('<?php echo $options_html; ?>');

                                    // Set default selection
                                        <?php if (empty($io_default_delivery_method)) : ?>
                                            jQuery("#io_default_delivery_method")[0].selectedIndex = 0;
                                        <?php else : ?>
                                            jQuery("#io_default_delivery_method").val("<?php echo esc_js($io_default_delivery_method); ?>");
                                        <?php endif; ?>
                                    });
                                </script>
                            </div>
                        <span class="io_deliverymethod_wrap"><input type="checkbox" name="io_deliverymethod" id="io_deliverymethod" value="1" <?php echo $io_deliverymethod; ?>  class="widefat" /></span>
                        <label for="io_deliverymethod" title="Show delivery methods that you have setup in your account on the cart window" class="io_fld_title"><?php _e( "Show delivery methods", 'io' ); ?>&nbsp;ⓘ</label><br>
                        <div id="io_deliveryMethodRestrict_container" style="display: grid; margin-left: 30px;">
                            <label for="io_delivery_method_restrict"><?php _e('Select which delivery methods you do not want shown.', 'text_domain'); ?></label>
                            <div><label for="io_delivery_method_restrict"><?php _e('Hold Ctrl to select multiple', 'text_domain'); ?></label> <a onclick="jQuery('#io_delivery_method_restrict').val([]);" style="cursor:pointer">Clear</a></div>
                            <select name="io_delivery_method_restrict[]" id="io_delivery_method_restrict" class="widefat" multiple style="height:100px"></select>
                            <script>
                                jQuery(document).ready(function () {
                                    if (jQuery("#io_deliverymethod").is(':checked')) {
                                        jQuery("#io_deliveryMethodRestrict_container").show();
                                    } else {
                                        jQuery("#io_deliveryMethodRestrict_container").hide();
                                    }
                                    jQuery("#io_deliverymethod").change(function () {
                                        if (jQuery(this).is(':checked')) {
                                            jQuery("#io_deliveryMethodRestrict_container").show();
                                        } else {
                                            jQuery("#io_deliveryMethodRestrict_container").hide();
                                        }
                                    });
                                    let method_restrict = jQuery("#io_delivery_method_restrict");
                                    <?php
                                    $options_html = '';
                                    foreach ($delivery_methods as $method => $data) {
                                        $options_html .= '<option value="' . $data->id . '" id="' . $data->id . '"> ' . $method . ' </option>';
                                    }
                                    ?>
                                    jQuery("#io_delivery_method_restrict").append('<?php echo $options_html ?>');
                                    jQuery("#io_delivery_method_restrict").val([<?php echo implode(',', $io_delivery_method_restrict) ?>]);
                                });
                            </script>
                        </div>
                        <span class="io_cartPartyPlannerEmail_wrap"><input type="checkbox" name="io_cartPartyPlannerEmail" id="io_cartPartyPlannerEmail" value="1" <?php echo $io_cartPartyPlannerEmail; ?>  class="widefat" /></span>
                        <label for="io_cartPartyPlannerEmail" title="Once the Party Planner feature has been enabled, the shopping cart on your website will have a place for a customer to enter in their email address. After supplying an email address and clicking “go,” a new browser tab will open with a Party Planning form." class="io_fld_title"><?php _e( "Enable Party Planner email input", 'io' ); ?>&nbsp;ⓘ</label><br>
                        <div id="io_cartPartyPlannerDestination_container" style=" display: grid; margin-left: 30px;">
                            <label for="io_cartPartyPlannerDestination" class="io_fld_title"><?php _e( "Destination URL", 'io' ); ?></label>
                            <input id="io_cartPartyPlannerDestination" name="io_cartPartyPlannerDestination" type="text" style="width:300px" value="<?php echo $io_cartPartyPlannerDestination; ?>">
                            <script>
                                jQuery( document ).ready(function() {
                                    if ( jQuery("#io_cartPartyPlannerEmail").is(':checked') ) {
                                        jQuery("#io_cartPartyPlannerDestination_container").show();
                                    } else {
                                        jQuery("#io_cartPartyPlannerDestination_container").hide();
                                    }
                                    jQuery("#io_cartPartyPlannerEmail").change(function() {
                                        if ( jQuery(this).is(':checked') ) {
                                            jQuery("#io_cartPartyPlannerDestination_container").show();
                                        } else {
                                            jQuery("#io_cartPartyPlannerDestination_container").hide();
                                        }
                                    });
                                });
                            </script>
                        </div>
                        <label for="io_cartmessage" title="Custom Message you can choose to display to customers in the cart window." class="io_fld_title"><?php _e( "In-cart message:", 'io' ); ?>&nbsp;ⓘ</label><br>
                        <span class="io_cartmessage_wrap"><textarea name="io_cartmessage" id="io_cartmessage" cols="50" rows="3"><?php echo $io_cartmessage; ?></textarea></span>
                    </div>

                    <div class="sc_section">

                        <table width="100%"><tr>

                                <td><p align="left"><input type="submit" name="io_submit" id="io_submit" class="button-primary" value="<?php _e('Save Changes')?>" /></p></td>

                            </tr></table>

                    </div>

                    <?php wp_nonce_field('io_create_form'); ?>

                    <input name="io_form_main" type="hidden" value="1" />

                </form>

            </div><!-- Content -->

        </div><!-- Wrap -->

        <?php
    }

    public function io_reviews_page()
    {
        require_once(__DIR__ . '/../reviews/controller.php');

        $io_reviews_admin_page = new IO_Reviews_Admin_Page();
        $io_reviews_admin_page->handle_requests();
        $io_reviews_admin_page->render_page();
    }

    public function io_price_block($hr,$checked='',$id=''){
        $display='';
        if($hr==1){
            $display = '1 hour';
        }elseif($hr<=16){
            $display = $hr. ' hours';
        }elseif($hr<168){
            $display = ($hr/24). ' days';
        }else{
            $display = ($hr/(24*7)). ' weeks';
        }
        $idc = '';
        if(!empty($id)) $idc = '_'.$id;
        $html = '<span class="io_prices_wrap"><input type="checkbox" name="io_product_price_'.$hr.'h'.$idc.'" id="io_product_price_'.$hr.'h'.$idc.'" value="1" '.$checked.' class="widefat" /></span>
                 <label for="io_product_price_'.$hr.'h'.$idc.'" class="io_fld_title" style="display:inline-block;width:52px;">'.$display.'</label>';
        if($hr==8 | $hr==16 | $hr==120) $html.='<br>';
        return $html;
    }

    public function build_delivery_method_options($io_delivery_prices_checked, $id='', $group=''){
        $delivery_methods = json_decode(get_option('io_delivery_methods'));
        if(!$delivery_methods) return '';
        $html = '<hr>';
        $html .= '<div ><h4>Delivery Methods:</h4></div>';
        $html .= '<p>The following options will display the price based on the time selected by the customer.</p>';
        if(empty($id)) {
            $id='0';
        }
        if(!empty($group)) $group = '_'.$group;
        foreach($delivery_methods as $method => $data){
            $checked = $io_delivery_prices_checked[$data->id][$id];
            if($id == 'add') $checked='';
            $html .= '<span class="io_prices_wrap"><input type="checkbox" name="io_delivery_price_'.$data->id.$group.'" id="io_delivery_price_'.$data->id.'" value="1" '.$checked.' class="widefat" /></span>
                     <label for="io_delivery_price_'.$data->id.$group.'" class="io_fld_title" style="display:inline-block;width:auto; margin-right: 5px;">'.$method.'</label>';
        }
        return $html;
    }

    public function build_accessory_pricing_option($io_accessory_price_checked, $id='', $group=''){
        $delivery_methods = json_decode(get_option('io_delivery_methods'));
        if(!$delivery_methods) return '';
        $html = '<hr>';
        $html .= '<h4>Delivery Methods:</h4>';
        $html .= '<p>The following options will display the price based on the time selected by the customer.</p>';
        if(empty($id)) {
            $id='0';
        }
        if(!empty($group)) $group = '_'.$group;
        foreach($delivery_methods as $method => $data){
            $checked = $io_delivery_prices_checked[$data->id][$id];
            if($id == 'add') $checked='';
            $html .= '<span class="io_prices_wrap"><input type="checkbox" name="io_delivery_price_'.$data->id.$group.'" id="io_delivery_price_'.$data->id.'" value="1" '.$checked.' class="widefat" /></span>
                     <label for="io_delivery_price_'.$data->id.$group.'" class="io_fld_title" style="display:inline-block;width:auto; margin-right: 5px;">'.$method.'</label>';
        }
        return $html;
    }


    /**
     * loads the plugin styles and scripts into scope
     * @return [type] [description]
     */
    public function admin_head() {
        wp_enqueue_style('wo_admin');
        wp_enqueue_script('wo_admin');
        wp_enqueue_script('jquery-ui-tabs');
    }

    /**
     * [options_do_page description]
     * @return [type] [description]
     */
    public function options_do_page() {
        $options = get_option($this->option_name);
        $this->admin_head();
        $scopes = apply_filters('WO_Scopes', null);
        error_reporting(0);
        add_thickbox();
        ?>
        <div class="wrap">
            <h2>WP OAuth Server <strong><small> | v<?php echo _WO()->version; ?></small></strong></h2>
            <br/>
            <p>VERSION 3.1.9</p>
            <form method="post" action="options.php">
                <?php settings_fields('wo_options');?>
                <div id="wo_tabs">
                    <ul>
                        <li><a href="#general-settings">General Settings</a></li>
                        <li><a href="#advanced-configuration">Advanced Configuration</a></li>
                        <li><a href="#clients">Clients</a></li>
                    </ul>

                    <!-- GENERAL SETTINGS -->
                    <div id="general-settings">
                        <table class="form-table">
                            <tr valign="top" style="display:none">
                                <th scope="row">License Key:</th>
                                <td>
                                    <input type="text" name="<?php echo $this->option_name?>[license]" value="<?php echo $options["license"];?>" length="40" style="width:300px;"/>
                                    <?php echo license_status(); ?>
                                    <?php if (!_vl()): ?>
                                        <p class="description">Get a license by visiting <a href="https://wp-oauth.com/knowledge-base/" target="_blank">http://wp-oauth.com/pro-license</a>.</p>
                                    <?php else: ?>
                                        <p class="description" style="color:orange;">Upgrade to 3.2.0. <strong>WARNING:</strong> There is manual setup to configure options after this update.</p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row">API Enabled:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[enabled]" value="1" <?php echo $options["enabled"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">If the API is not enabled, it will present requests with an "Unavailable" message.</p>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <!-- ADVANCED CONFIGURATION -->
                    <div id="advanced-configuration">
                        <h2>Advanced Configuration</h2>

                        <h3>Grant Types <hr></h3>
                        <p>Control which Grant Types that the server will accept.</p>
                        <table class="form-table">

                            <tr valign="top">
                                <th scope="row">Authorization Code:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[auth_code_enabled]" value="1" <?php echo $options["auth_code_enabled"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">HTTP redirects and WP login form when authenticating.</p>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">Client Credentials:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[client_creds_enabled]" value="1" <?php echo $options["client_creds_enabled"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">Enable "Client Credentials" Grant Type</p>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">User Credentials:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[user_creds_enabled]" value="1" <?php echo $options["user_creds_enabled"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">Enable "User Credentials" Grant Type</p>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">Refresh Tokens:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[refresh_tokens_enabled]" value="1" <?php echo $options["refresh_tokens_enabled"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">Enable "Refresh Token" Grant Type</p>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">Allow Implicit:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[implicit_enabled]" value="1" <?php echo $options["implicit_enabled"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">Enable "Authorization Code (Implicit)" <a href="http://wp-oauth.com/documentation/server-api/which-grant-type-to-use/">What is this?</a></p>
                                </td>
                            </tr>

                        </table>

                        <h3>Misc Settings <hr></h3>
                        <table class="form-table">
                            <tr valign="top">
                                <th scope="row">Key Length</th>
                                <td>
                                    <input type="number" name="<?php echo $this->option_name?>[client_id_length]" min="10" value="<?php echo $options["client_id_length"];?>" />
                                    <p class="description">Length of Client ID and Client Secrets when generated.</p>
                                </td>
                            </tr>
                            <tr valign="top">
                                <th scope="row">Require Exact Redirect URI:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[require_exact_redirect_uri]" value="1" <?php echo $options["require_exact_redirect_uri"] == "1" ? "checked='checked'" : "";?> />
                                    <p class="description">Enable if exact redirect URI is required when authenticating.</p>
                                </td>
                            </tr>

                            <tr valign="top">
                                <th scope="row">Enforce State Parameter:</th>
                                <td>
                                    <input type="checkbox" name="<?php echo $this->option_name?>[enforce_state]" value="1" <?php echo $options["enforce_state"] == "1" ? "checked='checked'" : "";?>/>
                                    <p class="description">Enable if the "state" parameter is required when authenticating. </p>
                                </td>
                            </tr>
                        </table>
                        <div style="display:none">
                            <!-- OpenID Connect -->
                            <h3>OpenID Connect 1.0a <hr></h3>
                            <p>
                                The OpenID Connect 1.0a works with other systems like Drupal and Moodle.
                            </p>
                            <table class="form-table">
                                <tr valign="top">
                                    <th scope="row">Enable OpenID Connect:</th>
                                    <?php if(_vl($options['license'])): ?>
                                        <td>
                                            <input type="checkbox" name="<?php echo $this->option_name?>[use_openid_connect]" value="1" <?php echo $options["use_openid_connect"] == "1" ? "checked='checked'" : "";?>/>
                                            <p class="description">Enable if your server should generate a id_token when OpenID request is made.</p>
                                        </td>
                                    <?php else: ?>
                                        <td>
                                            <input type="checkbox" disabled="yes" />
                                            <p class="description">Enable OpenID Connect 1.0a <a href="https://wp-oauth.com/downloads/wp-oauth-license/" style="color:red;">License Required</a></p>
                                        </td>
                                    <?php endif; ?>
                                </tr>

                                <tr valign="top">
                                    <?php if(_vl($options['license'])): ?>
                                        <th scope="row">ID Token Lifetime</th>
                                        <td>
                                            <input type="number" name="<?php echo $this->option_name?>[id_token_lifetime]" value="<?php echo $options["id_token_lifetime"];?>" placeholder="3600" />
                                            <p class="description">How long an id_token is valid (in seconds).</p>
                                        </td>
                                    <?php else: ?>
                                        <th scope="row">ID Token Lifetime</th>
                                        <td>
                                            <input type="number" placeholder="3600" disabled="yes" />
                                            <p class="description">How long an id_token is valid (in seconds). <a href="https://wp-oauth.com/downloads/wp-oauth-license/" style="color:red;">License Required</a></p>
                                        </td>
                                    <?php endif; ?>
                                </tr>

                            </table>

                            <h3>Token Lifetimes <?php echo !_vl()? ' <i style="color:red;font-size:14px;">License Required</i>':'';?> <hr></h3>
                            <p>
                                Take control of your token lifetimes easily. By default Access Tokens are valid for 1 hour
                                and Refresh Tokens are valid for 24 hours.
                            </p>
                            <?php if(_vl($options['license'])): ?>
                                <table class="form-table">
                                    <tr valign="top">
                                        <th scope="row">Access Token Lifetime</th>
                                        <td>
                                            <input type="number" name="<?php echo $this->option_name?>[access_token_lifetime]" value="<?php echo $options["access_token_lifetime"];?>" placeholder="3600" />
                                            <p class="description">How long an access token is valid (seconds) - Leave blank for default (1 hour)</p>
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <th scope="row">Refresh Token Lifetime</th>
                                        <td>
                                            <input type="number" name="<?php echo $this->option_name?>[refresh_token_lifetime]" value="<?php echo $options["refresh_token_lifetime"];?>" placeholder="86400"/>
                                            <p class="description">How long a refresh token is valid (seconds)- Leave blank for default (24 hours)</p>
                                        </td>
                                    </tr>
                                </table>
                            <?php endif; ?>

                            <h3>Firewall <?php echo !_vl($options['license'])? ' <i style="color:red;font-size:14px;">License Required</i>':'';?><hr></h3>
                            <p>
                                The firewall is used to secure your OAuth API by allowing you to block all IP's and only allow
                                approved IP's through. The firewall supports whitelisting of IPV4 and IPv6 addresses.
                            </p>
                            <?php if(_vl($options['license'])): ?>
                                <table class="form-table">
                                    <tr valign="top">
                                        <th scope="row">Block All Incoming Requests but Whitelisted: </th>
                                        <td>
                                            <input type="checkbox" name="<?php echo $this->option_name?>[firewall_block_all_incomming]" value="1" <?php echo $options["firewall_block_all_incomming"] == "1" ? "checked='checked'" : "";?>/>
                                            <p class="description">Block all incomming requests that are not whitelisted below. </p>
                                        </td>
                                    </tr>

                                    <tr valign="top">
                                        <th scope="row">IP Whitelist: </th>
                                        <td>
                                            <textarea name="<?php echo $this->option_name?>[firewall_ip_whitelist]" style="margin: 0px;width: 340px;height: 140px;resize: none;" placeholder="127.0.0.1, ::1"><?php echo $options["firewall_ip_whitelist"]; ?></textarea>
                                            <p class="description">Enter IP addresses separated by commas. IPV4 and IPV6 are supported.</p>
                                        </td>
                                    </tr>
                                </table>
                            <?php endif; ?>

                        </div>
                    </div>

                    <!-- CLIENTS -->
                    <div id="clients">
                        <h2>
                            Clients
                            <a href="<?php echo site_url(); ?>?wpoauthincludes=create&_wpnonce=<?php echo wp_create_nonce( 'wpo-create-client' ); ?>&TB_iframe=true&width=600&height=420" class="add-new-h2 thickbox" title="Add New Client">Add New Client</a>
                        </h2>

                        <?php
                        $wp_list_table = new WO_Table();
                        $wp_list_table->prepare_items();
                        $wp_list_table->display();
                        ?>
                    </div>
                    <br>
                </div>

                <p class="submit">
                    <input type="submit" class="button-primary" value="<?php _e('Save Changes')?>" />
                </p>
            </form>
        </div>
        <?php
    }

    /**
     * WO options validation
     * @param  [type] $input [description]
     * @return [type]        [description]
     */
    public function validate($input) {

        // Check box values
        $input["enabled"] = isset($input["enabled"]) ? $input["enabled"] : 0;
        $input["auth_code_enabled"] = isset($input["auth_code_enabled"]) ? $input["auth_code_enabled"] : 0;
        $input["client_creds_enabled"] = isset($input["client_creds_enabled"]) ? $input["client_creds_enabled"] : 0;
        $input["user_creds_enabled"] = isset($input["user_creds_enabled"]) ? $input["user_creds_enabled"] : 0;
        $input["refresh_tokens_enabled"] = isset($input["refresh_tokens_enabled"]) ? $input["refresh_tokens_enabled"] : 0;
        $input["implicit_enabled"] = isset($input["implicit_enabled"]) ? $input["implicit_enabled"] : 0;

        $input["require_exact_redirect_uri"] = isset($input["require_exact_redirect_uri"]) ? $input["require_exact_redirect_uri"] : 0;
        $input["enforce_state"] = isset($input["enforce_state"]) ? $input["enforce_state"] : 0;
        $input["use_openid_connect"] = isset($input["use_openid_connect"]) ? $input["use_openid_connect"] : 0;

        if(!isset($input['id_token_lifetime']))
            $input['id_token_lifetime'] = 3600;

        if(!isset($input['access_token_lifetime']))
            $input['access_token_lifetime'] = 3600;

        if(!isset($input['refresh_token_lifetime']))
            $input['refresh_token_lifetime'] = 86400;

        // Only run with valid license
        $input["blacklist_ip_range_enabled"] = isset($input["blacklist_ip_range_enabled"]) ? $input["blacklist_ip_range_enabled"] : 0;
        $input["block_all_incomming"] = isset($input["block_all_incomming"]) ? $input["block_all_incomming"] : 0;

        $current_options = get_option($this->option_name);
        if(!empty($input['license']) && $current_options['license'] != $input['license']){
            $api_params = array(
                'edd_action'=> 'activate_license',
                'license' 	=> $input['license'],
                'item_name' => urlencode('WP OAuth License'),
                'url'       => home_url()
            );
            $response = wp_remote_get( add_query_arg( $api_params, 'http://wp-oauth.com' ) );
            if ( !is_wp_error( $response ) ){
                $license_data = json_decode( wp_remote_retrieve_body( $response ) );
                $input['license_status'] = $license_data->license;
            }
        }elseif($input['license'] == ''){
            $input['license_status'] = '';
        }else {
            $input['license_status'] = $current_options['license_status'];
        }


        return $input;
    }
}
WPOAuth_Admin::init();