<?php

namespace KaliForms\Inc\Backend\Views;

if (!defined('WPINC')) {
    die;
}
use KaliForms\Inc\Utils\Plugin_Updater;

/**
 * Class License_Page
 *
 * @package Inc\Backend\Views
 */
class License_Page
{
    /**
     * Currend endpoint
     *
     * @var string
     */
    public $api_url = 'https://www.kaliforms.com/';
    /**
     * Plugin slug
     *
     * @var string
     */
    protected $slug = 'kaliforms';
    /**
     * Extensions_Page constructor.
     */
    public function __construct()
    {
        add_action('wp', [$this, 'init']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_init', [$this, 'activate_license']);
        add_action('admin_init', [$this, 'deactivate_license']);
        add_action('admin_init', [$this, 'check_license']);
        add_action('admin_init', [$this, 'updater'], 0);
    }

    /**
     * Show an error message that license needs to be activated
     */
    public function init()
    {
        if ('valid' !== get_option('kaliforms_pro_license_status')) {
            if ((!isset($_GET['page']) || 'kaliforms-license' !== $_GET['page'])) {
                add_action('admin_notices', function () {
                    echo '<div class="error"><p>' .
                    sprintf(__('The KaliForms Pro license needs to be activated. %sActivate Now%s', 'kaliforms'), '<a href="' . admin_url('edit.php?post_type=kaliforms_forms&page=kaliforms-license') . '">', '</a>') . '</p></div>';
                });
            } else {
                add_action('admin_notices', function () {
                    echo '<div class="notice"><p>' .
                    sprintf(__('License key invalid. Need a license? %sPurchase Now%s', 'kaliforms'), '<a target="_blank" href="www.kaliforms.com/pricing">', '</a>') .
                        '</p></div>';
                });
            }
        }
    }

    public function updater()
    {
        // retrieve our license key from the DB
        $license = get_option('kaliforms_pro_license_key');
        $status = get_option('kaliforms_pro_license_status');

        // setup the updater
        new Plugin_Updater($this->api_url, KALIFORMS_PRO_PLUGIN_FILE,
            [
                'version' => KALIFORMS_PRO_VERSION,
                'license' => $license,
                'item_id' => 218,
                'author' => 'Kali Forms',
            ],
            [
                'license_status' => $status,
                'admin_page_url' => admin_url('edit.php?post_type=kaliforms_forms&page=kaliforms-license'),
                'purchase_url' => 'https://www.kaliforms.com/pricing',
                'plugin_title' => 'Kali Forms Pro',
            ]
        );
    }

    /**
     * Renders app
     */
    public function render_app()
    {
        $license = get_option('kaliforms_pro_license_key');
        $status = get_option('kaliforms_pro_license_status');
        ?>
		<div class="wrap">
        	<h2>Kali Forms Pro</h2>
	    	<?php settings_errors();?>
        	<form method="post" action="options.php">
			<?php settings_fields('kaliforms_license');?>
			<?php if ('valid' != get_option('kaliforms_pro_license_status')) {?>
                <p><?php echo esc_html(sprintf(__('Thank you for purchasing %s!  Please enter your license key below.', 'kaliforms'), 'Kali Forms Pro')); ?></p>
            <?php };?>
			<table class="form-table">
				<tbody>
	                <tr valign="top">
	                    <th scope="row" valign="top">
	                        <?php esc_html_e('License Key', 'kaliforms');?>
	                    </th>
						<td>
	                        <input id="kaliforms_pro_license_key" name="kaliforms_pro_license_key" type="text" class="regular-text" value="<?php esc_attr_e($license);?>" />
	                        <label class="description" for="kaliforms_pro_license_key"><?php esc_html_e('Enter your license key', 'kaliforms');?></label>
	                    </td>
					</tr>
					<tr valign="top">
	                    <th scope="row" valign="top">
	                        <?php esc_html_e('Activate License', 'kaliforms');?>
	                    </th>
						<td>
	                        <?php if ($status !== false && $status == 'valid') {?>
	                            <?php wp_nonce_field('kaliforms_license_nonce', 'kaliforms_license_nonce');?>
	                            <input type="submit" class="button-secondary" name="kaliforms_license_deactivate" value="<?php esc_html_e('Deactivate License', 'kaliforms');?>"/>
                                <span style="color:green;"><?php esc_html_e('active', 'kaliforms');?></span>
	                        <?php } else {
            					wp_nonce_field('kaliforms_license_nonce', 'kaliforms_license_nonce');?>
	                            <input type="submit" class="button-secondary" name="kaliforms_license_activate" value="<?php esc_html_e('Activate License', 'kaliforms');?>"/>
	                        <?php }?>
	                    </td>
					</tr>
                </tbody>
            </table>
			<p><?php echo sprintf(esc_html(__('Any questions or problems with your license? %sContact us%s!', 'kaliforms')), '<a href="https://www.kaliforms.com/contact-us" target="_blank">', '</a>'); ?></p>
        	</form>
		</div>
	<?php
}

    public function register_settings()
    {
        register_setting('kaliforms_license', 'kaliforms_pro_license_key', [$this, 'sanitize_license']);
    }

    public function sanitize_license($new)
    {
        $old = get_option('kaliforms_pro_license_key');
        if ($old && $old != $new) {
            delete_option('kaliforms_pro_license_key');
        }
        return $new;
    }

    public function activate_license()
    {
        if (isset($_POST['kaliforms_license_activate'])) {
            // run a quick security check
            if (!check_admin_referer('kaliforms_license_nonce', 'kaliforms_license_nonce')) {
                return;
            }
            // get out if we didn't click the Activate button
            // save the license key to the database
            update_option('kaliforms_pro_license_key', $_POST['kaliforms_pro_license_key']);
            // retrieve the license from the database
            $license = trim(get_option('kaliforms_pro_license_key'));
            // data to send in our API request
            $api_params = [
                'edd_action' => 'activate_license',
                'license' => $license,
                'item_id' => 218, // the name of our product in EDD
                'url' => home_url(),
            ];
            // Call the custom API.
            $response = wp_remote_post($this->api_url, ['timeout' => 15, 'sslverify' => false, 'body' => $api_params]);

            // make sure the response came back okay
            if (is_wp_error($response)) {
                add_settings_error(
                    'kaliforms_license',
                    'activate',
                    __('There was an error activating the license, please verify your license is correct and try again or contact support.', 'kaliforms')
                );
                return false;
            }
            // decode the license data
            $license_data = json_decode(wp_remote_retrieve_body($response));
            // $license_data->license will be either "valid" or "invalid"
            update_option('kaliforms_pro_license_status', $license_data->license);
            if ('valid' != $license_data->license) {
                add_settings_error(
                    'kaliforms_license',
                    'activate',
                    __('There was an error activating the license, please verify your license is correct and try again or contact support.', 'kaliforms')
                );
            }
        }
    }
    public function deactivate_license()
    {
        // listen for our activate button to be clicked
        if (isset($_POST['kaliforms_license_deactivate'])) {
            // run a quick security check
            if (!check_admin_referer('kaliforms_license_nonce', 'kaliforms_license_nonce')) {
                return;
            }
            // get out if we didn't click the Activate button
            // retrieve the license from the database
            $license = trim(get_option('kaliforms_pro_license_key'));
            // data to send in our API request
            $api_params = [
                'edd_action' => 'deactivate_license',
                'license' => $license,
                'item_id' => 218, // the name of our product in EDD
                'url' => home_url(),
            ];
            // Call the custom API.
            $response = wp_remote_post($this->api_url, ['timeout' => 15, 'sslverify' => false, 'body' => $api_params]);
            // make sure the response came back okay
            if (is_wp_error($response)) {
                add_settings_error(
                    'kaliforms_license',
                    'deactivate',
                    __('There was an error deactivating the license, please try again or contact support.', 'kaliforms')
                );
                return false;
            }
            // decode the license data
            $license_data = json_decode(wp_remote_retrieve_body($response));
            // $license_data->license will be either "deactivated" or "failed"
            if ('deactivated' == $license_data->license) {
                add_settings_error(
                    'kaliforms_license',
                    'deactivate',
                    __('License deactivated', 'kaliforms')
                );
                delete_option('kaliforms_pro_license_status');
            } else {
                add_settings_error(
                    'kaliforms_license',
                    'deactivate',
                    __('Unable to deactivate license, please try again or contact support.', 'kaliforms')
                );
            }
        }
    }
    public function check_license()
    {
        if (get_transient('kaliforms_pro_license_status_checking')) {
            return;
        }

        $license = trim(get_option('kaliforms_pro_license_key'));
        $api_params = [
            'edd_action' => 'check_license',
            'license' => $license,
            'item_id' => 218,
            'url' => home_url(),
        ];
        // Call the custom API.
        $response = wp_remote_post(
            $this->api_url,
            [
                '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') {
            delete_option('kaliforms_pro_license_status');
        }
        // Set to check again in 12 hours
        set_transient(
            'kaliforms_pro_license_status_checking',
            $license_data,
            (60 * 60 * 12)
        );
    }

    /**
     * Invoking the class will render the app
     */
    public function __invoke()
    {
        /**
         * Initiate an action before rendering the app div
         */
        do_action($this->slug . '_before_license_page_rendering');

        /**
         * Echo the container
         */
        $this->render_app();

        /**
         * Initiate an action after rendering the app div
         */
        do_action($this->slug . '_after_license_page_rendering');
    }
}
