<?php
/**
 * API & License Management Section for Dashboard
 * 
 * Integrated API testing and license management functionality.
 *
 * @package VMPFence
 * @since 2.1.0
 * @since 2.2.2 -- Refactored license activation/deactivation handling
 */

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

// Ensure API client class is loaded
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-api-client.php';

$api_test_results = array();
$api_client = new VMPFence_API_Client();

// Process form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vmpfence_api_management_nonce']) && 
    wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['vmpfence_api_management_nonce'])), 'vmpfence_api_management')) {

    // Activate License
    if (isset($_POST['activate_license'])) {
        $license_key = isset($_POST['license_key']) ? sanitize_text_field(wp_unslash($_POST['license_key'])) : '';

        $start_time = microtime(true);
        $result = $api_client->activate_license($license_key, home_url());
        $elapsed = round((microtime(true) - $start_time) * 1000, 2);

        $api_test_results['activate_license'] = array(
            'result' => $result,
            'time_ms' => $elapsed,
            'success' => !is_wp_error($result) && isset($result['success']) && $result['success']
        );

        if ($api_test_results['activate_license']['success']) {
            // License settings already updated by activate_license() via get_license_status()
            // Clear transient to force immediate refresh on next page load
            delete_transient('vmpfence_license_last_refresh');
            
            wp_safe_redirect(add_query_arg(array(
                'page' => 'vmpfence-global-options',
                'license_activated' => '1',
                'cache_bust' => time()
            ), admin_url('admin.php')));
            exit;
        }
    }

    // Deactivate License
    if (isset($_POST['deactivate_license'])) {
        $license_key = VMPFence_Config::get('license_key', '');

        $start_time = microtime(true);
        $result = $api_client->deactivate_license($license_key, home_url());
        $elapsed = round((microtime(true) - $start_time) * 1000, 2);

        $api_test_results['deactivate_license'] = array(
            'result' => $result,
            'time_ms' => $elapsed,
            'success' => !is_wp_error($result) && isset($result['success']) && $result['success']
        );

        if ($api_test_results['deactivate_license']['success']) {
            // Clear license refresh transient to force immediate update
            delete_transient('vmpfence_license_last_refresh');
            
            // CRITICAL: Set manual deactivation flag to prevent auto-reactivation
            VMPFence_Config::set('license_manually_deactivated', true);
            
            VMPFence_Config::set('license_type', VMPFence_Constants::LICENSE_FREE);
            VMPFence_Config::set('license_key', '');
            VMPFence_Config::set('firewall_license_tier', 'free');
            VMPFence_Config::set('scanner_license_tier', 'free');
            update_option('vmpfence_scanner_license_tier', 'free');
            update_option('vmpfence_license', array(
                'license_type' => 'free',
                'deactivated_at' => current_time('mysql')
            ));
            // Also update license_status option
            update_option('vmpfence_license_status', array(
                'type' => 'free',
                'key' => '',
                'updated_at' => current_time('mysql')
            ));
            
            // Redirect to show updated status
            wp_safe_redirect(add_query_arg(array(
                'page' => 'vmpfence-global-options',
                'license_deactivated' => '1',
                'cache_bust' => time()
            ), admin_url('admin.php')));
            exit;
        }
    }
}

// Get current configuration
$raw_license_key = VMPFence_Config::get('license_key', '');
// Only show license key if it's a PREMIUM key (filter out FREE-XXXXXXXX)
$current_license_key = (strpos($raw_license_key, 'PREMIUM-') === 0) ? $raw_license_key : '';
$current_license_type = VMPFence_License::get_license_type();

// Check for success messages
$show_activation_success = isset($_GET['license_activated']) && $_GET['license_activated'] === '1';
$show_deactivation_success = isset($_GET['license_deactivated']) && $_GET['license_deactivated'] === '1';

if ($show_activation_success || $show_deactivation_success) {
    header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
}
?>

