<?php
/**
 * License Manager Class
 *
 * Handles license validation, tier management, and feature restrictions.
 *
 * @package VariationHub
 * @since 1.0.0
 */

namespace VariationHub\Core;

defined('ABSPATH') || exit;

class License_Manager {

    /**
     * WooCommerce logger instance
     *
     * @var \WC_Logger|null
     */
    private static $logger = null;

    /**
     * License tiers with limits and pricing
     */
    const TIERS = [
        'free' => [
            'name' => 'Free',
            'price' => 0,
            'billing_period' => 'lifetime',
            'csv_export_limit' => 200,          // CSV only, max 200 rows
            'csv_import_limit' => 200,          // CSV only, max 200 rows
            'xlsx_export' => false,             // XLSX blocked
            'xlsx_import' => false,             // XLSX blocked
            'bulk_operations_limit' => 10,      // Max 10 variations at once
            'sku_generator' => false,           // PRO only
            'attribute_manager' => false,       // PRO only
            'performance_tools' => false,       // PRO only (not implemented yet)
            'image_bulk_assign_limit' => 0,     // Blocked (not implemented yet)
        ],
        'pro' => [
            'name' => 'Pro',
            'price' => 29,
            'billing_period' => 'year',
            'csv_export_limit' => -1,           // unlimited
            'csv_import_limit' => -1,           // unlimited
            'xlsx_export' => true,              // XLSX enabled
            'xlsx_import' => true,              // XLSX enabled
            'bulk_operations_limit' => -1,      // unlimited variations
            'sku_generator' => true,            // enabled
            'attribute_manager' => true,        // enabled
            'performance_tools' => true,        // enabled
            'image_bulk_assign_limit' => -1,    // unlimited (when implemented)
        ],
    ];
    
    /**
     * License API endpoint - ByteBays License Server
     */
    const API_URL = 'https://bytebays.com/api/v1/licenses/';

    /**
     * Log a message using WooCommerce logger
     *
     * @param string $message Log message
     * @param string $level Log level (emergency|alert|critical|error|warning|notice|info|debug)
     * @return void
     */
    private static function log($message, $level = 'error') {
        if (null === self::$logger) {
            self::$logger = wc_get_logger();
        }
        self::$logger->log($level, $message, ['source' => 'variation-hub']);
    }

    /**
     * Get site domain (clean hostname without protocol/path)
     *
     * @return string Domain name
     */
    private static function get_site_domain() {
        return wp_parse_url(site_url(), PHP_URL_HOST);
    }
    
    /**
     * Encrypt license data for secure local storage with HMAC integrity protection
     *
     * Uses AES-256-CBC encryption with WordPress AUTH_KEY and SECURE_AUTH_KEY constants.
     * Additionally generates HMAC-SHA256 signature for tamper detection using NONCE_KEY.
     *
     * Format: base64(encrypted_data) + '|' + hmac_signature
     * This ensures both confidentiality (encryption) and integrity (HMAC).
     *
     * @since 1.0.0
     * @param array $data License data to encrypt
     * @return string|false Encrypted data with HMAC signature or false on failure
     */
    private static function encrypt_license_data($data) {
        // 1. Validate WordPress security constants
        $key = defined('AUTH_KEY') ? AUTH_KEY : '';
        $iv = defined('SECURE_AUTH_KEY') ? substr(SECURE_AUTH_KEY, 0, 16) : '';
        $hmac_key = defined('NONCE_KEY') ? NONCE_KEY : '';

        if (empty($key) || empty($iv)) {
            self::log('[VH] Encryption failed: AUTH_KEY or SECURE_AUTH_KEY not defined in wp-config.php', 'error');
            return false;
        }

        if (empty($hmac_key)) {
            self::log('[VH] HMAC generation warning: NONCE_KEY not defined in wp-config.php. Using fallback.', 'warning');
            // Fallback: use AUTH_SALT if available, otherwise use a constant
            $hmac_key = defined('AUTH_SALT') ? AUTH_SALT : 'vh-fallback-hmac-key-' . AUTH_KEY;
        }

        // 2. Encrypt the data (AES-256-CBC)
        $encrypted = openssl_encrypt(
            wp_json_encode($data),
            'AES-256-CBC',
            $key,
            0,
            $iv
        );

        if (false === $encrypted) {
            self::log('[VH] OpenSSL encryption failed', 'error');
            return false;
        }

        // 3. Base64 encode the encrypted data
        $encrypted_base64 = base64_encode($encrypted);

        // 4. Generate HMAC signature for integrity verification
        // Using the base64-encoded encrypted data to ensure consistent validation
        $hmac_signature = hash_hmac('sha256', $encrypted_base64, $hmac_key);

        // 5. Combine encrypted data and HMAC with delimiter
        // Format: encrypted_base64|hmac_signature
        $secured_data = $encrypted_base64 . '|' . $hmac_signature;

        self::log('[VH] License data encrypted successfully with HMAC protection', 'info');

        return $secured_data;
    }
    
