<?php

/**
 * Activation Manager
 *
 * @package     Retheme
 * @category    Core
 * @author      Webforia Studio
 * @version     1.0.0
 */

namespace Retheme;

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

// No need to proceed if this class already exists.
class Activation {
    public $product_name = '';
    public $product_slug = '';
    public $product_key = '';
    public $product_ref = '';
    public $domain = '';

    public function __construct($args = array()) {
        $this->product_name = RT_THEME_NAME;
        $this->product_slug = RT_THEME_SLUG;
        $this->product_key = !empty($args['product_key']) ? $args['product_key'] : get_option("{$this->product_slug}_key");
        $this->domain = preg_replace('#^https?://(?:www\.)?#', '', site_url());

        add_action('upgrader_process_complete', [$this, 'check_license'], 10, 2);
        add_action('after_switch_theme', [$this, 'check_license'], 10, 2);
    }
    /**
     * Server host license
     *
     * request serverhost without cache
     * @param [type] $action action from server     c, activate, deactivate
     * @param [type] $license_key key user
     * @return json responve
     */
    public function license_manager($action) {

        // request serverhost without cache
        $serverhost = "https://webforia.id/?time=" . time();
        $secret_key = "5c0a2dd7949698.97710041s";

        // API query parameters
        $api_params['slm_action'] = "slm_{$action}";
        $api_params['secret_key'] = $secret_key;
        $api_params['license_key'] = $this->product_key;
        $api_params['registered_domain'] = $this->domain;
        $api_params['item_reference'] = $this->product_name;

        // Send query to the license manager server
        $query = esc_url_raw(add_query_arg($api_params, $serverhost));
        $response = wp_remote_get($query, array('timeout' => 100, 'sslverify' => false));

        // Check for error in the response
        if (is_wp_error($response)) {
            echo __("Unexpected Error! The query returned with an error. Please check your internet connection", 'bagus-core');
        }

        // License data.
        return json_decode(wp_remote_retrieve_body($response));
    }

    /**
     * Get max domain for a domain
     *
     * @return number
     */
    public function max_allowed_domains() {
        $license = $this->license_manager('check');
        return $license->max_allowed_domains;
    }

    /**
     * Check active domain
     *
     * @return void
     */
    public function registered_domains() {
        $license = $this->license_manager('check');

        $data = '';

        if ($license->result !== 'error') {
            $data = $license->registered_domains;
        }

        return $data;
    }

    /**
     * Check domain active on license
     *
     * @param [type] $domain domain check
     * @return boolean
     */
    public function has_domain($site_url = '') {

        // Remove "www" and "http/https" prefixes from the URL
        $base_domain = preg_replace('#^https?://(?:www\.)?#', '', $site_url);

        $domains = $this->registered_domains();

        // Get all domain to array
        $domain_register = array();

        if ($domains) {
            foreach ($domains as $key => $domain) {
                $domain_register[] = $domain->registered_domain;
            }
        }

        // Find domain from array registered domains
        return in_array($base_domain, $domain_register);
    }

    /**
     * Get license status from option db
     * active, unregistered, expired, trial
     * @return void
     */
    public function status() {
        $product_status = "{$this->product_slug}_status";

        if (!empty(get_option($product_status))) {
            $status = get_option($product_status);
        } else {
            $status = 'Unregistered';
        }

        return $status;
    }

    /**
     * Check if user is only running the product’s Premium Version code
     */
    public function is_premium() {
        if (in_array($this->status(), ['active', 'trial', 'expired']) || $this->is_local()) {
            return true;
        }
    }

    /**
     * Check if user is only running the product’s Premium Version code
     */
    public function is_trial() {
        if ($this->status() === 'trial') {
            return true;
        }
    }

