<?php

// this is the URL our updater / license checker pings. This should be the URL of the site with EDD installed
define(
    'ADVANCED_GUTENBERG_AUTHOR_URL',
    'https://publishpress.com/' 
); // you should use your own CONSTANT name, and be sure to replace it throughout this file

// the download ID for the product in Easy Digital Downloads
define(
    'ADVANCED_GUTENBERG_DOWNLOAD_ID',
    98972 
); // you should use your own CONSTANT name, and be sure to replace it throughout this file

// the name of the product in Easy Digital Downloads
define(
    'ADVANCED_GUTENBERG_ITEM_NAME',
    'PublishPress Blocks Pro' 
); // you should use your own CONSTANT name, and be sure to replace it throughout this file

// the name of the settings page for the license input to be displayed
define('ADVANCED_GUTENBERG_LICENSE_PAGE', 'publishpress-license');

// Our custom page to redirect
// Default value to have the license pageas submenu for "Plugins" is ADVANCED_GUTENBERG_LICENSE_PAGE_URL
define('ADVANCED_GUTENBERG_LICENSE_PAGE_URL', 'admin.php?page=advgb_settings&tab=license');

if (! class_exists('PPB_AdvGutenbergPro_Plugin_Updater')) {
    include dirname(__FILE__) . '/plugin-updater-class.php';
}

/**
 * Initialize the updater. Hooked into `init` to work with the
 * wp_version_check cron job, which allows auto-updates.
 */
function advgb_pro_plugin_updater()
{
    // To support auto-updates, this needs to run during the wp_version_check cron job for privileged users.
    $doing_cron = defined('DOING_CRON') && DOING_CRON;
    if (! current_user_can('manage_options') && ! $doing_cron) {
        return;
    }

    // retrieve our license key from the DB
    $license_key = trim(get_option('advgb_pro_license_key'));

    // setup the updater
    $edd_updater = new PPB_AdvGutenbergPro_Plugin_Updater(
        ADVANCED_GUTENBERG_AUTHOR_URL,
        ADVANCED_GUTENBERG_PRO_PLUGIN_FILE,
        array(
            'version' => ADVANCED_GUTENBERG_PRO_VERSION,                    // current version number
            'license' => $license_key,             // license key (used get_option above to retrieve from DB)
            'item_id' => ADVANCED_GUTENBERG_DOWNLOAD_ID,       // ID of the product
            'author'  => 'PublishPress', // author of this plugin
            'beta'    => false,
        )
    );
}

add_action('init', 'advgb_pro_plugin_updater');

function advgb_pro_register_option()
{
    // creates our settings in the options table
    register_setting('advgb_pro_license', 'advgb_pro_license_key', 'advgb_pro_sanitize_license');
}

add_action('admin_init', 'advgb_pro_register_option');

function advgb_pro_sanitize_license($new)
{
    $old = get_option('advgb_pro_license_key');
    if ($old && $old != $new) {
        delete_option('advgb_pro_license_status'); // new license has been entered, so must reactivate
    }

    return $new;
}


/************************************
 * this illustrates how to activate
 * a license key
 *************************************/

function advgb_pro_activate_license()
{
    // listen for our activate button to be clicked
    if (isset($_POST['advgb_pro_license_activate'])) {
        // run a quick security check
        if (! check_admin_referer('advgb_pro_nonce', 'advgb_pro_nonce')) {
            return;
        } // get out if we didn't click the Activate button

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


        // data to send in our API request
        $api_params = array(
            'edd_action'  => 'activate_license',
            'license'     => $license,
            'item_name'   => urlencode(ADVANCED_GUTENBERG_ITEM_NAME), // the name of our product in EDD
            'item_id'     => ADVANCED_GUTENBERG_DOWNLOAD_ID,
            'url'         => home_url(),
            'environment' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'production',
        );

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

        // make sure the response came back okay
        if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            if (is_wp_error($response)) {
                $message = $response->get_error_message();
            } else {
                $message = __('An error occurred, please try again.');
            }
        } else {
            $license_data = json_decode(wp_remote_retrieve_body($response));

            if (false === $license_data->success) {
                switch ($license_data->error) {
                    case 'expired':
                        $message = sprintf(
                            __('Your license key expired on %s.'),
                            date_i18n(
                                get_option('date_format'),
                                strtotime($license_data->expires, current_time('timestamp')) 
                            )
                        );
                        break;

                    case 'disabled':
                    case 'revoked':
                        $message = __('Your license key has been disabled.');
                        break;

                    case 'missing':
                        $message = __('Invalid license.');
                        break;

                    case 'invalid':
                    case 'site_inactive':
                        $message = __('Your license is not active for this URL.');
                        break;

                    case 'item_name_mismatch':
                        $message = sprintf(
                            __('This appears to be an invalid license key for %s.'),
                            ADVANCED_GUTENBERG_ITEM_NAME 
                        );
                        break;

                    case 'no_activations_left':
                        $message = __('Your license key has reached its activation limit.');
                        break;

                    default:
                        $message = __('An error occurred, please try again.');
                        break;
                }
            }
        }

        // Check if anything passed on a message constituting a failure
        if (! empty($message)) {
            $base_url = admin_url(ADVANCED_GUTENBERG_LICENSE_PAGE_URL);
            $redirect = add_query_arg(
                array( 'sl_activation' => 'false', 'message' => urlencode($message) ),
                $base_url 
            );

            wp_redirect($redirect);
            exit();
        }

        // $license_data->license will be either "valid" or "invalid"

        update_option('advgb_pro_license_status', $license_data->license);
        wp_redirect(admin_url(ADVANCED_GUTENBERG_LICENSE_PAGE_URL));
        exit();
    }
}

