<?php
/**
 * Special License Key Manager
 *
 * Handles special license keys that map to dedicated ElevenLabs API keys
 * for higher credit tiers (275K, 575K characters/month).
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 * @since      2.0.7
 */

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

class Mementor_TTS_Special_License {

    /**
     * Singleton instance.
     *
     * @var Mementor_TTS_Special_License
     */
    private static $instance = null;

    /**
     * Option name for key mappings.
     *
     * @var string
     */
    const MAPPINGS_OPTION = 'mementor_tts_special_key_mappings';

    /**
     * Option name for the HMAC secret.
     *
     * @var string
     */
    const SECRET_OPTION = 'mementor_tts_special_key_secret';

    /**
     * Option name for the active license key.
     *
     * @var string
     */
    const ACTIVE_KEY_OPTION = 'mementor_tts_special_license_key';

    /**
     * Option name for the active tier.
     *
     * @var string
     */
    const ACTIVE_TIER_OPTION = 'mementor_tts_special_license_tier';

    /**
     * Get singleton instance.
     *
     * @return Mementor_TTS_Special_License
     */
    public static function get_instance() {
        if ( self::$instance === null ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Private constructor.
     */
    private function __construct() {}

    /**
     * Generate a new special license key for a tier.
     *
     * Admin-only. Stores the mapping (encrypted ElevenLabs key) in options.
     *
     * @param string $tier           Tier identifier (e.g. '275k', '575k').
     * @param string $elevenlabs_key The raw ElevenLabs API key.
     * @return string The generated special license key (64-char hex).
     */
    public function generate_key( $tier, $elevenlabs_key ) {
        $secret  = $this->get_or_create_secret();
        $uuid    = wp_generate_uuid4();
        $payload = 'special_tier:' . sanitize_text_field( $tier ) . ':' . $uuid;

        $license_key = hash_hmac( 'sha256', $payload, $secret );

        // Encrypt the ElevenLabs API key
        require_once plugin_dir_path( __FILE__ ) . 'class-mementor-tts-encryption.php';
        $encryption     = new Mementor_TTS_Encryption();
        $encrypted_key  = $encryption->encrypt( $elevenlabs_key );

        // Store in mappings
        $mappings = get_option( self::MAPPINGS_OPTION, array() );
        $mappings[ $license_key ] = array(
            'tier'              => sanitize_text_field( $tier ),
            'encrypted_api_key' => $encrypted_key,
            'created_at'        => current_time( 'mysql' ),
        );
        update_option( self::MAPPINGS_OPTION, $mappings, false );

        return $license_key;
    }

    /**
     * Validate a special license key.
     *
     * @param string $key The special license key entered by user.
     * @return array|false Array with 'tier' and 'api_key' (decrypted) on success, false on failure.
     */
    public function validate_key( $key ) {
        $key = sanitize_text_field( trim( $key ) );
        if ( empty( $key ) ) {
            return false;
        }

        $mappings = get_option( self::MAPPINGS_OPTION, array() );
        if ( ! isset( $mappings[ $key ] ) ) {
            return false;
        }

        $mapping = $mappings[ $key ];

        require_once plugin_dir_path( __FILE__ ) . 'class-mementor-tts-encryption.php';
        $encryption = new Mementor_TTS_Encryption();
        $decrypted  = $encryption->decrypt( $mapping['encrypted_api_key'] );

        if ( $decrypted === false ) {
            return false;
        }

        return array(
            'tier'    => $mapping['tier'],
            'api_key' => $decrypted,
        );
    }

    /**
     * Get the currently active special license info.
     *
     * @return array|false Array with 'tier' and 'api_key' on success, false if inactive.
     */
    public function get_active_license() {
        $stored_key = get_option( self::ACTIVE_KEY_OPTION, '' );
        if ( empty( $stored_key ) ) {
            return false;
        }
        return $this->validate_key( $stored_key );
    }

    /**
     * Activate a special license key.
     *
     * @param string $key The license key to activate.
     * @return array|false The license info on success, false on failure.
     */
    public function activate_key( $key ) {
        $result = $this->validate_key( $key );
        if ( $result === false ) {
            return false;
        }

        update_option( self::ACTIVE_KEY_OPTION, sanitize_text_field( trim( $key ) ), false );
        update_option( self::ACTIVE_TIER_OPTION, $result['tier'], false );

        return $result;
    }

    /**
     * Deactivate the current special license.
     *
     * @return void
     */
    public function deactivate() {
        delete_option( self::ACTIVE_KEY_OPTION );
        delete_option( self::ACTIVE_TIER_OPTION );
    }

    /**
     * Revoke a key from the mappings.
     *
     * @param string $key The license key to revoke.
     * @return bool True if revoked, false if not found.
     */
    public function revoke_key( $key ) {
        $key      = sanitize_text_field( trim( $key ) );
        $mappings = get_option( self::MAPPINGS_OPTION, array() );

        if ( ! isset( $mappings[ $key ] ) ) {
            return false;
        }

        unset( $mappings[ $key ] );
        update_option( self::MAPPINGS_OPTION, $mappings, false );

        // If this was the active key, deactivate it
        $active_key = get_option( self::ACTIVE_KEY_OPTION, '' );
        if ( $active_key === $key ) {
            $this->deactivate();
        }

        return true;
    }

    /**
     * Get human-readable tier label.
     *
     * @param string $tier Tier identifier.
     * @return string Formatted label.
     */
    public function get_tier_label( $tier ) {
        $labels = array(
            '275k' => '275,000',
            '575k' => '575,000',
        );
        return isset( $labels[ $tier ] ) ? $labels[ $tier ] : $tier;
    }

    /**
     * Check if a special license is currently active.
     *
     * @return bool
     */
    public function is_active() {
        return ! empty( get_option( self::ACTIVE_KEY_OPTION, '' ) );
    }

    /**
     * Get the active tier identifier.
     *
     * @return string Tier identifier or empty string.
     */
    public function get_active_tier() {
        return get_option( self::ACTIVE_TIER_OPTION, '' );
    }

    /**
     * Get or create the HMAC signing secret.
     *
     * @return string The HMAC secret.
     */
    private function get_or_create_secret() {
        $secret = get_option( self::SECRET_OPTION );
        if ( ! $secret ) {
            $secret = wp_generate_password( 64, true, true );
            update_option( self::SECRET_OPTION, $secret, false );
        }
        return $secret;
    }
}