    /**
     * Decrypt license data from secure storage with HMAC integrity validation
     *
     * Validates HMAC signature before decryption to detect tampering.
     * Supports backward compatibility with old encrypted data (without HMAC).
     *
     * Format expected: base64(encrypted_data) + '|' + hmac_signature
     * Old format (backward compatible): base64(encrypted_data)
     *
     * @since 1.0.0
     * @param string $encrypted Encrypted data with optional HMAC
     * @return array|false Decrypted license data or false on failure/tampering
     */
    private static function decrypt_license_data($encrypted) {
        // 1. Validate WordPress security constants
        $key = defined('AUTH_KEY') ? AUTH_KEY : '';
        $iv = defined('SECURE_AUTH_KEY') ? substr(SECURE_AUTH_KEY, 0, 16) : '';
        $hmac_key = defined('NONCE_KEY') ? NONCE_KEY : '';

        if (empty($key) || empty($iv) || empty($encrypted)) {
            return false;
        }

        if (empty($hmac_key)) {
            // Same fallback as encrypt
            $hmac_key = defined('AUTH_SALT') ? AUTH_SALT : 'vh-fallback-hmac-key-' . AUTH_KEY;
        }

        // 2. Check if data contains HMAC signature (new format)
        $has_hmac = strpos($encrypted, '|') !== false;

        if ($has_hmac) {
            // NEW FORMAT: encrypted_base64|hmac_signature

            // 3. Split encrypted data and HMAC signature
            $parts = explode('|', $encrypted, 2);

            if (count($parts) !== 2) {
                self::log('[VH] HMAC validation failed: Invalid format', 'error');
                return false;
            }

            list($encrypted_base64, $provided_hmac) = $parts;

            // 4. Validate HMAC signature
            $expected_hmac = hash_hmac('sha256', $encrypted_base64, $hmac_key);

            // Use hash_equals() for timing attack protection
            if (!hash_equals($expected_hmac, $provided_hmac)) {
                // 🚨 CRITICAL SECURITY INCIDENT: Tamper detected!
                self::log(
                    '[VH] 🚨 SECURITY ALERT: License data HMAC validation FAILED! Possible tampering detected. ' .
                    'Site: ' . site_url() . ' | Time: ' . current_time('mysql') . ' | User: ' . (is_user_logged_in() ? get_current_user_id() : 'not logged in'),
                    'error'
                );

                // For debugging (only in WP_DEBUG mode)
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    self::log('[VH] Debug: Expected HMAC: ' . substr($expected_hmac, 0, 10) . '... | Provided HMAC: ' . substr($provided_hmac, 0, 10) . '...', 'debug');
                }

                // Record security incident for admin notification
                self::record_security_incident('hmac_validation_failed', [
                    'event' => 'License data tampering detected',
                    'expected_hmac_prefix' => substr($expected_hmac, 0, 16),
                    'provided_hmac_prefix' => substr($provided_hmac, 0, 16),
                    'timestamp' => current_time('mysql'),
                    'user_id' => is_user_logged_in() ? get_current_user_id() : 0,
                    'ip_address' => self::get_client_ip(),
                ]);

                // Delete potentially tampered data
                delete_option('varihu_license_data');

                return false;
            }

            // 5. HMAC valid - proceed with decryption
            $encrypted_data = $encrypted_base64;

            self::log('[VH] HMAC validation passed - license data integrity confirmed', 'info');

        } else {
            // OLD FORMAT (backward compatibility): no HMAC present

            self::log('[VH] Legacy license data detected (no HMAC). Migrating to secure format...', 'warning');

            $encrypted_data = $encrypted;

            // Note: We'll re-save with HMAC after successful decryption (migration)
        }

