<?php

use MemberPress\GroundLevel\Mothership\AbstractPluginConnection;
use MemberPress\GroundLevel\Mothership\Api\Request\LicenseActivations;
use MemberPress\GroundLevel\Mothership\Credentials;
use MemberPress\GroundLevel\Mothership\Manager\LicenseManager;

if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

/**
 * MeprUpdateCtrl
 *
 * License management and activation are now handled by ground-level-mothership.
 * This controller only retains some legacy helpers along with the related admin
 * notices and settings UI. The plugin update mechanisms retained for backward
 * compatibility are kept in MeprPluginUpdaterCtrl so that WP.org-hosted editions
 * can exclude them, since those editions receive updates from WordPress.org
 * rather than the Mothership.
 */
class MeprUpdateCtrl extends MeprBaseCtrl
{
    /**
     * Load hooks for the update controller.
     *
     * @return void
     */
    public function load_hooks()
    {
        add_action('admin_notices', 'MeprUpdateCtrl::activation_warning');
        add_action('admin_init', 'MeprUpdateCtrl::activate_from_define');
        add_action('mepr_display_general_options', [$this,'display_options'], 99);
        add_action('mepr_process_options', [$this, 'store_options']);
    }

    /**
     * Display the options for the update controller.
     *
     * @return void
     */
    public function display_options()
    {
        $mepr_options = MeprOptions::fetch();
        MeprView::render('admin/auto-updates/option', get_defined_vars());
    }

    /**
     * Store the options for the update controller.
     *
     * @return void
     */
    public function store_options()
    {
        $mepr_options               = MeprOptions::fetch();
        $name                       = $mepr_options->auto_updates_str;
        $mepr_options->auto_updates = isset($_POST[$name]) ? sanitize_text_field(wp_unslash($_POST[$name])) : false;
        $mepr_options->store(false);
    }

    /**
     * Check if the MemberPress plugin is activated.
     *
     * @return boolean True if activated, false otherwise.
     */
    public static function is_activated()
    {
        return memberpress()->container()->get(AbstractPluginConnection::class)->getLicenseActivationStatus();
    }

    /**
     * Activate the license from a defined constant.
     *
     * @return void
     */
    public static function activate_from_define()
    {
        if (!defined('MEMBERPRESS_LICENSE_KEY')) {
            return;
        }

        $license_key = memberpress()->container()->get(Credentials::class)->getLicenseKey();
        $domain      = memberpress()->container()->get(Credentials::class)->getDomain();

        if ($license_key === MEMBERPRESS_LICENSE_KEY) {
            return;
        }

        if ($license_key) {
            memberpress()->container()->get(LicenseActivations::class)->deactivate($license_key, $domain);
        }

        $activation = memberpress()->container()->get(LicenseManager::class)->activateLicense(MEMBERPRESS_LICENSE_KEY, $domain);

        if ($activation->isSuccess()) {
            $message  = $activation->getMessage();
            $view     = '/admin/errors';
            $callback = function () use ($view, $message) {
                return MeprView::render($view, compact('message'));
            };
        } else {
            $view     = '/admin/update/activation_warning';
            $error    = $activation->getMessage();
            $callback = function () use ($view, $error) {
                return MeprView::render($view, compact('error'));
            };
        }

        add_action('admin_notices', $callback);
    }

    /**
     * Send a request to the Mothership API.
     *
     * @param string  $endpoint The API endpoint.
     * @param array   $args     Optional. The request arguments. Default empty array.
     * @param string  $method   Optional. The HTTP method to use. Default 'get'.
     * @param boolean $blocking Optional. Whether the request should block. Default true.
     *
     * @return array|boolean The response array or true if not blocking.
     *
     * @throws Exception If there is an error with the request.
     *
     * @deprecated
     */
    public static function send_mothership_request($endpoint, $args = [], $method = 'get', $blocking = true)
    {
        _deprecated_function(__METHOD__, '1.12.16');

        $domain       = defined('MEPR_MOTHERSHIP_DOMAIN') ? MEPR_MOTHERSHIP_DOMAIN : 'https://mothership.caseproof.com';
        $mepr_options = MeprOptions::fetch();
        $uri          = "{$domain}{$endpoint}";

        $arg_array = [
            'method'    => strtoupper($method),
            'body'      => $args,
            'timeout'   => 15,
            'blocking'  => $blocking,
            'sslverify' => $mepr_options->sslverify,
        ];

        $resp = wp_remote_request($uri, $arg_array);

        // If we're not blocking then the response is irrelevant
        // So we'll just return true.
        if ($blocking === false) {
            return true;
        }

        if (is_wp_error($resp)) {
            throw new Exception(esc_html__('You had an HTTP error connecting to Caseproof\'s Mothership API', 'memberpress'));
        } else {
            $json_res = json_decode($resp['body'], true);
            if (null !== $json_res) {
                if (isset($json_res['error'])) {
                    throw new Exception(esc_html($json_res['error']));
                } else {
                    return $json_res;
                }
            } else {
                throw new Exception(esc_html__('Your License Key was invalid', 'memberpress'));
            }
        }

        return false;
    }

    /**
     * Display an activation warning if the license is not activated.
     *
     * @return void
     */
    public static function activation_warning()
    {
        $license_key = memberpress()->container()->get(Credentials::class)->getLicenseKey();

        if (
            empty($license_key) &&
            (!isset($_REQUEST['page']) ||
            !($_REQUEST['page'] === 'memberpress-options' ||
            (!self::is_activated() && $_REQUEST['page'] === 'memberpress')))
        ) {
            MeprView::render('/admin/update/activation_warning', get_defined_vars());
        }
    }
}
