<?php
/**
 * ExploreXR Premium License Page - Completely Rewritten
 * Modern, responsive design with enhanced UX and functionality
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Render the license page with modern design
 */
function explorexr_premium_license_page() {
    // Get license handler using the correct function or class
    if (function_exists('ExploreXR_License_Handler')) {
        $license_handler = ExploreXR_License_Handler();
    } elseif (class_exists('ExploreXR_License_Handler')) {
        $license_handler = ExploreXR_License_Handler::instance();
    } else {
        // License handler not available
        ?>
        <div class="wrap">
            <h1>ExploreXR License Manager</h1>
            <div class="notice notice-error">
                <p><strong>Error:</strong> License system not available. Please check your ExploreXR Premium installation.</p>
            </div>
        </div>
        <?php
        return;
    }
    
    // Get license data
    $license_data = $license_handler->get_license_data();
    $license_status = isset($license_data['status']) ? $license_data['status'] : 'inactive';
    $license_key = isset($license_data['key']) ? $license_data['key'] : '';
    $license_tier = isset($license_data['tier']) ? $license_data['tier'] : 'free';
    $license_error = isset($license_data['error']) ? $license_data['error'] : '';
    $license_expires = isset($license_data['expires']) ? $license_data['expires'] : '';
    
    // Get available add-ons
    $addons = $license_handler->get_addons();
    $activated_addons = $license_handler->get_activated_addons();
    $max_addons = $license_handler->get_max_addons();
    $license_tiers = $license_handler->get_license_tiers();
    
    // Calculate days until expiration
    $days_until_expiry = 0;
    $is_expiring_soon = false;
    if (!empty($license_expires)) {
        $expiry_timestamp = strtotime($license_expires);
        $current_timestamp = current_time('timestamp');
        $days_until_expiry = max(0, ceil(($expiry_timestamp - $current_timestamp) / DAY_IN_SECONDS));
        $is_expiring_soon = $days_until_expiry <= 30 && $days_until_expiry > 0;
    }
    
    ?>
    <div class="wrap explorexr-premium-license-page">
        <?php 
        $page_title = 'ExploreXR License Manager';
        include EXPLOREXR_PLUGIN_DIR . 'admin/templates/admin-header.php'; 
        ?>
        
        
        <!-- License Status Section -->
        <div class="explorexr-premium-license-section">
            <h2><span class="dashicons dashicons-admin-network"></span> Your License</h2>
            <div class="explorexr-premium-license-section-content">
                <?php if ($license_status === 'active'): ?>
                    <div class="explorexr-premium-license-info active">
                        <div class="explorexr-premium-license-tier">
                            <span class="dashicons <?php echo esc_attr($is_expiring_soon ? 'dashicons-warning' : 'dashicons-yes-alt'); ?>"></span>
                            <span class="tier-name">ExploreXR <?php echo esc_html(ucfirst($license_tier)); ?></span>
                            <span class="<?php echo esc_attr($is_expiring_soon ? 'license-inactive' : 'license-active'); ?>">
                                <?php echo $is_expiring_soon ? esc_html("Expires in {$days_until_expiry} days") : esc_html('Active'); ?>
                            </span>
                        </div>
                        
                        <div class="explorexr-premium-license-details">
                            <p><strong>License Key:</strong> <?php echo esc_html(substr($license_key, 0, 8) . '••••••••••••'); ?></p>
                            <p><strong>License Tier:</strong> <?php echo esc_html(strtoupper($license_tier)); ?></p>
                            <?php if (!empty($license_expires)): ?>
                                <p><strong>Expires:</strong> <?php echo esc_html(gmdate('M j, Y', strtotime($license_expires))); ?></p>
                            <?php endif; ?>
                            <p><strong>Max Add-ons:</strong> <?php echo $max_addons < 0 ? esc_html('Unlimited') : esc_html($max_addons); ?></p>
                        </div>
                        
                        <?php if ($is_expiring_soon): ?>
                            <div class="explorexr-premium-license-validation-result">
                                <div class="notice notice-warning inline">
                                    <p><strong>⚠️ License Expiring Soon!</strong> Your license expires in <?php echo esc_html($days_until_expiry); ?> days.
                                    <a href="https://expoxr.com/explorexr/" target="_blank">Renew now</a> to continue using premium features.</p>
                                </div>
                            </div>
                        <?php endif; ?>

                        <form class="explorexr-premium-license-form deactivate">
                            <?php wp_nonce_field('explorexr_premium_license_nonce', 'explorexr_premium_license_nonce'); ?>
                            <button type="button" class="button button-secondary explorexr-premium-validate-current-license">
                                <span class="dashicons dashicons-update"></span> Re-validate License
                            </button>
                            <button type="button" class="button button-secondary explorexr-premium-deactivate-license">
                                <span class="dashicons dashicons-unlock"></span> Deactivate License
                            </button>
                        </form>
                        
                    </div>
                <?php else: ?>
                    <div class="explorexr-premium-license-info inactive">
                        <div class="explorexr-premium-license-tier">
                            <span class="dashicons dashicons-warning"></span>
                            <span class="tier-name">No License Active</span>
                            <span class="license-inactive">License required for premium features</span>
                        </div>
                        
                        <form class="explorexr-premium-license-form activate">
                            <?php wp_nonce_field('explorexr_premium_license_nonce', 'explorexr_premium_license_nonce'); ?>
                            <div class="explorexr-premium-license-input-group">
                                <input type="text" 
                                       name="license_key" 
                                       placeholder="Enter your license key (e.g., PRO-XXXX-XXXX-XXXX-XXXX-XXXX-EXXR)" 
                                       class="regular-text" 
                                       value="<?php echo esc_attr($license_key); ?>"
                                       maxlength="50">
                                <button type="button" class="button button-primary explorexr-premium-activate-license">
                                    <span class="dashicons dashicons-lock"></span> Activate License
                                </button>
                            </div>
                            
                            <?php if (!empty($license_error)): ?>
                                <div class="explorexr-premium-license-validation-result">
                                    <div class="notice notice-error inline">
                                        <p><?php echo esc_html($license_error); ?></p>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </form>
                    </div>
                <?php endif; ?>
                
                <!-- Response Messages Container -->
                <div class="explorexr-premium-license-validation-result" style="display: none;"></div>
            </div>
        </div>
        
        <!-- Add-ons Quick Link Section -->
        <?php if ($license_status === 'active'): ?>
            <div class="explorexr-premium-addons-section">
                <h2>
                    <span class="dashicons dashicons-admin-plugins"></span> 
                    Add-ons Management
                </h2>
                
                <div class="addon-summary">
                    <div class="addon-stats">
                        <div class="stat-box">
                            <span class="stat-number"><?php echo count($activated_addons); ?></span>
                            <span class="stat-label">Active Add-ons</span>
                        </div>
                        <div class="stat-box">
                            <span class="stat-number"><?php echo esc_html($max_addons < 0 ? '∞' : $max_addons); ?></span>
                            <span class="stat-label">Maximum Allowed</span>
                        </div>
                    </div>
                    
                    <div class="addon-actions">
                        <a href="<?php echo esc_url(admin_url('admin.php?page=explorexr-addons')); ?>" class="button button-primary button-large">
                            <span class="dashicons dashicons-admin-plugins"></span> Manage Add-ons
                        </a>
                        <p class="description">Configure which add-ons are active and manage their global settings</p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <!-- License Tiers Section -->
        <div class="explorexr-premium-upgrade-section">
            <h2><span class="dashicons dashicons-star-filled"></span> License Tiers</h2>
            <div class="explorexr-premium-tiers-grid">
                <?php foreach ($license_tiers as $tier_id => $tier): ?>
                    <?php
                    // Skip free tier (not a purchasable plan) and trial tier
                    // (trial is temporary and not a tier users upgrade "to" from here).
                    if ($tier_id === 'free' || $tier_id === 'trial') {
                        continue;
                    }
                    ?>
                    <?php
                    // Determine tier hierarchy: pro(1) < plus(2) < ultra(3).
                    // Trial is treated as equivalent to plus for upgrade/downgrade display.
                    $tier_hierarchy = array('trial' => 2, 'pro' => 1, 'plus' => 2, 'ultra' => 3);
                    $current_tier_level = isset($tier_hierarchy[$license_tier]) ? $tier_hierarchy[$license_tier] : 0;
                    $this_tier_level = isset($tier_hierarchy[$tier_id]) ? $tier_hierarchy[$tier_id] : 0;
                    $is_current = $license_tier === $tier_id;
                    $is_upgrade = $this_tier_level > $current_tier_level;
                    $is_downgrade = $this_tier_level < $current_tier_level;
                    ?>
                    <div class="explorexr-premium-tier-card <?php echo esc_attr($is_current ? 'current-tier' : ''); ?>">
                        <div class="tier-header">
                            <h3>ExploreXR <?php echo esc_html(ucfirst($tier_id)); ?></h3>
                            <?php if ($is_current): ?>
                                <span class="current-tier-badge">Current Plan</span>
                            <?php endif; ?>
                        </div>
                        
                        <div class="tier-features">
                            <p><strong>Add-ons:</strong> 
                                <?php 
                                if ($tier['max_addons'] < 0) {
                                    echo 'All 9 add-ons included';
                                } elseif ($tier['max_addons'] === 0) {
                                    echo 'No add-ons';
                                } else {
                                    echo 'Choose any ' . esc_html($tier['max_addons']) . ' add-on' . ($tier['max_addons'] > 1 ? 's' : '');
                                }
                                ?>
                            </p>
                            <p><?php echo esc_html($tier['description']); ?></p>
                            <p><strong>Features:</strong></p>
                            <ul style="text-align: left; margin: 10px 0;">
                                <li>Premium support</li>
                                <li>Regular updates</li>
                                <li>Commercial license</li>
                                <?php if ($tier_id === 'ultra'): ?>
                                    <li>Priority development requests</li>
                                    <li>Custom integrations</li>
                                <?php elseif ($tier_id === 'plus'): ?>
                                    <li>Advanced features</li>
                                    <li>Extended support</li>
                                <?php endif; ?>
                            </ul>
                        </div>
                        
                        <?php if (!$is_current): ?>
                            <a href="https://expoxr.com/explorexr/pricing/?tier=<?php echo esc_attr($tier_id); ?>&current=<?php echo esc_attr($license_tier); ?>" 
                               target="_blank" 
                               class="button <?php echo $is_upgrade ? 'button-primary' : 'button-secondary'; ?> tier-upgrade-btn">
                                <?php 
                                if ($license_tier === 'free') {
                                    echo esc_html('Get ' . ucfirst($tier_id));
                                } elseif ($is_upgrade) {
                                    echo '<span class="dashicons dashicons-arrow-up-alt"></span> ' . esc_html('Upgrade to ' . ucfirst($tier_id));
                                } else {
                                    echo '<span class="dashicons dashicons-arrow-down-alt"></span> ' . esc_html('Downgrade to ' . ucfirst($tier_id));
                                }
                                ?>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <?php if ($license_status === 'active'): ?>
                <div class="tier-change-note" style="margin-top: 20px; padding: 15px; background: #f0f6fc; border-left: 4px solid #2AACE2; border-radius: 4px;">
                    <p style="margin: 0;">
                        <strong>ℹ️ Note:</strong> 
                        <?php if ($license_tier === 'pro'): ?>
                            You can <strong>upgrade</strong> to <strong>Plus</strong> (4 addons) or <strong>Ultra</strong> (all addons), 
                            or <strong>downgrade</strong> if you need fewer addons. Your current addon selections will be preserved where possible.
                        <?php elseif ($license_tier === 'plus'): ?>
                            You can <strong>upgrade</strong> to <strong>Ultra</strong> (all addons) for unlimited access, 
                            or <strong>downgrade</strong> to <strong>Pro</strong> (2 addons) if you need fewer. Your current addon selections will be preserved where possible.
                        <?php elseif ($license_tier === 'ultra'): ?>
                            You have unlimited access to all addons! You can <strong>downgrade</strong> to <strong>Plus</strong> (4 addons) 
                            or <strong>Pro</strong> (2 addons) if needed. You'll need to select which addons to keep after downgrading.
                        <?php endif; ?>
                    </p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Help & Support Section -->
        <div class="explorexr-premium-help-section">
            <h2><span class="dashicons dashicons-sos"></span> Need Help?</h2>
            <div class="help-grid">
                <div class="help-item">
                    <h3>📚 Documentation</h3>
                    <p>Comprehensive guides and tutorials for getting started with ExploreXR Premium and license management.</p>
                    <p><a href="https://expoxr.com/docs/" target="_blank" class="button button-secondary">View Documentation</a></p>
                </div>
                
                <div class="help-item">
                    <h3>💬 Support Forum</h3>
                    <p>Get help from our community and support team. Connect with other ExploreXR users and developers.</p>
                    <p><a href="https://expoxr.com/support/" target="_blank" class="button button-secondary">Get Support</a></p>
                </div>
            </div>
        </div>
        
        <script>
        // Enhanced JavaScript with ExploreXR styling integration
        jQuery(document).ready(function($) {            
            function logLicenseDebug(method, args) {
                if (typeof exploreXRLicense === 'undefined' || !exploreXRLicense.debug) {
                    return;
                }

                if (window.ExploreXRLogger && typeof window.ExploreXRLogger[method] === 'function') {
                    window.ExploreXRLogger[method].apply(window.ExploreXRLogger, args);
                    return;
                }

                if (window.console && typeof window.console[method] === 'function') {
                    window.console[method].apply(window.console, args);
                }
            }

            // Enhanced message display using ExploreXR notice system
            function showLicenseMessage(message, type, container) {
                const noticeClasses = {
                    success: 'notice-success',
                    error: 'notice-error', 
                    warning: 'notice-warning',
                    info: 'notice-info'
                };
                
                const noticeHtml = `
                    <div class="notice ${noticeClasses[type] || 'notice-info'} inline">
                        <p>${message}</p>
                    </div>
                `;
                
                container.html(noticeHtml).show();
                
                // Auto-hide success messages after 5 seconds
                if (type === 'success') {
                    setTimeout(() => {
                        container.fadeOut();
                    }, 5000);
                }
            }
            
            // Button loading state with dashicons
            function setButtonLoading(button, loading) {
                const dashicon = button.find('.dashicons');
                const originalClass = dashicon.attr('class');
                
                if (!button.data('original-dashicon')) {
                    button.data('original-dashicon', originalClass);
                }
                
                if (loading) {
                    button.prop('disabled', true);
                    dashicon.attr('class', 'dashicons dashicons-update spin-animation');
                } else {
                    button.prop('disabled', false);
                    dashicon.attr('class', button.data('original-dashicon'));
                }
            }
            
            // Add spinning animation for loading state
            $('<style>').text('.spin-animation { animation: spin 1s linear infinite; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }').appendTo('head');
            
            // Re-validate current license
            $('.explorexr-premium-validate-current-license').off('click').on('click', function(e) {
                e.preventDefault();
                
                const button = $(this);
                const form = button.closest('form');
                const resultDiv = $('.explorexr-premium-license-validation-result');
                
                // For re-validation, use the stored license key from PHP, not the input field
                const storedLicenseKey = '<?php echo esc_js($license_key); ?>';
                
                if (!storedLicenseKey) {
                    showLicenseMessage('No license key found to validate.', 'warning', resultDiv);
                    return;
                }
                
                setButtonLoading(button, true);
                resultDiv.hide();
                
                $.ajax({
                    url: exploreXRLicense.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'explorexr_premium_validate_license_real_time',
                        license_key: storedLicenseKey,
                        nonce: exploreXRLicense.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            showLicenseMessage(response.data.message, response.data.type || 'success', resultDiv);
                        } else {
                            showLicenseMessage(response.data.message, response.data.type || 'error', resultDiv);
                        }
                        setButtonLoading(button, false);
                    },
                    error: function() {
                        showLicenseMessage('Network error occurred while validating the license. Please try again.', 'error', resultDiv);
                        setButtonLoading(button, false);
                    }
                });
            });
            
            // Deactivate license with enhanced debugging
            $('.explorexr-premium-deactivate-license').off('click').on('click', function(e) {
                e.preventDefault();
                
                logLicenseDebug('log', ['[ExploreXR PHP Inline] License deactivation started']);
                logLicenseDebug('log', ['[ExploreXR PHP Inline] exploreXRLicense available:', typeof exploreXRLicense !== 'undefined']);
                
                if (typeof exploreXRLicense === 'undefined') {
                    logLicenseDebug('error', ['[ExploreXR PHP Inline] exploreXRLicense is undefined!']);
                    alert('License system error: JavaScript not properly initialized. Please refresh the page and try again.');
                    return;
                }
                
                // Removed popup confirmation to improve UX
                // License deactivation is now instant without confirmation
                
                const button = $(this);
                const form = button.closest('form');
                const resultDiv = $('.explorexr-premium-license-validation-result');
                
                logLicenseDebug('log', ['[ExploreXR PHP Inline] Form elements found:', {
                    button: button.length,
                    form: form.length,
                    resultDiv: resultDiv.length
                }]);
                
                setButtonLoading(button, true);
                resultDiv.hide();
                
                const ajaxData = {
                    action: 'explorexr_premium_deactivate_license_improved',
                    nonce: exploreXRLicense.nonce
                };
                
                logLicenseDebug('log', ['[ExploreXR PHP Inline] AJAX Data:', ajaxData]);
                logLicenseDebug('log', ['[ExploreXR PHP Inline] AJAX URL:', exploreXRLicense.ajaxUrl]);
                
                $.ajax({
                    url: exploreXRLicense.ajaxUrl,
                    type: 'POST',
                    data: ajaxData,
                    beforeSend: function(xhr, settings) {
                        logLicenseDebug('log', ['[ExploreXR PHP Inline] AJAX Request starting:', {
                            url: settings.url,
                            type: settings.type,
                            data: settings.data
                        }]);
                    },
                    success: function(response, textStatus, xhr) {
                        logLicenseDebug('log', ['[ExploreXR PHP Inline] AJAX Success:', {
                            response: response,
                            textStatus: textStatus,
                            status: xhr.status
                        }]);
                        
                        // Always treat as success since we want to ensure license is deactivated
                        var message = response.success ? 
                            response.data.message : 
                            (response.data && response.data.message ? 
                                response.data.message : 
                                'License has been deactivated locally.');
                                
                        showLicenseMessage(message + ' Reloading page...', 'success', resultDiv);
                        setTimeout(() => {
                            logLicenseDebug('log', ['[ExploreXR PHP Inline] Reloading page after success']);
                            location.reload();
                        }, 2500);
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        logLicenseDebug('log', ['[ExploreXR PHP Inline] AJAX Error:', {
                            status: xhr.status,
                            statusText: xhr.statusText,
                            textStatus: textStatus,
                            errorThrown: errorThrown,
                            responseText: xhr.responseText
                        }]);
                        
                        // Even on AJAX error, show success message since local cleanup should still work
                        showLicenseMessage('License deactivation completed. Some network operations may have failed, but local license has been cleared. Reloading page...', 'success', resultDiv);
                        setTimeout(() => {
                            logLicenseDebug('log', ['[ExploreXR PHP Inline] Reloading page after error']);
                            location.reload();
                        }, 2500);
                    }
                });
            });
            
            // Activate license
            $('.explorexr-premium-activate-license').off('click').on('click', function(e) {
                e.preventDefault();
                
                const button = $(this);
                const form = button.closest('form');
                const resultDiv = $('.explorexr-premium-license-validation-result');
                const licenseKey = form.find('[name="license_key"]').val().trim();
                
                if (!licenseKey) {
                    showLicenseMessage('Please enter a license key.', 'warning', resultDiv);
                    return;
                }
                
                // Enhanced format validation
                if (!/^[A-Z]+-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z]{4}$/i.test(licenseKey)) {
                    showLicenseMessage('Invalid license key format. Expected format: <strong>TIER-XXXX-XXXX-XXXX-XXXX-XXXX-EXXR</strong>', 'warning', resultDiv);
                    return;
                }
                
                setButtonLoading(button, true);
                resultDiv.hide();
                
                $.ajax({
                    url: exploreXRLicense.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'explorexr_premium_activate_license',
                        license_key: licenseKey,
                        nonce: exploreXRLicense.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            showLicenseMessage(response.data.message + ' Reloading page...', 'success', resultDiv);
                            setTimeout(() => location.reload(), 2500);
                        } else {
                            setButtonLoading(button, false);
                            showLicenseMessage(response.data.message, 'error', resultDiv);
                        }
                    },
                    error: function() {
                        setButtonLoading(button, false);
                        showLicenseMessage('Network error occurred while activating the license. Please try again.', 'error', resultDiv);
                    }
                });
            });
            
            // Enhanced license key input formatting
            $('[name="license_key"]').on('input', function() {
                let value = $(this).val().toUpperCase().replace(/[^A-Z0-9-]/g, '');
                
                // Auto-format with hyphens (TIER-XXXX-XXXX-XXXX-XXXX-XXXX-EXXR)
                if (value.length > 4 && value.indexOf('-') === -1) {
                    const compact = value.replace(/-/g, '');
                    const prefixes = ['ULTRA', 'PLUS', 'PRO', 'EXTR'];
                    const prefix = prefixes.find((item) => compact.indexOf(item) === 0);

                    if (prefix) {
                        const groups = compact.slice(prefix.length).match(/.{1,4}/g) || [];
                        value = [prefix].concat(groups.slice(0, 6)).join('-');
                    }
                }
                
                $(this).val(value);
                
                // Visual feedback for format validity
                const isValidFormat = /^(ULTRA|PLUS|PRO|EXTR)-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-EXXR$/i.test(value);
                if (value.length > 10) {
                    $(this).css('border-color', isValidFormat ? '#2AACE2' : '#dc3545');
                } else {
                    $(this).css('border-color', '');
                }
            });
            
            // Add tooltip for license key format
            $('[name="license_key"]').attr('title', 'Format: TIER-XXXX-XXXX-XXXX-XXXX-XXXX-EXXR\nValid tiers: PRO, PLUS, ULTRA, EXTR');
        });
        </script>
    </div>
    <?php
}