        // 6. Decrypt the data (AES-256-CBC)
        $decrypted = openssl_decrypt(
            base64_decode($encrypted_data),
            'AES-256-CBC',
            $key,
            0,
            $iv
        );

        if (false === $decrypted) {
            self::log('[VH] OpenSSL decryption failed', 'error');
            return false;
        }

        // 7. Parse JSON data
        $license_data = json_decode($decrypted, true);

        if (!is_array($license_data)) {
            self::log('[VH] License data JSON decode failed', 'error');
            return false;
        }

        // 8. If old format was detected, re-save with HMAC protection (automatic migration)
        if (!$has_hmac && !empty($license_data)) {
            self::log('[VH] Automatically migrating legacy license data to HMAC-protected format', 'info');

            $encrypted_with_hmac = self::encrypt_license_data($license_data);

            if (false !== $encrypted_with_hmac) {
                update_option('varihu_license_data', $encrypted_with_hmac, false);
                self::log('[VH] Legacy license data successfully migrated to HMAC format', 'info');
            }
        }

        return $license_data;
    }
    
    /**
     * Save license data to encrypted storage
     *
     * @param string $license_key License key
     * @param array $api_response Response from ByteBays API
     * @return bool Success status
     */
    private static function save_license_data($license_key, $api_response) {
        $data = [
            'license_key' => $license_key,
            'tier' => $api_response['tier'] ?? 'free',
            'expires_at' => $api_response['expires_at'] ?? '',
            'activated_at' => current_time('mysql'),
            'last_validated' => current_time('mysql'),
        ];
        
        $encrypted = self::encrypt_license_data($data);
        
        if (false === $encrypted) {
            return false;
        }
        
        return update_option('varihu_license_data', $encrypted, false); // false = no autoload
    }
    
    /**
     * Get decrypted license data from storage
     *
     * @return array|false License data or false if not found/invalid
     */
    private static function get_license_data() {
        $encrypted = get_option('varihu_license_data', '');
        
        if (empty($encrypted)) {
            return false;
        }
        
        return self::decrypt_license_data($encrypted);
    }
    
    /**
     * Get current license tier
     *
     * @return string Tier name (free, pro)
     */
    public static function get_tier() {
        // Get encrypted license data
        $license_data = self::get_license_data();
        
        if (!$license_data) {
            return 'free';
        }
        
        // Check expiration with grace period
        $expires_at = strtotime($license_data['expires_at']);
        $last_validated = strtotime($license_data['last_validated']);
        $grace_period = 7 * DAY_IN_SECONDS; // 7 days offline operation
        
        // License expired AND grace period exceeded
        if ($expires_at < time() && ($last_validated + $grace_period) < time()) {
            // Grace period exceeded - revert to FREE
            delete_option('varihu_license_data');
            return 'free';
        }
        
        return $license_data['tier'] ?? 'free';
    }
    
    /**
     * Check if a feature is available for current tier
     *
     * @param string $feature Feature key (e.g., 'bulk_operations')
     * @return bool
     */
    public static function has_feature($feature) {
        $tier = self::get_tier();
        $limits = self::TIERS[$tier] ?? self::TIERS['free'];
        
        return $limits[$feature] ?? false;
    }
    
    /**
     * Get limit value for current tier
     *
     * @param string $limit Limit key (e.g., 'max_variations')
     * @return int Limit value (-1 = unlimited)
     */
    public static function get_limit($limit) {
        $tier = self::get_tier();
        $limits = self::TIERS[$tier] ?? self::TIERS['free'];
        
        return $limits[$limit] ?? 0;
    }
    
    /**
     * Check if variation limit is reached
     *
     * @return bool
     */
    public static function is_variation_limit_reached() {
        $max = self::get_limit('max_variations');
        
        if ($max === -1) {
            return false; // unlimited
        }
        
        $total = self::count_variations();
        
        return $total >= $max;
    }
    
    /**
     * Count total variations in store
     *
     * @return int
     */
    public static function count_variations() {
        $counts = wp_count_posts('product_variation');
        return (int) ($counts->publish ?? 0);
    }
    
    /**
     * Get remaining variations quota
     *
     * @return int|string Number or 'unlimited'
     */
    public static function get_remaining_quota() {
        $max = self::get_limit('max_variations');
        
        if ($max === -1) {
            return __('Unlimited', 'variation-hub');
        }
        
        $total = self::count_variations();
        $remaining = max(0, $max - $total);
        
        return $remaining;
    }
    
    /**
     * Schedule daily license validation (called on plugin activation)
     *
     * @return void
     */
    public static function schedule_validation() {
        if (!wp_next_scheduled('varihu_validate_license_daily')) {
            wp_schedule_event(time(), 'daily', 'varihu_validate_license_daily');
        }
    }
    
    /**
     * Unschedule daily license validation (called on plugin deactivation)
     *
     * @return void
     */
    public static function unschedule_validation() {
        $timestamp = wp_next_scheduled('varihu_validate_license_daily');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'varihu_validate_license_daily');
        }
    }
    
    /**
     * Validate license with ByteBays API (WP Cron daily job)
     * 
     * Updates last_validated timestamp if license is still valid.
     * Removes license data if validation fails.
     *
     * @return void
     */
    public static function validate_license_cron() {
        $license_data = self::get_license_data();
        
        if (!$license_data) {
            return; // No license to validate
        }
        
        // Call ByteBays validate endpoint
        $response = wp_remote_get(self::API_URL . 'validate.php?' . http_build_query([
            'license_key' => $license_data['license_key'],
            'domain' => self::get_site_domain(),
        ]), [
            'timeout' => 10,
        ]);
        
        if (is_wp_error($response)) {
            self::log('[VH] License validation cron failed: ' . $response->get_error_message(), 'error');
            return; // Don't remove license on network error (grace period handles this)
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($data && $data['success'] && $data['valid']) {
            // License still valid - update last_validated timestamp
            $license_data['last_validated'] = current_time('mysql');
            $encrypted = self::encrypt_license_data($license_data);
            
            if ($encrypted) {
                update_option('varihu_license_data', $encrypted, false);
            }
        } else {
            // License invalid - remove it
            delete_option('varihu_license_data');
            self::log('[VH] License validation failed: ' . ($data['message'] ?? 'Unknown error'), 'error');
        }
    }
    
    /**
     * Activate license key
     *
     * @param string $license_key License key
     * @return array Result with success status and message
     */
    public static function activate_license($license_key) {
        // Prepare request data
        $body_data = [
            'license_key' => $license_key,
            'domain' => self::get_site_domain(),
            'site_url' => site_url(),
            'home_url' => home_url(),
            'wp_version' => get_bloginfo('version'),
            'wc_version' => defined('WC_VERSION') ? WC_VERSION : 'N/A',
            'plugin_version' => VARIHU_VERSION,
        ];
        
        // Call ByteBays API activate endpoint
        $response = wp_remote_post(self::API_URL . 'activate.php', [
            'timeout' => 15,
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => wp_json_encode($body_data),
        ]);
        
        if (is_wp_error($response)) {
            self::log('[VH] License activation WP_Error: ' . $response->get_error_message(), 'error');
            return [
                'success' => false,
                'message' => __('Network error: Unable to connect to license server. Please try again later.', 'variation-hub'),
            ];
        }

        $body = wp_remote_retrieve_body($response);
        $http_code = wp_remote_retrieve_response_code($response);

        self::log('[VH] ByteBays API Response Code: ' . $http_code, 'debug');
        self::log('[VH] ByteBays API Response Body: ' . $body, 'debug');
        
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            self::log('[VH] JSON decode error: ' . json_last_error_msg(), 'error');
            return [
                'success' => false,
                'message' => __('Invalid API response format (JSON error)', 'variation-hub'),
            ];
        }
        
        if (!$data || !$data['success']) {
            self::log('[VH] License activation failed. API response: ' . wp_json_encode($data), 'error');
            return [
                'success' => false,
                'message' => $data['message'] ?? __('Invalid license key', 'variation-hub'),
            ];
        }

        // Extract license data from ByteBays API response
        $license_data = $data['data'] ?? [];

        self::log('[VH] Extracted license_data: ' . wp_json_encode($license_data), 'debug');
        
        if (empty($license_data['tier']) || empty($license_data['expires_at'])) {
            self::log('[VH] Missing tier or expires_at in API response', 'error');
            return [
                'success' => false,
                'message' => __('Invalid API response format', 'variation-hub'),
            ];
        }

        // Save encrypted license data (not plain text!)
        $save_result = self::save_license_data($license_key, $license_data);

        self::log('[VH] Save license data result: ' . ($save_result ? 'SUCCESS' : 'FAILED'), 'debug');
        
        if (!$save_result) {
            return [
                'success' => false,
                'message' => __('Failed to save license data. Please check WordPress AUTH_KEY constant.', 'variation-hub'),
            ];
        }
        
        // Clear old plain text option (migration from old version)
        delete_option('varihu_license_key');
        delete_option('varihu_license_tier');
        delete_option('varihu_license_expires');
        
        return [
            'success' => true,
            'message' => __('License activated successfully!', 'variation-hub'),
            'tier' => $license_data['tier'],
            'expires_at' => $license_data['expires_at'],
        ];
    }
    
    /**
     * Deactivate license key
     *
     * @return array Result with success status and message
     */
    public static function deactivate_license() {
        $license_data = self::get_license_data();
        
        if (!$license_data) {
            return [
                'success' => false,
                'message' => __('No active license', 'variation-hub'),
            ];
        }
        
        // Call ByteBays deactivate endpoint
        $response = wp_remote_post(self::API_URL . 'deactivate.php', [
            'timeout' => 10,
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => wp_json_encode([
                'license_key' => $license_data['license_key'],
                'domain' => self::get_site_domain(),
            ]),
        ]);
        
        // Remove local data regardless of API response (user wants to deactivate)
        delete_option('varihu_license_data');
        
        // Also clean up old plain text options (migration)
        delete_option('varihu_license_key');
        delete_option('varihu_license_tier');
        delete_option('varihu_license_expires');
        
        if (is_wp_error($response)) {
            // Local data removed, but API call failed
            return [
                'success' => true,
                'message' => __('License deactivated locally (server unreachable)', 'variation-hub'),
            ];
        }
        
        return [
            'success' => true,
            'message' => __('License deactivated successfully', 'variation-hub'),
        ];
    }
    
    /**
     * Get license info for display
     *
     * @return array License information
     */
    public static function get_license_info() {
        $tier = self::get_tier();
        $license_data = self::get_license_data();
        $limits = self::TIERS[$tier] ?? self::TIERS['free'];
        
        $info = [
            'tier' => $tier,
            'tier_label' => self::get_tier_label($tier),
            'is_active' => (bool) $license_data,
            'license_key' => '',
            'expires' => '',
            'limits' => $limits,
            'features' => [
                'csv_export_limit' => isset($limits['csv_export_limit']),
                'csv_import_limit' => isset($limits['csv_import_limit']),
                'xlsx_export' => $limits['xlsx_export'] ?? false,
                'xlsx_import' => $limits['xlsx_import'] ?? false,
                'bulk_operations_limit' => isset($limits['bulk_operations_limit']),
                'sku_generator' => $limits['sku_generator'] ?? false,
                'attribute_manager' => $limits['attribute_manager'] ?? false,
                'performance_tools' => $limits['performance_tools'] ?? false,
            ],
            'usage' => [
                'variations' => self::count_variations(),
            ],
        ];
        
        // Add encrypted license data if available
        if ($license_data) {
            $info['license_key'] = substr($license_data['license_key'], 0, 15) . '...';
            $info['expires'] = $license_data['expires_at'];
            $info['activated_at'] = $license_data['activated_at'] ?? '';
            $info['last_validated'] = $license_data['last_validated'] ?? '';
        }
        
        return $info;
    }
    
    /**
     * Get human-readable tier label
     *
     * @param string $tier Tier key
     * @return string
     */
    private static function get_tier_label($tier) {
        $labels = [
            'free' => __('Ingyenes', 'variation-hub'),
            'pro' => __('Pro', 'variation-hub'),
        ];
        
        return $labels[$tier] ?? $labels['free'];
    }
    
    /**
     * Show upgrade notice in admin
     *
     * @param string $feature Feature name for context
     * @return void
     */
    public static function show_upgrade_notice($feature = '') {
        $message = sprintf(
            /* translators: %s: URL to pricing page */
            __('This feature is available in the <strong>Pro</strong> version. <a href="%s" target="_blank">Upgrade now</a>', 'variation-hub'),
            'https://variationhub.com/pricing'
        );

        printf(
            '<div class="notice notice-warning"><p>%s</p></div>',
            wp_kses_post($message)
        );
    }

    /**
     * Record security incident for admin notification
     *
     * Stores security incident data in database and notifies ByteBays.
     *
     * @since 1.0.0
     * @param string $incident_type Type of security incident
     * @param array $details Incident details
     * @return void
     */
    private static function record_security_incident($incident_type, $details = []) {
        // Store in database via Security_Incidents_Manager
        if (class_exists('\VariationHub\Core\Security_Incidents_Manager')) {
            \VariationHub\Core\Security_Incidents_Manager::record_incident($incident_type, $details);
        }

        // Also keep transient for backward compatibility (admin notices)
        $incident_data = [
            'type' => $incident_type,
            'details' => $details,
            'recorded_at' => current_time('mysql'),
        ];
        set_transient('varihu_security_incident_' . $incident_type, $incident_data, 7 * DAY_IN_SECONDS);

        // Notify ByteBays server about critical security incident
        self::notify_bytebays_security_incident($incident_type, $details);

        // Trigger action for external security monitoring (optional)
        do_action('variation_hub_security_incident', $incident_type, $details);
    }

    /**
     * Notify ByteBays License Server about security incident
     *
     * Sends tamper detection and security incidents to ByteBays for
     * fraud detection, account monitoring, and abuse prevention.
     *
     * @since 1.0.0
     * @param string $incident_type Type of security incident
     * @param array $details Incident details
     * @return bool Success status
     */
    private static function notify_bytebays_security_incident($incident_type, $details = []) {
        // Get license data (if available)
        $license_data = self::get_license_data();
        $license_key = $license_data['license_key'] ?? 'unknown';

        // Prepare payload
        $payload = [
            'incident_type' => $incident_type,
            'license_key' => $license_key,
            'domain' => self::get_site_domain(),
            'site_url' => site_url(),
            'timestamp' => current_time('mysql'),
            'details' => $details,
            'plugin_version' => defined('VARIATION_HUB_VERSION') ? VARIATION_HUB_VERSION : '1.0.0',
            'wordpress_version' => get_bloginfo('version'),
            'php_version' => PHP_VERSION,
        ];

        // Send async request to ByteBays (non-blocking)
        wp_remote_post(
            self::API_URL . 'security-incident.php',
            [
                'timeout' => 5,
                'blocking' => false, // Non-blocking - don't wait for response
                'headers' => [
                    'Content-Type' => 'application/json',
                    'X-VH-Security-Report' => 'v1',
                ],
                'body' => wp_json_encode($payload),
            ]
        );

        self::log('[VH] Security incident reported to ByteBays: ' . $incident_type, 'info');

        return true;
    }

    /**
     * Get client IP address (security logging)
     *
     * Attempts to get real IP even behind proxies/load balancers.
     *
     * @since 1.0.0
     * @return string Client IP address
     */
    private static function get_client_ip() {
        $ip_keys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR',
        ];

        foreach ($ip_keys as $key) {
            if (!empty($_SERVER[$key])) {
                $ip = sanitize_text_field(wp_unslash($_SERVER[$key]));

                // Handle comma-separated IPs (X-Forwarded-For can contain multiple IPs)
                if (strpos($ip, ',') !== false) {
                    $ips = explode(',', $ip);
                    $ip = trim($ips[0]);
                }

                // Validate IP format
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    return $ip;
                }
            }
        }

        return 'unknown';
    }

    /**
     * Display admin notice for security incidents
     *
     * Shows critical security alerts in WordPress admin.
     * Hooked to admin_notices.
     *
     * @since 1.0.0
     * @return void
     */
    public static function display_security_notices() {
        // Only show to administrators
        if (!current_user_can('manage_options')) {
            return;
        }

        // Check for HMAC validation failure incident
        $hmac_incident = get_transient('varihu_security_incident_hmac_validation_failed');

        if ($hmac_incident !== false) {
            $details = $hmac_incident['details'] ?? [];
            $timestamp = $details['timestamp'] ?? 'unknown';
            $user_id = $details['user_id'] ?? 0;
            $ip = $details['ip_address'] ?? 'unknown';

            ?>
            <div class="notice notice-error is-dismissible" style="border-left: 4px solid #dc3232;">
                <p style="font-weight: bold; font-size: 14px;">
                    🚨 <?php echo esc_html__('CRITICAL SECURITY ALERT: License Data Tampering Detected', 'variation-hub'); ?>
                </p>
                <p>
                    <?php echo esc_html__('Variation Hub detected an attempt to tamper with encrypted license data. The license has been automatically deactivated for security.', 'variation-hub'); ?>
                </p>
                <p style="margin: 10px 0; padding: 10px; background: #f8d7da; border-radius: 4px;">
                    <strong><?php echo esc_html__('Incident Details:', 'variation-hub'); ?></strong><br>
                    <strong><?php echo esc_html__('Time:', 'variation-hub'); ?></strong> <?php echo esc_html($timestamp); ?><br>
                    <strong><?php echo esc_html__('User ID:', 'variation-hub'); ?></strong> <?php echo esc_html($user_id ? $user_id : __('Not logged in', 'variation-hub')); ?><br>
                    <strong><?php echo esc_html__('IP Address:', 'variation-hub'); ?></strong> <?php echo esc_html($ip); ?>
                </p>
                <p>
                    <strong><?php echo esc_html__('Recommended Actions:', 'variation-hub'); ?></strong>
                </p>
                <ul style="list-style: disc; margin-left: 20px;">
                    <li><?php echo esc_html__('Review your server security and database access logs', 'variation-hub'); ?></li>
                    <li><?php echo esc_html__('Check for unauthorized database modifications', 'variation-hub'); ?></li>
                    <li><?php echo esc_html__('Re-activate your license if this was a false positive', 'variation-hub'); ?></li>
                    <li><?php echo esc_html__('Contact support if the issue persists', 'variation-hub'); ?></li>
                </ul>
                <p>
                    <button type="button" class="button button-primary" onclick="jQuery(this).closest('.notice').fadeOut(); fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>?action=varihu_dismiss_security_incident&incident=hmac_validation_failed&_wpnonce=<?php echo esc_attr(wp_create_nonce('varihu_dismiss_security_incident')); ?>');">
                        <?php echo esc_html__('Dismiss This Alert', 'variation-hub'); ?>
                    </button>
                </p>
            </div>
            <?php
        }
    }

    /**
     * Dismiss security incident (AJAX handler)
     *
     * @since 1.0.0
     * @return void
     */
    public static function dismiss_security_incident_ajax() {
        check_ajax_referer('varihu_dismiss_security_incident', '_wpnonce');

        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized', 403);
        }

        $incident = isset($_GET['incident']) ? sanitize_text_field(wp_unslash($_GET['incident'])) : '';

        if ($incident) {
            delete_transient('varihu_security_incident_' . $incident);
            self::log('[VH] Security incident dismissed by admin: ' . $incident, 'info');
        }

        wp_die('OK', 200);
    }
}

// Hook WP Cron daily validation
add_action('varihu_validate_license_daily', ['VariationHub\Core\License_Manager', 'validate_license_cron']);

// Hook admin notices for security incidents
add_action('admin_notices', ['VariationHub\Core\License_Manager', 'display_security_notices']);

// Hook AJAX handler for dismissing security incidents
add_action('wp_ajax_varihu_dismiss_security_incident', ['VariationHub\Core\License_Manager', 'dismiss_security_incident_ajax']);
