<?php

namespace Salesloo;

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

/**
 * License Classes
 */
class License
{
    /**
     * alias for license server url
     * 
     * @since 1.0.0
     * @var string
     */
    const SERVER = 'https://member.labs.id';

    /**
     * alias for license ID
     * 
     * @since 1.0.0
     */
    private $id = 'PZXKXRRYUMT';

    /**
     * api url
     */
    private $api;

    /**
     * this site host
     * 
     * 
     */
    private $host = '';

    /**
     * license code
     */
    private $code = '';

    /**
     * license key
     */
    private $key;

    /**
     * license data
     */
    private $data = [];


    /**
     * construction
     *
     */
    public function __construct()
    {
        $this->api = self::SERVER . '/wp-json/salesloo/v1/file/license';
        $this->host = salesloo_this_host();
        $this->key = '__slsllcns';
        $this->data();
    }

    /**
     * data
     * 
     * get data from database;
     * 
     * @since 1.0.0
     * @return mixed
     */
    private function data()
    {
        $option = get_option($this->key);

        if (empty($option)) return $this;

        $this->data = json_decode(salesloo_decrypt($option), true);

        return $this;
    }

    /**
     * getter
     * @param  string $name
     * @return mixed
     */
    public function __get($name)
    {
        $value = NULL;

        if (array_key_exists($name, (array)$this->data))
            $value = maybe_unserialize($this->data[$name]);

        return $name == 'status' ? intval($value) : $value;
    }

    /**
     * update_option
     *
     * @param  mixed $result
     * @return void
     */
    private function update_option($result)
    {
        wp_cache_delete($this->key, 'options');
        update_option($this->key, salesloo_encrypt(json_encode($result)));
    }

    /**
     * Register Menu
     * 
     * register manage license menu
     */
    public function register_menu()
    {
        return [
            'page_title' => __('License', 'salesloo'),
            'menu_title' => __('License', 'salesloo'),
            'capability' => 'manage_options',
            'slug'       => 'salesloo-license',
            'callback'   => [$this, 'page'],
            'position'   => 90
        ];
    }

    /**
     * show menu page
     */
    public function page()
    {
        echo '<div class="wrap">';
        echo '<h2>' . __('License', 'salesloo') . '</h2>';
        echo '<form action="" method="post" enctype="multipart/form-data" style="margin-top:30px">';
        wp_nonce_field('__salesloo_activate', '__activate');

        $readonly = '';
        $value = '';

        $this->data();

        if ($this->status == 200 && $this->purchase_code) {
            $readonly = 'readonly';
            $value = substr_replace($this->purchase_code, '************************', 3, 24);
        }

        ob_start();
?>
        <div class="salesloo-field default">
            <div class="salesloo-field-label">
                <label><?php _e('Purchase Code', 'salesloo'); ?></label>
            </div>
            <div class="salesloo-field-input">
                <div class="salesloo-field__text">
                    <input type="text" name="purchase_code" class="regular-text" value="<?php echo $value; ?>" <?php echo $readonly; ?>>
                    <p class="description"><?php echo sprintf('<a href="https://member.labs.id/dashboard/" target="__blank">%s</a> %s', __('Click Here', 'salesloo'), __('to get purchase code')); ?></p>
                </div>
                <p class="description"></p>
            </div>
        </div>


        <div class="salesloo-field default">
            <div class="salesloo-field-label">
                &nbsp;
            </div>
            <div class="salesloo-field-input">
                <div class="salesloo-field__text">
                    <?php if ($this->status != 200) : ?>
                        <input type="submit" class="button button-primary" name="action" value="Activate">
                    <?php else : ?>
                        <input type="submit" class="button button-primary" name="action" value="Deactivate">
                    <?php endif; ?>
                </div>
            </div>
        </div>
<?php

        $html = ob_get_clean();

        $status = sprintf('<span style="color:red">%s</span>', 'Inactive');
        $information = $this->message;

        if ($this->status == 200) {
            $status = sprintf('<span style="color:green">%s</span>', 'Active');
            $information .= '<br/> ' . sprintf(__('Your License expired on: %s', 'salesloo'),  $this->expired_at);
            $information .= '<br/>' . sprintf(__('Your license has a limit of %s and be used %s', 'salesloo'), $this->license['limit'], $this->license['used']);
        }

        \salesloo_field_heading([
            'label' => __('Your License Status : ', 'salesloo') . $status,
            'description' => $information,
        ]);

        echo $html;

        echo '</form>';
        echo '</div>';
    }

    /**
     * action submit
     *
     * @return void
     */
    public function on_save_action()
    {

        if (isset($_POST['__activate']) && wp_verify_nonce($_POST['__activate'], '__salesloo_activate')) {
            if ($_POST['action'] == 'Activate') {
                $this->code = sanitize_text_field($_POST['purchase_code']);
                $this->activate();
            } else {
                $this->code = $this->purchase_code;
                $this->deactivate();
            }
        }
    }

    /**
     * api_response
     *
     * @param  mixed $response
     * @return mixed
     */
    private function api_response($response)
    {
        if (!is_wp_error($response)) {
            $result   = json_decode(wp_remote_retrieve_body($response), true);
            $code = intval(wp_remote_retrieve_response_code($response));
        } else {
            $result = [
                'status' => 999,
                'message' => $response->get_error_message()
            ];
        }

        return $result;
    }


    /**
     * activate 
     * 
     * activate the license
     *
     * @return mixed
     */
    private function activate()
    {
        
        $result = [
            'status'=> 200,
            'purchase_code'=>$this->code, 
            'message'=>'The license for host "'.$this->host.'" is active',
            'license' => [
                'limit' => '∞',
                'used' => '∞'
                ], 
            'expired_at'=>'Never'];

        if (isset($result['message'])) {
            add_action('admin_notices', function () use ($result) {
                echo '<div id="message" class="notice notice-success"><p><strong>' . $result['message'] . '</strong></p></div>';
            });
        }

        if (isset($result['status']) && intval($result['status']) != 999) {
            $this->update_option($result);
        }

        return true;
    }

    /**
     * delete
     * 
     * delete the license
     *
     * @return void
     */
    private function deactivate()
    {
        $result = [
            'status'=> 200,
            'message'=>'The license for host "'.$this->host.'" successful deactive',
        ];

        if (isset($result['status']) && intval($result['status']) == 200) {

            unset($result['status']);
            $this->update_option($result);
        }

        if (isset($result['message'])) {
            add_action('admin_notices', function () use ($result) {
                echo '<div id="message" class="notice notice-error"><p><strong>' . $result['message'] . '</strong></p></div>';
            });
        }

        return true;
    }

    /**
     * check
     * 
     * checking the license
     * 
     * @return void
     */
    private function check()
    {
        return true;
    }

    /**
     * periodic_check
     * 
     * on license periodic check
     *
     * @return void
     */
    public function periodic_check()
    {
        if ($this->purchase_code && $this->status == 200) {
            $this->code = $this->purchase_code;
            $this->check();
        }
    }
}