<!-- API & License Management Section -->
<div id="vmpfence-license-management" class="vmpfence-section vmpfence-api-management" style="font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; max-width: 1300px;">
    <div class="vmpfence-section-header">
        <h3>
            <span class="vmpfence-notification-icon">🎫</span> License Management
        </h3>
    </div>
    <div class="vmpfence-section-content vmpfence-api-content" style="display: block;">
        
        <!-- Current License Status -->
        <div class="vmpfence-api-card" style="background: linear-gradient(135deg, <?php echo $current_license_type === 'premium' ? '#f0f4ff' : '#f6f7f7'; ?> 0%, <?php echo $current_license_type === 'premium' ? '#e8f0ff' : '#ffffff'; ?> 100%);">
            <h4 style="margin-top: 0; padding-bottom: 12px; border-bottom: 2px solid <?php echo $current_license_type === 'premium' ? '#191970' : '#c3c4c7'; ?>; font-family: 'Inter', sans-serif; font-weight: 600; font-size: 16px; color: #1d2327;">
                📋 License Status
            </h4>
            <div style="margin-top: 20px;">
                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
                    <span style="font-weight: 600; color: #646970; min-width: 120px; font-family: 'Inter', sans-serif;">License Type:</span>
                    <?php if ($current_license_type === 'premium') : ?>
                        <span style="display: inline-flex; align-items: center; gap: 6px; background: linear-gradient(135deg, #191970 0%, #2A2669 100%); color: #ffffff; padding: 6px 16px; border-radius: 12px; font-weight: 600; font-size: 13px; font-family: 'Inter', sans-serif; text-transform: uppercase; letter-spacing: 0.5px; box-shadow: 0 2px 8px rgba(25, 25, 112, 0.25);">
                            ⭐ PREMIUM
                        </span>
                    <?php else : ?>
                        <span style="display: inline-flex; align-items: center; gap: 6px; background: #f6f7f7; color: #646970; padding: 6px 16px; border-radius: 12px; font-weight: 600; font-size: 13px; font-family: 'Inter', sans-serif; text-transform: uppercase; border: 1px solid #c3c4c7;">
                            FREE
                        </span>
                    <?php endif; ?>
                </div>
                <?php if (!empty($current_license_key)) : ?>
                <div style="display: flex; align-items: center; gap: 12px;">
                    <span style="font-weight: 600; color: #646970; min-width: 120px; font-family: 'Inter', sans-serif;">License Key:</span>
                    <div style="display: flex; align-items: center; gap: 8px; flex: 1;">
                        <code id="license-key-display" style="background: #ffffff; padding: 8px 12px; border-radius: 12px; font-size: 13px; font-family: 'Consolas', 'Monaco', monospace; color: #191970; border: 1px solid #c3c4c7; flex: 1;"><?php echo esc_html($current_license_key); ?></code>
                        <button type="button" id="copy-license-btn" onclick="copyLicenseKey(event)" style="background: #191970; color: #ffffff; border: none; padding: 8px 16px; border-radius: 12px; cursor: pointer; font-family: 'Inter', sans-serif; font-weight: 600; font-size: 13px; transition: all 0.2s; display: flex; align-items: center; gap: 6px; height: 40px;" onmouseover="if(!copyLicenseKeyInProgress){this.style.background='#0f0f4d'}" onmouseout="if(!copyLicenseKeyInProgress){this.style.background='#191970'}">
                             Copy
                        </button>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- License Management -->
        <div class="vmpfence-api-card">
            <h4 style="margin-top: 0; padding-bottom: 12px; border-bottom: 2px solid #c3c4c7; font-family: 'Inter', sans-serif; font-weight: 600; font-size: 16px; color: #1d2327;">
                🔑 Manage License
            </h4>
            
            <div style="max-width: 600px; margin: 20px auto 0;">
                <!-- Activate License -->
                <form method="post" style="margin-bottom: 16px;">
                    <?php wp_nonce_field('vmpfence_api_management', 'vmpfence_api_management_nonce'); ?>
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; font-family: 'Inter', sans-serif; color: #1d2327; font-size: 14px;">
                        <?php esc_html_e('Activate Premium License', 'vmpfence-security'); ?>
                    </label>
                    <div style="display: flex; gap: 12px; align-items: stretch;">
                        <input type="text" name="license_key" value="" class="regular-text" placeholder="PREMIUM-XXXXXXXX" style="flex: 1; height: 48px; border-radius: 12px; border: 1px solid #8c8f94; padding: 0 16px; font-family: 'Inter', sans-serif; font-size: 14px; transition: border-color 0.2s;" onfocus="this.style.borderColor='#007AFF'" onblur="this.style.borderColor='#8c8f94'" <?php echo $current_license_type === 'premium' ? 'disabled' : ''; ?> />
                        <button type="submit" name="activate_license" style="height: 48px; background: <?php echo $current_license_type === 'premium' ? '#c3c4c7' : '#191970'; ?>; color: #ffffff; border: none; border-radius: 12px; font-family: 'Inter', sans-serif; font-weight: 600; font-size: 14px; cursor: <?php echo $current_license_type === 'premium' ? 'not-allowed' : 'pointer'; ?>; transition: all 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px; padding: 0 24px; white-space: nowrap;" <?php echo $current_license_type === 'premium' ? 'disabled' : ''; ?> onmouseover="if(!this.disabled){this.style.background='#0f0f4d'; this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 12px rgba(25, 25, 112, 0.3)'}" onmouseout="if(!this.disabled){this.style.background='#191970'; this.style.transform='translateY(0)'; this.style.boxShadow='none'}">
                            <span style="font-size: 18px;">🎫</span>
                            <?php esc_html_e('Activate', 'vmpfence-security'); ?>
                        </button>
                    </div>
                    <?php if ($current_license_type === 'premium') : ?>
                        <p style="margin: 8px 0 0; color: #646970; font-size: 13px; font-family: 'Inter', sans-serif;">
                            ℹ️ A premium license is already active. Deactivate it first to activate a new one.
                        </p>
                    <?php endif; ?>
                </form>

                <!-- Deactivate License -->
                <form method="post" id="vmpfence-deactivate-form">
                    <?php wp_nonce_field('vmpfence_api_management', 'vmpfence_api_management_nonce'); ?>
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; font-family: 'Inter', sans-serif; color: #1d2327; font-size: 14px;">
                        <?php esc_html_e('Deactivate Current License', 'vmpfence-security'); ?>
                    </label>
                    <button type="submit" name="deactivate_license" style="width: 100%; height: 48px; background: <?php echo empty($current_license_key) ? 'transparent' : 'transparent'; ?>; color: <?php echo empty($current_license_key) ? '#c3c4c7' : '#d63638'; ?>; border: 2px solid <?php echo empty($current_license_key) ? '#c3c4c7' : '#d63638'; ?>; border-radius: 12px; font-family: 'Inter', sans-serif; font-weight: 600; font-size: 14px; cursor: <?php echo empty($current_license_key) ? 'not-allowed' : 'pointer'; ?>; transition: all 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px;" <?php echo empty($current_license_key) ? 'disabled' : ''; ?> onmouseover="if(!this.disabled){this.style.background='#d63638'; this.style.color='#ffffff';}" onmouseout="if(!this.disabled){this.style.background='transparent'; this.style.color='#d63638';}">
                        <span style="font-size: 18px;">⛔</span>
                        <?php esc_html_e('Deactivate License', 'vmpfence-security'); ?>
                    </button>
                    <?php if (empty($current_license_key)) : ?>
                        <p style="margin: 8px 0 0; color: #646970; font-size: 13px; font-family: 'Inter', sans-serif;">
                            ℹ️ No premium license is currently active.
                        </p>
                    <?php endif; ?>
                </form>
            </div>

            <?php 
            // Display results for license actions
            foreach (['activate_license', 'deactivate_license'] as $action) {
                if (isset($api_test_results[$action])) {
                    $test = $api_test_results[$action];
                    ?>
                    <div class="vmpfence-test-result vmpfence-test-<?php echo $test['success'] ? 'success' : 'error'; ?>" style="margin-top: 20px; padding: 16px 20px; border-left: 4px solid; border-radius: 12px; font-family: 'Inter', sans-serif;">
                        <strong style="font-weight: 600; font-size: 14px;"><?php echo $test['success'] ? '✅ Success' : '❌ Failed'; ?></strong>
                        <span style="color: #646970; font-size: 13px; margin-left: 12px;">(<?php echo esc_html($test['time_ms']); ?>ms)</span>
                        <details style="margin-top: 12px;">
                            <summary style="cursor: pointer; color: #646970; font-weight: 600; font-size: 13px;">View Response</summary>
                            <pre style="background: #f6f7f7; padding: 16px; border: 1px solid #c3c4c7; border-radius: 12px; overflow-x: auto; max-height: 200px; font-size: 12px; margin-top: 10px; font-family: 'Consolas', 'Monaco', monospace;"><?php echo esc_html(print_r($test['result'], true)); ?></pre>
                        </details>
                    </div>
                    <?php
                }
            }
            ?>
        </div>

    </div>
