<?php
if ( ! defined( 'ABSPATH' ) ) exit;

// Load license manager
require_once WP_PLUGIN_DIR . '/blogibot/src/License/LicenseManager.php';

$license_status = Blog82AI_License_Manager::get_license_status();
$is_valid = Blog82AI_License_Manager::is_license_valid();
?>

<div class="blog82ai-license-management">
    <div class="blog82ai-page-header">
        <h2 class="blog82ai-page-header-title">License Management</h2>
        <p>Please activate your Blogibot license to access AI Blog and Feed features.</p>
    </div>

    <?php if ($is_valid): ?>
        <!-- Active License Display -->
            <div class="blog82ai-form-section blog82ai-license-active-section blog82ai-license-active">
            <div class="blog82ai-license-status-header">
                <span class="dashicons dashicons-yes-alt blog82ai-license-icon-success"></span>
                <h3>License Active</h3>
            </div>
            <div class="blog82ai-license-details">
                <div class="blog82ai-form-row">
                    <div class="blog82ai-form-group">
                        <label>License Key</label>
                        <input type="text" value="<?php echo esc_attr(substr($license_status['license_key'], 0, 10) . '...'); ?>" readonly>
                    </div>
                    <div class="blog82ai-form-group">
                        <label>Domain</label>
                        <input type="text" value="<?php echo esc_attr($license_status['domain']); ?>" readonly>
                    </div>
                </div>
                <div class="blog82ai-form-group">
                    <label>Activated Date</label>
                    <input type="text" value="<?php echo esc_attr(date('F j, Y', strtotime($license_status['activated_at']))); ?>" readonly>
                </div>
            </div>
            <div class="blog82ai-form-actions">
                <button type="button" class="button button-secondary" onclick="showModifyLicense()">
                    Modify License
                </button>
                <button type="button" class="button button-link-delete" onclick="removeLicense()">
                    Remove License
                </button>
            </div>
        </div>

        <!-- Hidden modify form -->
        <div id="modify-license-form" class="blog82ai-form-section" style="display: none;">
            <h3 class="blog82ai-form-section-title">Modify License</h3>
            <form id="license-form" method="post">
                <div class="blog82ai-form-row">
                    <div class="blog82ai-form-group">
                        <label for="license_key">License Key</label>
                        <input type="text" 
                               id="license_key" 
                               name="license_key" 
                               value="<?php echo esc_attr($license_status['license_key']); ?>" 
                               placeholder="Enter your license key" 
                               required>
                    </div>
                    <div class="blog82ai-form-group">
                        <label for="domain">Domain Name</label>
                        <input type="text" 
                               id="domain" 
                               name="domain" 
                               value="<?php echo esc_attr($license_status['domain']); ?>" 
                               placeholder="example.com" 
                               required>
                        <small>Enter your domain name without http:// or https://</small>
                    </div>
                </div>
                <div class="blog82ai-form-actions">
                    <button type="submit" class="button button-primary">Update License</button>
                    <button type="button" class="button button-secondary" onclick="cancelModify()">Cancel</button>
                </div>
            </form>
        </div>

    <?php else: ?>
        <!-- License Information Note -->
        <div class="blog82ai-license-info-note">
            <div class="blog82ai-note-icon">
                <span class="dashicons dashicons-info-outline"></span>
            </div>
            <div class="blog82ai-note-content">
                <h4>Need a License?</h4>
                <p>Get your Blogibot license from our website to unlock all premium features including AI Blog Generation, Feed Management, and advanced SEO tools.</p>
                <a href="https://myapps.wontonee.com" target="_blank" rel="noopener noreferrer" class="button button-primary">
                    <span class="dashicons dashicons-external" style="margin-top: 3px;"></span>
                    Get License from MyApps.Wontonee.com
                </a>
            </div>
        </div>
        
        <!-- License Activation Form -->
        <div class="blog82ai-form-section">
            <div class="blog82ai-license-status-header">
                <span class="dashicons dashicons-lock blog82ai-license-icon-warning"></span>
                <h3 class="blog82ai-form-section-title">Activate Your License</h3>
            </div>
            <p class="blog82ai-license-description">Enter your license key and domain to unlock all Blogibot features.</p>
            
            <form id="license-form" method="post">
                <div class="blog82ai-form-row">
                    <div class="blog82ai-form-group">
                        <label for="license_key">License Key</label>
                        <input type="text" 
                               id="license_key" 
                               name="license_key" 
                               placeholder="Enter your license key" 
                               required>
                    </div>
                    <div class="blog82ai-form-group">
                        <label for="domain">Domain Name</label>
                        <input type="text" 
                               id="domain" 
                               name="domain" 
                               placeholder="example.com" 
                               required>
                        <small>Enter your domain name without http:// or https://</small>
                    </div>
                </div>
                <div class="blog82ai-form-actions">
                    <button type="submit" class="button button-primary">Activate License</button>
                </div>
            </form>
        </div>

        <!-- Elegant License CTA -->
        <div class="blog82ai-form-section blog82ai-license-cta-section">
            <div class="blog82ai-license-cta">
                <div class="blog82ai-license-cta-content">
                    <div class="blog82ai-license-cta-icon"><span class="dashicons dashicons-awards"></span></div>
                    <div class="blog82ai-license-cta-text">
                        <h4>Need a license?</h4>
                        <p>Get a Blogibot license to unlock all AI Blog and Feed features. Visit our licensing portal to choose a plan and obtain your license key.</p>
                    </div>
                </div>
                <div class="blog82ai-license-cta-actions">
                    <a class="button button-primary" href="https://myapps.wontonee.com" target="_blank" rel="noopener">Get a License</a>
                    <a class="button" href="https://myapps.wontonee.com" target="_blank" rel="noopener">Learn more</a>
                </div>
            </div>
        </div>

        <!-- Features Preview -->
        <div class="blog82ai-form-section">
            <h3 class="blog82ai-form-section-title">Unlock These Features</h3>
            <div class="blog82ai-features-grid">
                <div class="blog82ai-feature-card">
                    <div class="blog82ai-feature-icon">
                        <span class="dashicons dashicons-admin-post"></span>
                    </div>
                    <h4>AI Blog Generation</h4>
                    <p>Create SEO-optimized blog posts with AI assistance</p>
                </div>
                <div class="blog82ai-feature-card">
                    <div class="blog82ai-feature-icon">
                        <span class="dashicons dashicons-calendar-alt"></span>
                    </div>
                    <h4>Scheduled Publishing</h4>
                    <p>Automate your content calendar with smart scheduling</p>
                </div>
                <div class="blog82ai-feature-card">
                    <div class="blog82ai-feature-icon">
                        <span class="dashicons dashicons-rss"></span>
                    </div>
                    <h4>Feed Management</h4>
                    <p>Import and manage content from RSS feeds</p>
                </div>
                <div class="blog82ai-feature-card">
                    <div class="blog82ai-feature-icon">
                        <span class="dashicons dashicons-chart-line"></span>
                    </div>
                    <h4>SEO Analytics</h4>
                    <p>Track and optimize your content performance</p>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php if (defined('WP_DEBUG') && WP_DEBUG): ?>
