<?php
/**
 * @author      Flycart (Alagesan)
 * @license     http://www.gnu.org/licenses/gpl-3.0.html
 * @link        https://www.flycart.org
 * */

namespace Wlpr\App\Helpers;
class License
{
    private $remote_license_url = "https://www.flycart.org/";
    public static $instance = null;
    private $plugin_slug = "loyalty-points-and-rewards";

    /**
     * License constructor.
     * @param array $config
     * @since 1.0.0
     */
    public function __construct($config = array())
    {
    }

    /**
     * instance of class
     * @param array $config
     * @return License|null
     * @since 1.0.0
     */
    public static function getInstance(array $config = array())
    {
        if (!self::$instance) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**
     * verify the license_key
     * @param $license_key
     * @return array
     * @since 1.0.0
     */
    function verifylicenseKey($license_key)
    {
        $current_status = 'invalid';
        update_option('wlpr_point_license_key_status', $current_status);
        update_option('wlpr_point_license_key', $license_key);
        if (!empty($license_key)) {
            $license_key_status = '';
            if(!Validation::validateLicenceKay($license_key)){
                $license_key_status = 'invalid';
            }
            if($license_key_status != 'invalid'){
                $license_key_status = $this->validateKey($license_key);
            }
            if ($license_key_status) {
                $current_status = $license_key_status;
            }
            if ($current_status == "invalid") {
                $response['license_key'] = false;
                $response['license_key_message'] = esc_html__('Please enter valid license key!', WLPR_TEXT_DOMAIN);
            } elseif ($current_status == "expired") {
                $response['license_key'] = false;
                $response['license_key_message'] = esc_html__('Your license key was expired!', WLPR_TEXT_DOMAIN);
            } else {
                $response['license_key'] = true;
                $response['license_key_message'] = esc_html__('Your license key validated successfully!', WLPR_TEXT_DOMAIN);
            }
        } else {
            $response['license_key'] = false;
            $response['license_key_message'] = esc_html__("Please enter license key!", WLPR_TEXT_DOMAIN);
        }
        update_option('wlpr_point_license_key_status', $current_status);
        return $response;
    }

    /**
     * Validate the license key
     * @param $key
     * @return bool|string
     * @since 1.0.0
     */
    function validateKey($key)
    {
        if (empty($key)) {
            return false;
        }
        $fields = array(
            'wpaction' => 'licensecheck',
            'wpslug' => urlencode($this->plugin_slug),
            'pro' => 0,
            'dlid' => $key
        );
        $response = $this->request('', $fields);
        $status = $this->validateResponse($response);
        if (!is_wp_error($status)) {
            $json = json_decode($response['body']);
            $current_status = 'invalid';
            if (is_object($json) && isset($json->license_check)) {
                $is_verified = (bool)$json->license_check;
                if ($is_verified) {
                    $current_status = 'active';
                }
            }
            return $current_status;
        }
        return false;
    }

    /**
     * get operation for Remote URL
     * @param $url
     * @param $need_domain_in_suffix
     * @param array $fields
     * @return array|bool|mixed|object|string
     * @since 1.0.0
     */
    function request($url, $fields = array(), $need_domain_in_suffix = true)
    {
        try {
            if (is_array($fields) && !empty($fields)) {
                $url = rtrim($url, '/');
                $url .= '?' . http_build_query($fields);
            }
            if ($need_domain_in_suffix)
                $url = $this->remote_license_url . $url;
            $response = wp_remote_get($url);
        } catch (\Exception $e) {
            $response = $e->getMessage();
        }
        return $response;
    }

    /**
     * Check curl is enbled or not
     * @return bool
     * @since 1.0.0
     */
    function isCurlEnabled()
    {
        return function_exists('curl_version');
    }

    /**
     * Check if $result is a successful update API response.
     *
     * @param array|\WP_Error $result
     * @return true|\WP_Error
     * @since 1.0.0
     */
    protected function validateResponse($result)
    {
        if (is_wp_error($result)) {
            /** @var \WP_Error $result */
            return new \WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
        }
        if (!isset($result['response']['code'])) {
            return new \WP_Error(
                'puc_no_response_code',
                'wp_remote_get() returned an unexpected result.'
            );
        }
        if ($result['response']['code'] !== 200) {
            return new \WP_Error(
                'puc_unexpected_response_code',
                'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
            );
        }
        if (empty($result['body'])) {
            return new \WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
        }
        return true;
    }

    /**
     * Update checker
     * @since 1.0.0
     */
    function initUpdateChecker()
    {
        $this->addHooks();
        $this->runUpdater();
    }

    /**
     * Add hooks
     * @since 1.0.0
     * */
    function addHooks()
    {
        //add_filter('puc_request_info_result-' . $this->plugin_slug, array($this, 'loadWlprPointDescription'), 10, 2);
        add_filter('in_plugin_update_message-' . plugin_basename(WLPR_PLUGIN_FILE), array($this, 'showExpiredLicenseMessage'), 10, 2);
    }

    /**
     * To run the updater
     * @since 1.0.0
     * */
    protected function runUpdater()
    {
        $update_url = $this->getUpdateURL();
        if ($update_url != '') {
            \Puc_v4_Factory::buildUpdateChecker(
                $update_url, WLPR_PLUGIN_FILE, $this->plugin_slug
            );
        }
    }

    /**
     * To get update URL
     *
     * @return string
     * @since 1.0.0
     * */
    protected function getUpdateURL()
    {
        $licence_key = $this->getLicenseKey();
        if (empty($licence_key)) {
            return NULL;
        }
        $fields = array(
            'wpaction' => 'updatecheck',
            'wpslug' => urlencode($this->plugin_slug),
            'pro' => 0,
            'dlid' => $licence_key
        );
        $update_url = $this->remote_license_url . 'update?' . http_build_query($fields);
        if ($licence_key == '') {
            add_action('admin_notices', array($this, 'enterLicenceKeyErrorNotice'));
            //return '';
        }
        return $update_url;
    }

    /**
     * @return mixed|void
     * @since 1.0.0
     */
    function getLicenseKey()
    {
        return get_option('wlpr_point_license_key', NULL);
    }

    /**
     * To display error message in admin page while there is no licence key
     * @since 1.0.0
     * */
    public function enterLicenceKeyErrorNotice()
    {
        $notice_on_for_user = get_user_meta(get_current_user_id(), 'dismissed_wlpr_point_admin_installed_notice', true);
        if (!$notice_on_for_user) {
            $htmlPrefix = '<div class="updated woocommerce-message"><p>';
            $htmlSuffix = '</p></div>';
            $msg = "<strong>";
            $msg .= __("WP Rewards - WooCommerce Loyalty Points and Rewards Builder installed", WLPR_TEXT_DOMAIN);
            $msg .= "</strong>";
            $msg .= __(" - Make sure to activate your copy of the plugin to receive updates, support and security fixes!", WLPR_TEXT_DOMAIN);
            $msg .= '<p>';
            $msg .= '<a href="' . $this->getSettingsPageUrl() . '" class="button-primary">';
            $msg .= __('Settings', WLPR_TEXT_DOMAIN);
            $msg .= '</a></p>';
            // $msg .= '<a href="' . esc_url(wp_nonce_url(add_query_arg('wlpr-hide-notice', 'installed'), 'wlpr_point_admin_hide_notices_nonce', '_wlpr_notice_nonce')) . '" class="wlpr-notice-a notice-dismiss"><span class="screen-reader-text">' . __('Dismiss this notice.', WLPR_TEXT_DOMAIN) . '</span></a>';
            echo $htmlPrefix . $msg . $htmlSuffix;
        }
    }

    /**
     * Get licence key
     * @since 1.0.0
     * */
    function getSettingsPageUrl()
    {
        return admin_url("admin.php?page=" . WLPR_PLUGIN_SLUG . "&view=settings");
    }

    /**
     * Message on plugin page when license is expired
     * @param $plugin_data
     * @param $response
     * @return mixed
     * @since 1.0.0
     */
    function showExpiredLicenseMessage($plugin_data, $response)
    {
        if (empty($response->package)) {
            echo "<br>";
            echo $this->getLicenseExpiredMessage();
        }
        return $plugin_data;
    }

    /**
     * get message on license expired
     * @return string
     * @since 1.0.0
     */
    function getLicenseExpiredMessage()
    {
        $msg = '';
        $licenseKey = $this->getLicenseKey();
        if ($licenseKey == '') {
            $upgrade_url = '<a href="' . $this->getSettingsPageUrl() . '">' . esc_html__('enter license key', WLPR_TEXT_DOMAIN) . '</a>';
            $msg .= sprintf(esc_html__('Please %s to receive automatic updates or you can manually update the plugin by downloading it.', WLPR_TEXT_DOMAIN), $upgrade_url);
        } else {
            $upgrade_url = '<a target="_blank" href="' . $this->getProductUrl() . '">' . esc_html__('renew your support license', WLPR_TEXT_DOMAIN) . '</a>';
            $msg .= sprintf(esc_html__('Please %s to receive automatic updates or you can manually update the plugin by downloading it.', WLPR_TEXT_DOMAIN), $upgrade_url);
        }
        return $msg;
    }

    /**
     * Get product URL
     * @since 1.0.0
     * */
    function getProductUrl()
    {
        return 'https://www.flycart.org/products/wordpress/loyalty-points-and-rewards-for-woocommerce';
    }

    /**
     * Check the given license is valid or not
     * @return bool
     */
    function isValidLicense()
    {
        $current_status = get_option('wlpr_point_license_key_status','invalid');
        $is_valid_license = ($current_status == "active");
        return apply_filters('wlpr_point_is_valid_license', $is_valid_license);
    }
}