</div>

<style>
.vmpfence-api-management .vmpfence-api-card {
    background: #ffffff;
    border: 1px solid #c3c4c7;
    /* border-radius: 12px; */
    padding: 24px;
    margin: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.vmpfence-api-management .vmpfence-test-result {
    padding: 16px 20px;
    border-left: 4px solid;
    border-radius: 12px;
    font-family: 'Inter', sans-serif;
}

.vmpfence-api-management .vmpfence-test-success {
    background: #d4edda;
    border-color: #46b450;
    color: #155724;
}

.vmpfence-api-management .vmpfence-test-error {
    background: #fff3cd;
    border-color: #F5A623;
    color: #856404;
}
</style>

<script>
jQuery(document).ready(function($) {
    // License Activation Success Toast
    var urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('license_activated') === '1') {
        // Wait for toast system to initialize
        setTimeout(function() {
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showSuccess(
                    'Your premium license has been activated and all premium features are now unlocked.',
                    5000,
                    '✓ License Activated Successfully!'
                );
                
                // Clean URL (remove query param without reload)
                var cleanUrl = window.location.pathname + '?page=vmpfence-dashboard';
                window.history.replaceState({}, document.title, cleanUrl);
            }
        }, 100);
    }
    
    // Deactivation Confirmation Modal
    $('#vmpfence-deactivate-form').on('submit', function(e) {
        e.preventDefault(); // Always prevent default first
        
        var $form = $(this);
        
        // Show toast confirmation modal
        VMPFenceNotifications.showConfirmModal({
            title: 'Deactivate Premium License',
            message: 'Are you sure you want to deactivate the license? All premium features will be disabled.',
            confirmText: 'Deactivate',
            cancelText: 'Cancel',
            type: 'danger',
            showIcon: true
        }).then(function(confirmed) {
            if (confirmed) {
                // CRITICAL: Add hidden input for submit button name
                // When using $form[0].submit(), the button's name/value is NOT included in POST data
                // This causes PHP handler to fail because it checks isset($_POST['deactivate_license'])
                $('<input>').attr({
                    type: 'hidden',
                    name: 'deactivate_license',
                    value: '1'
                }).appendTo($form);
                
                // Now submit the form using native DOM (bypasses jQuery event handlers to avoid infinite loop)
                $form[0].submit();
            }
            // If cancelled, do nothing - form won't submit
        });
        
        return false; // Prevent default form submission
    });
});