<!-- Debug/API Information Section -->
<div class="blog82ai-form-section" style="border: 2px dashed #ffb900; background: #fff8e1;">
    <h3 style="color: #ff8f00;">🔧 Debug Information</h3>
    <p style="color: #666; font-size: 12px;">This section is only visible in debug mode.</p>
    
    <div class="blog82ai-form-row">
        <div class="blog82ai-form-group">
            <label><strong>API Environment</strong></label>
            <div style="background: #f9f9f9; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px;">
                <?php
                require_once WP_PLUGIN_DIR . '/blogibot/src/API/Routes.php';
                $env_info = Blog82AI_API_Routes::get_environment_info();
                echo "Environment: " . $env_info['environment'] . "<br>";
                echo "Base URL: " . $env_info['base_url'] . "<br>";
                echo "Is Production: " . ($env_info['is_production'] ? 'Yes' : 'No') . "<br>";
                echo "Is Local: " . ($env_info['is_local'] ? 'Yes' : 'No');
                ?>
            </div>
        </div>
        <div class="blog82ai-form-group">
            <label><strong>Available Endpoints</strong></label>
            <div style="background: #f9f9f9; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto;">
                <?php
                $endpoints = Blog82AI_API_Routes::get_endpoints_by_category('license');
                foreach ($endpoints as $key => $config) {
                    $full_url = Blog82AI_API_Routes::get_endpoint_url($key);
                    echo "<strong>{$key}</strong><br>";
                    echo "&nbsp;&nbsp;{$config['method']} {$full_url}<br>";
                    echo "&nbsp;&nbsp;{$config['description']}<br><br>";
                }
                ?>
            </div>
        </div>
    </div>
    
    <div class="blog82ai-form-actions">
        <button type="button" class="button button-secondary" onclick="showApiDebugInfo()">
            Show Full API Debug Info
        </button>
        <button type="button" class="button button-secondary" onclick="validateCurrentLicense()">
            Validate Current License
        </button>
    </div>
</div>
<?php endif; ?>