    /**
     * Check product register for this license key
     *
     * @return bolean
     */
    public function check_product() {
        $license = $this->license_manager('check');

        if (!empty($license->product_ref)) {

            // Menemukan variasi produk dari nama
            // menemukan variasi dari nama
            // contoh: nama produk - variasi
            $product_ref = explode(' - ', $license->product_ref);

            // cek variation
            $product = !empty($product_ref[0]) ? $product_ref[0] : $license->product_ref;

            // get product name
            // remove spacing from product name
            // Text to lowecase
            $product_slug = str_replace(" ", "-", strtolower($product));

            if ($product_slug === $this->product_slug) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Get product varian
     *
     * @param [type] $variation
     * @return void
     */
    public function is_product_variation($variation) {
        $product_variation = "{$this->product_slug}_product_variation";

        if (get_option($product_variation) == $variation) {
            return true;
        }
    }

    /**
     * Deactive license for current domain
     *
     * @return void
     */
    public function deactivate() {

        $license = $this->license_manager('deactivate');
        $product_status = "{$this->product_slug}_status";
        $product_key = "{$this->product_slug}_key";

        // set option
        update_option($product_status, 'unregistered');
        update_option($product_key, '');

        $data['result'] = $license->result;
        $data['message'] = $license->message;

        return $data;
    }

    /**
     * Activated license for current domain
     *
     * @return void
     */
    public function activate() {
        $product_status = "{$this->product_slug}_status";
        $product_key = "{$this->product_slug}_key";
        $product_date_expired = "{$this->product_slug}_date_expired";
        $product_date_created = "{$this->product_slug}_date_created";
        $product_date_renewed = "{$this->product_slug}_date_renewed";
        $product_variation = "{$this->product_slug}_product_variation";
        $product_update = "{$this->product_slug}_product_update";

        // check product license
        if ($this->check_product()) {

            $license = $this->license_manager('check');

            if ($license->result !== 'error') {

                // set status
                $set_stats = $this->license_manager('activate');

                // set product varian
                // get product varian from title produk
                $product_slug = str_replace(" ", "", strtolower($license->product_ref));
                $variation = explode("-", $product_slug);

                // set option
                update_option($product_status, 'active');
                update_option($product_update, true);
                update_option($product_key, $license->license_key);
                update_option($product_date_created, $license->date_created);
                update_option($product_date_renewed, $license->date_renewed);
                update_option($product_date_expired, $license->date_expiry);
                update_option($product_variation, '');

                if (!empty($variation[1])) {
                    update_option($product_variation, trim($variation[1]));
                }

                // Set status trial
                if ($this->is_product_variation('trial')) {
                    update_option($product_status, 'trial');
                }

                // Set status expired
                if ($this->get_expired_date_duration() < 1) {
                    update_option($product_status, 'expired');
                    update_option($product_update, false);
                }

                // Set status expired
                if ($this->is_product_variation('trial') && $this->get_expired_date_duration() < 1) {
                    update_option($product_status, 'trial expired');
                }
            }

            $data['result'] = $license->result;
            $data['message'] = $license->message;
        } else {
            $data['result'] = 'error';
            $data['message'] =  wp_sprintf(__('License not valid or %s not register for this license'), $this->product_name);;
        }

        return $data;
    }

    /**
     * Check domain aviable on server
     */
    public function check_license() {
        if ($this->is_premium() && !$this->has_domain(site_url())) {
            $this->deactivate();
        }
    }

    /**
     * Date license create
     *
     * @return void
     */
    public function get_date_create($format = '') {
        $date = get_option("{$this->product_slug}_date_created");

        if ($format) {
            $date = date("d F Y", strtotime($date));
        }

        return $date;
    }

    /**
     * Get date expired
     *
     * @return void
     */
    public function get_expired_date($format = '') {
        $date = get_option("{$this->product_slug}_date_expired");

        if ($format) {
            $date = date("d F Y", strtotime($date));
        }

        return $date;
    }

    /**
     * Date expiry conditional
     */
    public function get_expired_date_duration() {

        $now = strtotime('now');
        $end = strtotime($this->get_expired_date());
        $number_days = ($end - $now) / (60 * 60 * 24);

        return round($number_days);
    }

    /**
     * Local server running
     *
     * Check if user is only running the product’s on localhost
     * @return boolean
     */
    public function is_local() {

        return false;
        // $site = $this->domain;

        // $local = array(
        //     'localhost',
        //     '127.0.0.1',
        //     '10.0.0.0/8',
        //     '172.16.0.0/12',
        //     '192.168.0.0/16',
        // );

        // if (in_array($site, $local)) {
        //     return true;
        // }

        // // Check local or stage server
        // preg_match_all('/\b(?:\.local|dev\.|staging\.)\b/', $site, $matches);

        // if (!empty($matches[0])) {
        //     return true;
        // }
    }
}

new Activation;