// Copy license key to clipboard
var copyLicenseKeyTimeout = null; // Track timeout to prevent memory leaks
var copyLicenseKeyInProgress = false; // Prevent concurrent executions
var vmpfenceNotificationsInitialized = false; // Track if notifications are initialized

function copyLicenseKey(event) {
    // Prevent concurrent executions (debounce)
    if (copyLicenseKeyInProgress) {
        // console.log('Copy already in progress, ignoring duplicate request');
        return;
    }
    
    // Prevent default button behavior
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    
    // Validate element exists
    const element = document.getElementById('license-key-display');
    if (!element) {
        console.error('License key display element not found');
        return;
    }
    
    // Get license key and validate it's not empty
    // Use innerText instead of textContent to avoid HTML whitespace issues
    const licenseKey = (element.innerText || element.textContent || '').trim();
    if (!licenseKey) {
        console.error('License key is empty');
        if (typeof VMPFenceNotifications !== 'undefined') {
            initializeNotifications();
            VMPFenceNotifications.showToast('No license key available to copy', 'error');
        }
        return;
    }
    
    // Set flag to prevent concurrent executions
    copyLicenseKeyInProgress = true;
    
    const btn = event ? event.target.closest('button') : null;
    const originalHTML = btn ? btn.innerHTML : null;
    
    // Safely get computed background style
    var originalBackground = '#191970'; // Default fallback
    if (btn) {
        if (btn.style.background) {
            originalBackground = btn.style.background;
        } else {
            try {
                const computedStyle = window.getComputedStyle(btn);
                if (computedStyle && computedStyle.background) {
                    originalBackground = computedStyle.background;
                }
            } catch (e) {
                console.warn('Failed to get computed style:', e);
            }
        }
    }
    
    // Helper function to initialize notifications once
    function initializeNotifications() {
        if (!vmpfenceNotificationsInitialized && typeof VMPFenceNotifications !== 'undefined' && typeof VMPFenceNotifications.init === 'function') {
            try {
                VMPFenceNotifications.init();
                vmpfenceNotificationsInitialized = true;
            } catch (e) {
                console.error('Failed to initialize notifications:', e);
            }
        }
    }
    
    // Helper function to reset button state
    function resetButton() {
        if (btn && originalHTML) {
            btn.innerHTML = originalHTML;
            btn.style.background = originalBackground;
        }
        // Always reset flag
        copyLicenseKeyInProgress = false;
    }
    
    // Helper function to show success feedback
    function showSuccess() {
        // Clear any existing timeout
        if (copyLicenseKeyTimeout) {
            clearTimeout(copyLicenseKeyTimeout);
            copyLicenseKeyTimeout = null;
        }
        
        if (btn) {
            btn.innerHTML = '✓ Copied!';
            btn.style.background = '#46b450';
            
            copyLicenseKeyTimeout = setTimeout(resetButton, 2000);
        } else {
            // No button to update, just reset flag
            copyLicenseKeyInProgress = false;
        }
        
        // Initialize and show toast notification
        if (typeof VMPFenceNotifications !== 'undefined') {
            initializeNotifications();
            try {
                VMPFenceNotifications.showToast('License key copied to clipboard successfully!', 'success');
            } catch (e) {
                console.error('Failed to show success toast:', e);
            }
        }
    }
    
    // Helper function to show error
    function showError(err) {
        console.error('Copy failed:', err);
        
        // Reset button state on error
        resetButton();
        
        // Initialize and show toast notification
        if (typeof VMPFenceNotifications !== 'undefined') {
            initializeNotifications();
            try {
                VMPFenceNotifications.showToast('Failed to copy license key. Please try selecting and copying manually.', 'error');
            } catch (e) {
                console.error('Failed to show error toast:', e);
            }
        }
    }
    
    // Check if we're in a secure context (HTTPS or localhost)
    const isSecureContext = window.isSecureContext !== false && (window.location.protocol === 'https:' || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
    
    // Modern Clipboard API (preferred) - requires secure context
    if (isSecureContext && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
        navigator.clipboard.writeText(licenseKey)
            .then(showSuccess)
            .catch(function(err) {
                // Clipboard API failed, try fallback
                console.warn('Clipboard API failed, trying fallback method:', err);
                copyWithFallback(licenseKey, showSuccess, showError);
            });
    } else {
        // Use fallback method directly
        copyWithFallback(licenseKey, showSuccess, showError);
    }
}

// Fallback copy method for older browsers or insecure contexts
function copyWithFallback(text, onSuccess, onError) {
    var textArea = null;
    var appended = false;
    
    try {
        textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        textArea.style.opacity = '0';
        textArea.style.pointerEvents = 'none';
        textArea.setAttribute('readonly', ''); // Prevent mobile keyboard
        textArea.setAttribute('aria-hidden', 'true'); // Hide from screen readers
        textArea.setAttribute('tabindex', '-1'); // Not focusable via tab
        
        document.body.appendChild(textArea);
        appended = true;
        
        textArea.focus();
        textArea.select();
        
        // iOS requires different approach
        if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
            try {
                const range = document.createRange();
                range.selectNodeContents(textArea);
                const selection = window.getSelection();
                if (selection) {
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
                textArea.setSelectionRange(0, 999999);
            } catch (iosErr) {
                console.warn('iOS selection failed, trying standard select:', iosErr);
            }
        }
        
        const successful = document.execCommand('copy');
        
        if (successful) {
            onSuccess();
        } else {
            onError(new Error('execCommand returned false'));
        }
    } catch (err) {
        onError(err);
    } finally {
        // Cleanup: Only remove if successfully appended and still in DOM
        try {
            if (appended && textArea && textArea.parentNode) {
                document.body.removeChild(textArea);
            }
        } catch (cleanupErr) {
            console.warn('Cleanup failed:', cleanupErr);
        }
    }
}

// Clear browser cache on license activation/deactivation
<?php if ($show_activation_success || $show_deactivation_success) : ?>
(function() {
    if (window.jQuery && jQuery.ajaxSetup) {
        jQuery.ajaxSetup({ cache: false });
    }
    
    if (window.fetch) {
        const originalFetch = window.fetch;
        window.fetch = function() {
            const args = arguments;
            if (args[1] && typeof args[1] === 'object') {
                args[1].cache = 'no-store';
            } else {
                args[1] = { cache: 'no-store' };
            }
            return originalFetch.apply(this, args);
        };
    }
    
    // console.log('✓ License <?php echo $show_activation_success ? 'activated' : 'deactivated'; ?> - browser cache cleared');
    
    // Show success notification
    jQuery(document).ready(function($) {
        if (typeof VMPFenceNotifications !== 'undefined') {
            <?php if ($show_activation_success): ?>
            VMPFenceNotifications.showToast('License activated successfully! Premium features are now enabled.', 'success');
            <?php elseif ($show_deactivation_success): ?>
            VMPFenceNotifications.showToast('License deactivated successfully. You are now using the free version.', 'success');
            <?php endif; ?>
            
            // Clean URL without reloading (remove query params from address bar)
            if (window.history && window.history.replaceState) {
                const url = new URL(window.location.href);
                url.searchParams.delete('license_activated');
                url.searchParams.delete('license_deactivated');
                url.searchParams.delete('cache_bust');
                window.history.replaceState({}, document.title, url.toString());
            }
        }
    });
})();
<?php endif; ?>
</script>