</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('license-form');
    
    // Add page unload protection to show loading during refresh
    window.addEventListener('beforeunload', function() {
        // Show loading modal during page refresh
        if (document.body.classList.contains('license-processing')) {
            Blog82AI_Modal.showLoadingForReload('Refreshing page...');
        }
    });
    
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(form);
            formData.append('action', 'blog82ai_manage_license');
            formData.append('license_action', 'activate');
            formData.append('_wpnonce', '<?php echo wp_create_nonce("blog82ai_license_nonce"); ?>');
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = 'Processing...';
            submitBtn.disabled = true;
            
            // Show loading modal
            Blog82AI_Modal.showLoading('Activating your license...');
            
            // Add processing class to body for unload detection
            document.body.classList.add('license-processing');
            
            fetch(ajaxurl, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                Blog82AI_Modal.closeLoading();
                
                if (data.success) {
                    Blog82AI_Modal.showSuccess('License Activated', 'Your license has been successfully activated! Refreshing page...', false);
                    // Give user time to see the success message, then reload
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    Blog82AI_Modal.showError('License Activation Failed', data.data || 'Unknown error occurred');
                }
            })
            .catch(error => {
                Blog82AI_Modal.closeLoading();
                document.body.classList.remove('license-processing');
                Blog82AI_Modal.showError('Connection Error', 'An error occurred while activating your license. Please try again.');
                console.error('Error:', error);
            })
            .finally(() => {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            });
        });
    }
});

function showModifyLicense() {
    document.querySelector('.blog82ai-license-active').style.display = 'none';
    document.getElementById('modify-license-form').style.display = 'block';
}

function cancelModify() {
    document.querySelector('.blog82ai-license-active').style.display = 'block';
    document.getElementById('modify-license-form').style.display = 'none';
}

function removeLicense() {
    Blog82AI_Modal.showConfirm(
        'Remove License',
        'Are you sure you want to remove your license? This will disable all Blogibot features.',
        function() {
            // User confirmed, proceed with removal
            const formData = new FormData();
            formData.append('action', 'blog82ai_manage_license');
            formData.append('license_action', 'remove');
            formData.append('_wpnonce', '<?php echo wp_create_nonce("blog82ai_license_nonce"); ?>');
            
            Blog82AI_Modal.showLoading('Removing your license...');
            
            // Add processing class to body for unload detection
            document.body.classList.add('license-processing');
            
            fetch(ajaxurl, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                Blog82AI_Modal.closeLoading();
                
                if (data.success) {
                    Blog82AI_Modal.showSuccess('License Removed', 'Your license has been successfully removed. Refreshing page...', false);
                    // Give user time to see the success message, then reload
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    Blog82AI_Modal.showError('License Removal Failed', data.data || 'Failed to remove license');
                    document.body.classList.remove('license-processing');
                }
            })
            .catch(error => {
                Blog82AI_Modal.closeLoading();
                document.body.classList.remove('license-processing');
                console.error('License removal error details:', error);
                console.error('Error stack:', error.stack);
                Blog82AI_Modal.showError('Connection Error', 'An error occurred while removing your license. Check console for details.');
            });
        }
    );
}

function showApiDebugInfo() {
    const formData = new FormData();
    formData.append('action', 'blog82ai_get_debug_info');
    formData.append('_wpnonce', '<?php echo wp_create_nonce("blog82ai_license_nonce"); ?>');
    
    Blog82AI_Modal.showLoading('Retrieving debug information...');
    
    fetch(ajaxurl, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        Blog82AI_Modal.closeLoading();
        
        if (data.success) {
            console.log('API Debug Info:', data.data);
            Blog82AI_Modal.showSuccess('Debug Information', 'Debug information has been logged to the browser console. Press F12 to view developer tools.', false);
        } else {
            Blog82AI_Modal.showError('Debug Info Failed', data.data || 'Unknown error');
        }
    })
    .catch(error => {
        Blog82AI_Modal.closeLoading();
        console.error('Error:', error);
        Blog82AI_Modal.showError('Debug Info Failed', error.message);
    });
}

function validateCurrentLicense() {
    const formData = new FormData();
    formData.append('action', 'blog82ai_manage_license');
    formData.append('license_action', 'validate');
    formData.append('license_key', '<?php echo esc_js($license_status['license_key'] ?? ''); ?>');
    formData.append('domain', '<?php echo esc_js($license_status['domain'] ?? ''); ?>');
    formData.append('_wpnonce', '<?php echo wp_create_nonce("blog82ai_license_nonce"); ?>');
    
    Blog82AI_Modal.showLoading('Validating your license...');
    
    fetch(ajaxurl, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        Blog82AI_Modal.closeLoading();
        
        if (data.success) {
            Blog82AI_Modal.showSuccess('License Validation', data.data, false);
        } else {
            Blog82AI_Modal.showError('License Validation Failed', data.data);
        }
    })
    .catch(error => {
        Blog82AI_Modal.closeLoading();
        console.error('Error:', error);
        Blog82AI_Modal.showError('Validation Failed', error.message);
    });
}
</script>

<?php
// Ensure WordPress admin footer is properly displayed
do_action('admin_footer');
?>
