<?php
defined('ABSPATH') or die("you do not have acces to this page!");

if (!class_exists('CMPLZ_SL_Plugin_Updater')) {
    // load our custom updater
    include(dirname(__FILE__) . '/EDD_SL_Plugin_Updater.php');
}

if (!class_exists("cmplz_license")) {
    class cmplz_license
    {
        private static $_this;
        public $product_name;
        public $website;
        public $author;

        function __construct()
        {
            if (isset(self::$_this))
	            wp_die(sprintf('%s is a singleton class and you cannot create a second instance.', get_class($this)));

            self::$_this = $this;

            $this->product_name = 'Complianz GDPR premium';
            $this->website = 'https://complianz.io';
            $this->author = 'Complianz';

            add_action('admin_init', array($this, 'plugin_updater'), 0);
            add_action('admin_init', array($this, 'activate_license'), 10, 3);
            add_action('admin_init', array($this, 'register_option'), 20, 3);

            add_action('admin_init', array($this, 'deactivate_license'), 30, 3);

            add_action('wp_ajax_cmplz_dismiss_license_notice', array($this, 'dismiss_license_notice'));
            add_action("admin_notices", array($this, 'show_notice_license'));
            add_action('cmplz_admin_menu', array($this, 'admin_menu'), 40, 1);
        }

        static function this()
        {
            return self::$_this;
        }

        public function admin_menu(){
            if (!cmplz_user_can_manage()) return;

            add_submenu_page(
                'complianz',
                __('License', 'complianz-gdpr'),
                __('License', 'complianz-gdpr'),
                'manage_options',
                "cmplz-license",
                array($this, 'license_page')
            );
        }

        public function show_notice_license()
        {
            $screen = get_current_screen();
            if ( $screen->parent_base === 'edit' ) return;

            add_action('admin_print_footer_scripts', array($this, 'dismiss_license_notice_script'));
            $dismissed = get_option('cmplz_license_notice_dismissed');
            $link_open = '<a href="'.admin_url('admin.php?page=cmplz-license').'">';
            $link_open_purchase = '<a target="blank" href="https://complianz.io/pricing">';
            if (!$this->license_is_valid() && !$dismissed) { ?>
                <div id="message" class="error fade notice is-dismissible cmplz-dismiss-notice really-simple-plugins">
                    <p>
                        <?php echo __("You haven't activated your Complianz Privacy Suite premium license yet. To get all future updates, enter your license on the settings page.", 'complianz-gdpr'); ?>
                        <?php printf(__("Go to the %ssettings page%s or %spurchase a license%s", 'complianz-gdpr'), $link_open, '</a>', $link_open_purchase, '</a>'); ?>
                    </p>
                </div>
                <?php
            }
        }

        /**
         * Process the ajax dismissal of the success message.
         *
         * @since  2.0
         *
         * @access public
         *
         */

        public function dismiss_license_notice()
        {
            check_ajax_referer('cmplz-dismiss-license-notice', 'nonce');
            update_option('cmplz_license_notice_dismissed', true);
            wp_die();
        }

        public function dismiss_license_notice_script()
        {
            $ajax_nonce = wp_create_nonce("cmplz-dismiss-license-notice");
            ?>
            <script type='text/javascript'>
                jQuery(document).ready(function ($) {

                    $(".cmplz-dismiss-notice.notice.is-dismissible").on("click", ".notice-dismiss", function (event) {

                        var data = {
                            'action': 'cmplz_dismiss_license_notice',
                            'nonce': '<?php echo $ajax_nonce; ?>'
                        };

                        $.post(ajaxurl, data, function (response) {

                        });
                    });
                });
            </script>
            <?php
        }



        public function plugin_updater()
        {
            // retrieve our license key from the DB
            $license_key = trim(get_option('cmplz_license_key'));

            // setup the updater
            $edd_updater = new CMPLZ_SL_Plugin_Updater($this->website, cmplz_plugin_file, array(
                    'version' => cmplz_version,                // current version number
                    'license' => $license_key,        // license key (used get_option above to retrieve from DB)
                    'item_id' => 994,       // ID of the product
                    'author' => $this->author,  // author of this plugin
                )
            );
        }


        public function license_page()
        {
            //retrieve latest license date first.
            $license_data = $this->get_latest_license_data();

            $license = get_option('cmplz_license_key');
            $status = get_transient('cmplz_license_status');
            $deactivated = get_option('cmplz_deactivated');
            $expires = get_option('cmplz_license_expires');
            ?><div class="wrap"><?php
            echo "<h1>".__("License",'complianz-gdpr')."</h1>";

            //expired, revoked, missing, invalid, site_inactive, item_name_mismatch, no_activations_left
            $message = $this->get_error_message($license_data);

            if ($license_data && ($status==='valid' || $license_data->license == 'site_inactive') && $license_data->activations_left==0){
                $upgrade = $license_data->license_limit==1 ? __("a 5 sites or unlimited sites license", 'complianz-gdpr') : __("an unlimited sites license", 'complianz-gdpr');

                if ($license_data->license_limit> 0) {
                    cmplz_notice(sprintf(__('You have 0 activations left on your %s sites license. If you need more activations you can upgrade your current license to %s on your %saccount%s', 'complianz-gdpr'), $license_data->license_limit, $upgrade, '<a target="_blank"  href="https://complianz.io/account">', '</a>'), 'warning');
                }
            }

            if ($message) {
                cmplz_notice($message,'warning');
            } elseif ($deactivated){
                if ($status=='valid'){
                    cmplz_notice(__("Your license is valid, but not activated on this site", 'complianz-gdpr'));
                } elseif(!empty($status)){
                    cmplz_notice(__("Your license does not seem to be valid. Please check your license key", 'complianz-gdpr'));
                }

            } elseif ($status == 'valid') {
                cmplz_notice(sprintf(__("Your license is valid, and expires on: %s", 'complianz-gdpr'), $expires));
            } else {
                cmplz_notice(__("Enter your license here so you keep receiving updates and support.", 'complianz-gdpr'));
            }


            ?>
            <form method="post" action="options.php">
                <?php wp_nonce_field('cmplz_nonce', 'cmplz_nonce'); ?>
                <?php settings_fields('cmplz_license'); ?>

                <table class="form-table">
                    <tbody>
                    <tr valign="top">
                        <th scope="row" valign="top">
                            <?php _e('License Key', 'complianz-gdpr'); ?>
                        </th>
                        <td>
                            <input id="cmplz_license_key" name="cmplz_license_key" type="password" class="regular-text"
                                   value="<?php esc_attr_e($license); ?>"/>
                        <?php if (false !== $license) { ?>
                            <?php if ($status && ($status == 'valid') && !$deactivated) { ?>
                                <span style="color:green;" class="description"><?php _e('active'); ?></span>
                                <input type="submit" class="button-secondary" name="cmplz_license_deactivate"
                                       value="<?php _e('Deactivate License'); ?>"/>
                            <?php } else { ?>
	                            <span style="color:red;" class="description"><?php _e('inactive'); ?></span>
	                            <input type="submit" class="button-secondary" name="cmplz_license_activate"
                                       value="<?php _e('Activate License'); ?>"/>

                            <?php } ?>
                        </td>
                    </tr>
                    <?php } else {
                        ?>
                        <label class="description"
                               for="cmplz_license_key"><?php _e('Enter your license key'); ?></label>
                        <?php
                    } ?>

                    </td>
                    </tr>

                    </tbody>
                </table>
                <?php submit_button(); ?>

            </form>

            <p>
                <?php printf(__("Complianz Privacy Suite includes GeoLite2 data created by MaxMind, available from %shttp://www.maxmind.com%s", 'complianz-gdpr'), '<a target="_blank" href="http://www.maxmind.com">','</a>')?>
            </p>
            </div>
            <?php
        }

        public function get_error_message($license_data){
            $link = '<a target="_blank" href="' . $this->website . '">';
            $support_link = '<a target="_blank" href="https://complianz.io/support">';
            $message = false;
            if ($license_data && $license_data->license =='invalid'){
                $message  = __("This is not a valid license", 'complianz-gdpr');
            } elseif ($license_data && ( false === $license_data->success )) {

                switch ($license_data->error) {
                    case 'expired':
                        $message = sprintf(__("Your license is expired. Please renew your license at %scomplianz.io%s", 'complianz-gdpr'), $link, '</a>');
                        break;
                    case 'revoked':
                        $message = sprintf(__("Your license has been revoked. Please contact %ssupport%s", 'complianz-gdpr'), $support_link, '</a>');
                        break;
                    case 'missing':
                        $message = sprintf(__("Your license could not be found in the database. Please contact %ssupport%s", 'complianz-gdpr'), $support_link, '</a>');
                        break;
                    case 'invalid':
                    case 'site_inactive':
                        $message = __("Your license has not yet been activated for this domain.", 'complianz-gdpr');
                        break;
                    case 'item_name_mismatch':
                        $message = __("Your license key appears to be invalid.", 'complianz-gdpr');
                        break;
                    case 'no_activations_left':
                        $message = sprintf(__("You have no activations left on your license. Please upgrade your license at %scomplianz.io%s", 'complianz-gdpr'), $link, '</a>');
                        break;
                }

            } elseif ($license_data && ( true === $license_data->success )) {
                switch ($license_data->license) {
                    case 'inactive':
                        $message = __("Your license is valid, but has not yet been activated for this domain.", 'complianz-gdpr');
                        break;
                }

                if (!defined('cmplz_premium_multisite') && is_multisite()){
                    $message = __("For a multisite environment you need the Complianz Privacy Suite multisite plugin", 'complianz-gdpr');
                }

            }elseif (!$license_data) {
                $message  = __("license data error", 'complianz-gdpr');
            }


            return $message;
        }

        public
        function register_option()
        {
            // creates our settings in the options table
            register_setting('cmplz_license', 'cmplz_license_key', array($this, 'sanitize_license'));
        }

        public
        function sanitize_license($new)
        {
            $old = get_option('cmplz_license_key');
            if ($old && $old != $new) {
                delete_transient('cmplz_license_status'); // new license has been entered, so must reactivate
            }
            return $new;
        }


        public
        function get_latest_license_data()
        {

            $license_data = false;
            // retrieve the license from the database
            $license = get_option('cmplz_license_key');

            // data to send in our API request
            $api_params = array(
                'edd_action' => 'check_license',
                'license' => $license,
                'item_name' => urlencode($this->product_name), // the name of our product in EDD
                'url' => home_url()
            );

            // Call the custom API.
            $args = array('timeout' => 15, 'sslverify' => true, 'body' => $api_params);
            $args = apply_filters('cmplz_license_verification_args', $args);

            $response = wp_remote_post($this->website, $args);

            // make sure the response came back okay
            if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
                $message = is_wp_error($response) ? $response->get_error_message() : __('An error occurred while updating the license data, please try again.');
            } else {
                $license_data = json_decode(wp_remote_retrieve_body($response));
                if ('valid' !== $license_data->license) {
                    delete_transient('cmplz_license_status');
                    //expired, revoked, missing, invalid, site_inactive, item_name_mismatch, no_activations_left
                } else {
                    $date = $license_data->expires;
                    $date = strtotime($date);
                    $date = date(get_option('date_format'), $date);
                    update_option('cmplz_license_expires', $date);
                    set_transient('cmplz_license_status', $license_data->license, MONTH_IN_SECONDS);
                    // $license_data->license will be either "deactivated" or "failed"
                    if ($license_data->license == 'deactivated') {
                        delete_transient('cmplz_license_status');
                    }
                }
            }

            return $license_data;
        }

        public
        function activate_license()
        {
            // listen for our activate button to be clicked
            if (isset($_POST['cmplz_license_key']) && isset($_POST['cmplz_nonce']) && (isset($_POST['submit']) || isset($_POST['cmplz_license_activate']))) {
                // run a quick security check
                if (!check_admin_referer('cmplz_nonce', 'cmplz_nonce'))
                    return; // get out if we didn't click the Activate button

                if (strlen($_POST['cmplz_license_key']) == 0 ){
                    return;
                }

                // retrieve the license from the posted data
                $license = sanitize_key(trim($_POST['cmplz_license_key']));
                update_option('cmplz_license_key', $license);

                // data to send in our API request
                $api_params = array(
                    'edd_action' => 'activate_license',
                    'license' => $license,
                    'item_name' => urlencode($this->product_name), // the name of our product in EDD
                    'url' => home_url()
                );

                // Call the custom API.
                $args = array('timeout' => 15, 'sslverify' => false, 'body' => $api_params);
                $args = apply_filters('cmplz_license_verification_args', $args);

                $response = wp_remote_post($this->website, $args);

                // make sure the response came back okay
                if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
                    $message = is_wp_error($response) ? $response->get_error_message() : __('An error occurred while updating the license data, please try again.');
                } else {
                    update_option('cmplz_deactivated', false);
                    $license_data = json_decode(wp_remote_retrieve_body($response));
                    $message = $this->get_error_message($license_data);
                    // Check if anything passed on a message constituting a failure
                    if ($message) {
                        $base_url = admin_url('admin.php?page=cmplz-license');
                        $redirect = add_query_arg(array('sl_activation' => 'false', 'message' => urlencode($message)), $base_url);
                        delete_transient('cmplz_license_status');
                        update_option('cmplz_deactivated', false);
                        wp_redirect($redirect);
                        exit();

                        //no errors found
                    } else {

                        if ($license_data->license == 'active' && (defined('cmplz_premium_multisite') || !is_multisite())) {
                            update_option('cmplz_license_expires', $license_data->expires);
                            set_transient('cmplz_license_status', $license_data->license, MONTH_IN_SECONDS);
                        }
                        // $license_data->license will be either "deactivated" or "failed"
                        if ($license_data->license == 'deactivated') {
                            delete_transient('cmplz_license_status');
                        }

                        wp_redirect(admin_url('admin.php?page=cmplz-license'));
                        exit();
                    }

                }



            }
        }


        /***********************************************
         * Illustrates how to deactivate a license key.
         * This will descrease the site count
         ***********************************************/


        public
        function deactivate_license()
        {

            // listen for our deactivate button to be clicked
            if (isset($_POST['cmplz_license_deactivate'])) {

                // run a quick security check
                if (!check_admin_referer('cmplz_nonce', 'cmplz_nonce'))
                    return; // get out if we didn't click the Activate button

                // retrieve the license from the database
                $license = trim(get_option('cmplz_license_key'));

                // data to send in our API request
                $api_params = array(
                    'edd_action' => 'deactivate_license',
                    'license' => $license,
                    'item_name' => urlencode($this->product_name), // the name of our product in EDD
                    'url' => home_url()
                );

                // Call the custom API.
                $response = wp_remote_post($this->website, array('timeout' => 15, 'sslverify' => false, 'body' => $api_params));

                // make sure the response came back okay
                if (is_wp_error($response))
                    return false;

                // decode the license data
                $license_data = json_decode(wp_remote_retrieve_body($response));

                // $license_data->license will be either "deactivated" or "failed"
                if ($license_data->license == 'deactivated') {
                    update_option('cmplz_deactivated', true);
                    delete_transient('cmplz_license_status');
                    delete_option('cmplz_license_notice_dismissed');
                }
            }
        }


        public
        function license_is_valid()
        {
            $status = get_transient('cmplz_license_status');
            $deactivated = get_option('cmplz_deactivated');
            if (!$status && !$deactivated) {
                $this->get_latest_license_data();
                $status = get_transient('cmplz_license_status');
            }

            if ($status && ($status == "valid")) return true;

            //check if any of the multisite sites has a valid license.
            //One with a valid license is enough.
            if (is_multisite()) {
                $sites = $this->get_sites_bw_compatible();
                foreach ($sites as $site) {
                    $this->switch_to_blog_bw_compatible($site);
                    if (is_main_site(get_current_blog_id())) {
                        $status = get_transient('cmplz_license_status');
                        if (!$status) {
                            $this->get_latest_license_data();
                            $status = get_transient('cmplz_license_status');
                        }
                    }

                    restore_current_blog(); //switches back to previous blog, not current, so we have to do it each loop

                    //but if it's true, we exit immediately.
                    if ($status && $status == "valid") {
                        return true;
                    }
                }
            }

            return false;

        }

//change deprecated function depending on version.

        public
        function get_sites_bw_compatible()
        {
            global $wp_version;
            $sites = ($wp_version >= 4.6) ? get_sites() : wp_get_sites();
            return $sites;
        }

        /*
                    The new get_sites function returns an object.

        */

        public
        function switch_to_blog_bw_compatible($site)
        {
            global $wp_version;
            if ($wp_version >= 4.6) {
                switch_to_blog($site->blog_id);
            } else {
                switch_to_blog($site['blog_id']);
            }
        }
    }
} //class closure
