<?php
/**
 * License Management class.
 *
 * Handles Pro license validation, activation, and status checks.
 *
 * @package Hugeicons
 */

namespace Hugeicons;

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

/**
 * License class for managing Pro licenses.
 */
class License {

    /**
     * Option name for license key.
     *
     * @var string
     */
    const OPTION_LICENSE_KEY = 'hugeicons_license_key';

    /**
     * Option name for license status.
     *
     * @var string
     */
    const OPTION_LICENSE_STATUS = 'hugeicons_license_status';

    /**
     * Option name for license data (cached).
     *
     * @var string
     */
    const OPTION_LICENSE_DATA = 'hugeicons_license_data';

    /**
     * API endpoint for token validation.
     *
     * @var string
     */
    const API_VALIDATE_URL = 'https://hugeicons.com/api/validate-token';

    /**
     * Free style that doesn't require a license.
     *
     * @var string
     */
    const FREE_STYLE = 'stroke-rounded';

    /**
     * Activate a license with the given token.
     *
     * @param string $token The license token to validate.
     * @return array Result with 'success' boolean and 'message' string.
     */
    public function activate_license( $token ) {
        // Sanitize the token.
        $token = sanitize_text_field( trim( $token ) );

        if ( empty( $token ) ) {
            return array(
                'success' => false,
                'message' => __( 'Please enter a valid license key.', 'hugeicons' ),
            );
        }

        // Validate against the API.
        $response = wp_remote_post(
            self::API_VALIDATE_URL,
            array(
                'timeout' => 15,
                'headers' => array(
                    'Content-Type' => 'application/json',
                ),
                'body'    => wp_json_encode( array( 'token' => $token ) ),
            )
        );

        if ( is_wp_error( $response ) ) {
            return array(
                'success' => false,
                'message' => __( 'Could not connect to license server. Please try again later.', 'hugeicons' ),
            );
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $body          = wp_remote_retrieve_body( $response );
        $data          = json_decode( $body, true );

        if ( 200 !== $response_code ) {
            $error_message = isset( $data['message'] ) ? $data['message'] : __( 'License validation failed.', 'hugeicons' );
            return array(
                'success' => false,
                'message' => $error_message,
            );
        }

        // Check if the response indicates a valid license.
        $is_valid = isset( $data['valid'] ) && true === $data['valid'];

        if ( ! $is_valid ) {
            $error_message = isset( $data['message'] ) ? $data['message'] : __( 'Invalid license key.', 'hugeicons' );
            return array(
                'success' => false,
                'message' => $error_message,
            );
        }

        // Store the license.
        update_option( self::OPTION_LICENSE_KEY, $token );
        update_option( self::OPTION_LICENSE_STATUS, 'active' );
        update_option( self::OPTION_LICENSE_DATA, $data );

        return array(
            'success' => true,
            'message' => __( 'License activated successfully!', 'hugeicons' ),
            'data'    => $data,
        );
    }

    /**
     * Deactivate the current license.
     *
     * @return array Result with 'success' boolean and 'message' string.
     */
    public function deactivate_license() {
        delete_option( self::OPTION_LICENSE_KEY );
        delete_option( self::OPTION_LICENSE_STATUS );
        delete_option( self::OPTION_LICENSE_DATA );

        return array(
            'success' => true,
            'message' => __( 'License deactivated successfully.', 'hugeicons' ),
        );
    }

    /**
     * Check if the Pro license is active.
     *
     * @return bool True if Pro is active, false otherwise.
     */
    public function is_pro_active() {
        $status = get_option( self::OPTION_LICENSE_STATUS, '' );
        return 'active' === $status;
    }

    /**
     * Get the current license status.
     *
     * @return array License status data.
     */
    public function get_license_status() {
        $key    = get_option( self::OPTION_LICENSE_KEY, '' );
        $status = get_option( self::OPTION_LICENSE_STATUS, 'inactive' );
        $data   = get_option( self::OPTION_LICENSE_DATA, array() );

        return array(
            'is_active'   => $this->is_pro_active(),
            'status'      => $status,
            'license_key' => $key ? $this->mask_license_key( $key ) : '',
            'data'        => $data,
        );
    }

    /**
     * Mask a license key for display purposes.
     *
     * @param string $key The full license key.
     * @return string The masked license key.
     */
    private function mask_license_key( $key ) {
        if ( strlen( $key ) < 8 ) {
            return $key;
        }
        return substr( $key, 0, 4 ) . '****-****-****-' . substr( $key, -4 );
    }

    /**
     * Get the free style name.
     *
     * @return string The free style identifier.
     */
    public static function get_free_style() {
        return self::FREE_STYLE;
    }

    /**
     * Check if a specific style is available (free or pro-enabled).
     *
     * @param string $style The style to check.
     * @return bool True if the style is available, false otherwise.
     */
    public function is_style_available( $style ) {
        if ( self::FREE_STYLE === $style ) {
            return true;
        }
        return $this->is_pro_active();
    }
}