add_action('admin_init', 'advgb_pro_activate_license');


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

function advgb_pro_deactivate_license()
{
    // listen for our activate button to be clicked
    if (isset($_POST['advgb_pro_license_deactivate'])) {
        // run a quick security check
        if (! check_admin_referer('advgb_pro_nonce', 'advgb_pro_nonce')) {
            return;
        } // get out if we didn't click the Activate button

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

        // data to send in our API request
        $api_params = array(
            'edd_action'  => 'deactivate_license',
            'license'     => $license,
            'item_name'   => urlencode(ADVANCED_GUTENBERG_ITEM_NAME), // the name of our product in EDD
            'item_id'     => ADVANCED_GUTENBERG_DOWNLOAD_ID,
            'url'         => home_url(),
            'environment' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'production',
        );

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

        // make sure the response came back okay
        if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            if (is_wp_error($response)) {
                $message = $response->get_error_message();
            } else {
                $message = __('An error occurred, please try again.');
            }

            $base_url = admin_url(ADVANCED_GUTENBERG_LICENSE_PAGE_URL);
            $redirect = add_query_arg(
                array( 'sl_activation' => 'false', 'message' => urlencode($message) ),
                $base_url 
            );

            wp_redirect($redirect);
            exit();
        }

        // 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') {
            delete_option('advgb_pro_license_status');
        }

        wp_redirect(admin_url(ADVANCED_GUTENBERG_LICENSE_PAGE_URL));
        exit();
    }
}

add_action('admin_init', 'advgb_pro_deactivate_license');


/************************************
 * this illustrates how to check if
 * a license key is still valid
 * the updater does this for you,
 * so this is only needed if you
 * want to do something custom
 *************************************/

function advgb_pro_check_license()
{
    global $wp_version;

    $license = trim(get_option('advgb_pro_license_key'));

    $api_params = array(
        'edd_action'  => 'check_license',
        'license'     => $license,
        'item_name'   => urlencode(ADVANCED_GUTENBERG_ITEM_NAME),
        'item_id'     => ADVANCED_GUTENBERG_DOWNLOAD_ID,
        'url'         => home_url(),
        'environment' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'production',
    );

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

    if (is_wp_error($response)) {
        return false;
    }

    $license_data = json_decode(wp_remote_retrieve_body($response));

    if ($license_data->license == 'valid') {
        echo 'valid';
        exit;
        // this license is still valid
    } else {
        echo 'invalid';
        exit;
        // this license is no longer valid
    }
}

/**
 * This is a means of catching errors from the activation method above and displaying it to the customer
 */
function advgb_pro_admin_notices()
{
    if (isset($_GET['sl_activation']) && ! empty($_GET['message'])) {
        switch ($_GET['sl_activation']) {
            case 'false':
                $message = urldecode($_GET['message']); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                $message = sanitize_text_field($message);
                ?>
                <div class="error">
                    <p><?php
                        echo $message; ?></p>
                </div>
                <?php
                break;

            case 'true':
            default:
                // Developers can put a custom success message here for when activation is successful if they way.
                break;
        }
    }
}

add_action('admin_notices', 'advgb_pro_admin_notices');
