<?php
/**
 * Licfy Client Example
 *
 * Drop-in license protection for a THIRD-PARTY plugin or theme (i.e. a product you
 * sell that is protected by your own Licfy install). Copy this file into your
 * product, rename the class/prefix, fill in the 3 constants below, and call
 * Licfy_Client_Example::init() from your main plugin/theme file.
 *
 * This file does NOT belong to Licfy itself - it is the code a seller embeds
 * inside the product they are protecting, running on their customer's site.
 *
 * @package YourPluginName
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // No direct access.
}

class Licfy_Client_Example {

    /**
     * Base URL of the Licfy install that sells/manages licenses for this product
     * (your own site running the Licfy plugin), e.g. https://your-site.com/api/licfy/v1
     */
    const API_BASE = 'https://your-licfy-site.com/api/licfy/v1';

    /**
     * Your Licfy API token (Licfy -> API Token in your WP admin). Identifies
     * YOU as the seller - never expose this to customers or in JS.
     */
    const API_TOKEN = 'YOUR_LICFY_API_TOKEN';

    /**
     * The exact product slug you registered under Licfy -> Products.
     */
    const PRODUCT_SLUG = 'my-awesome-plugin';

    /** wp_options key used to store the customer's entered license key. */
    const OPTION_LICENSE_KEY = 'my_plugin_license_key';

    /** transient key used to cache the last verification result. */
    const TRANSIENT_STATUS = 'my_plugin_license_status';

    /**
     * Wire up the settings page and the activate/deactivate handlers.
     */
    public static function init() {
        add_action( 'admin_menu', array( __CLASS__, 'register_settings_page' ) );
        add_action( 'admin_post_my_plugin_activate_license', array( __CLASS__, 'handle_activate' ) );
        add_action( 'admin_post_my_plugin_deactivate_license', array( __CLASS__, 'handle_deactivate' ) );
        add_action( 'admin_notices', array( __CLASS__, 'maybe_show_inactive_notice' ) );
    }

    /**
     * Settings > My Plugin License page with the key input + activate/deactivate form.
     */
    public static function register_settings_page() {
        add_options_page(
            __( 'My Plugin License', 'my-plugin' ),
            __( 'My Plugin License', 'my-plugin' ),
            'manage_options',
            'my-plugin-license',
            array( __CLASS__, 'render_settings_page' )
        );
    }

    public static function render_settings_page() {
        $license_key = get_option( self::OPTION_LICENSE_KEY, '' );
        $is_active   = self::is_active();
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'My Plugin License', 'my-plugin' ); ?></h1>

            <p>
                <?php if ( $is_active ) : ?>
                    <span style="color:#0a7d2c;font-weight:600;">&#10003; <?php esc_html_e( 'License active', 'my-plugin' ); ?></span>
                <?php else : ?>
                    <span style="color:#d92d20;font-weight:600;"><?php esc_html_e( 'License not active', 'my-plugin' ); ?></span>
                <?php endif; ?>
            </p>

            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                <input type="hidden" name="action" value="<?php echo $is_active ? 'my_plugin_deactivate_license' : 'my_plugin_activate_license'; ?>" />
                <?php wp_nonce_field( 'my_plugin_license_nonce' ); ?>

                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="my_plugin_license_key"><?php esc_html_e( 'License Key', 'my-plugin' ); ?></label></th>
                        <td>
                            <input type="text" id="my_plugin_license_key" name="license_key" class="regular-text"
                                value="<?php echo esc_attr( $license_key ); ?>" placeholder="<?php esc_attr_e( 'Paste your license key here', 'my-plugin' ); ?>"
                                <?php disabled( $is_active ); ?> />
                        </td>
                    </tr>
                </table>

                <?php submit_button( $is_active ? __( 'Deactivate License', 'my-plugin' ) : __( 'Activate License', 'my-plugin' ) ); ?>
            </form>
        </div>
        <?php
    }

    /**
     * Handles the "Activate License" form submission.
     */
    public static function handle_activate() {
        check_admin_referer( 'my_plugin_license_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to do this.', 'my-plugin' ) );
        }

        $license_key = isset( $_POST['license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['license_key'] ) ) : '';
        update_option( self::OPTION_LICENSE_KEY, $license_key );

        // Force a fresh check against Licfy instead of using any cached result.
        delete_transient( self::TRANSIENT_STATUS );
        $result = self::verify( $license_key );

        $notice = ( ! empty( $result['license_status'] ) && 'valid' === $result['license_status'] )
            ? 'activated'
            : 'failed';

        wp_safe_redirect( add_query_arg( 'my_plugin_license', $notice, wp_get_referer() ) );
        exit;
    }

    /**
     * Handles the "Deactivate License" form submission (clears local state only).
     */
    public static function handle_deactivate() {
        check_admin_referer( 'my_plugin_license_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to do this.', 'my-plugin' ) );
        }

        delete_option( self::OPTION_LICENSE_KEY );
        delete_transient( self::TRANSIENT_STATUS );

        wp_safe_redirect( add_query_arg( 'my_plugin_license', 'deactivated', wp_get_referer() ) );
        exit;
    }

    /**
     * Calls the Licfy /verify endpoint for the given license key.
     *
     * @param string $license_key Customer's license key.
     * @return array Decoded Licfy response, or an ['status' => 'error'] shape on failure.
     */
    public static function verify( $license_key ) {
        $response = wp_remote_post( self::API_BASE . '/verify', array(
            'timeout' => 15,
            'headers' => array(
                'Authorization' => 'Bearer ' . self::API_TOKEN,
                'Content-Type'  => 'application/json',
            ),
            'body' => wp_json_encode( array(
                'email'        => get_option( 'admin_email' ),
                'license_key'  => $license_key,
                'product_slug' => self::PRODUCT_SLUG,
                'website_name' => get_bloginfo( 'name' ),
                'website_url'  => home_url(),
            ) ),
        ) );

        if ( is_wp_error( $response ) ) {
            return array( 'status' => 'error', 'message' => $response->get_error_message() );
        }

        $data = json_decode( wp_remote_retrieve_body( $response ), true );

        return is_array( $data ) ? $data : array( 'status' => 'error', 'message' => 'Unexpected response' );
    }

    /**
     * Whether the stored license key is currently valid. Result is cached for a
     * day so premium features aren't blocked by an API call on every page load.
     *
     * @return bool
     */
    public static function is_active() {
        $cached = get_transient( self::TRANSIENT_STATUS );
        if ( false !== $cached ) {
            return 'valid' === $cached;
        }

        $license_key = get_option( self::OPTION_LICENSE_KEY );
        if ( ! $license_key ) {
            return false;
        }

        $result = self::verify( $license_key );
        $status = ( ! empty( $result['license_status'] ) && 'valid' === $result['license_status'] ) ? 'valid' : 'invalid';

        set_transient( self::TRANSIENT_STATUS, $status, DAY_IN_SECONDS );

        return 'valid' === $status;
    }

    /**
     * Admin notice nudging the site owner to activate their license.
     */
    public static function maybe_show_inactive_notice() {
        if ( self::is_active() || ! current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
        <div class="notice notice-warning">
            <p>
                <?php
                printf(
                    /* translators: %s: settings page link */
                    esc_html__( 'My Plugin is not licensed. %s to unlock premium features.', 'my-plugin' ),
                    '<a href="' . esc_url( admin_url( 'options-general.php?page=my-plugin-license' ) ) . '">' . esc_html__( 'Activate your license', 'my-plugin' ) . '</a>'
                );
                ?>
            </p>
        </div>
        <?php
    }
}

/**
 * ---------------------------------------------------------------------------
 * Usage in your own plugin/theme main file:
 *
 *   require_once __DIR__ . '/class-licfy-client-example.php';
 *   Licfy_Client_Example::init();
 *
 * Then gate any premium feature with:
 *
 *   if ( Licfy_Client_Example::is_active() ) {
 *       // unlock premium feature / updates.
 *   }
 * ---------------------------------------------------------------------------
 */
