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

$validation = USCDN_Validator::validate_config();
?>

<div class="wrap uscdn-tools">
    <?php include USCDN_PLUGIN_DIR . 'admin/views/branding.php'; ?>
    
    <p class="description">
        <?php _e('Test your CDN configuration and manage cache.', 'utility-server-cdn'); ?>
    </p>
    
    <!-- Configuration Validation -->
    <div class="uscdn-section">
        <h2><?php _e('Configuration Status', 'utility-server-cdn'); ?></h2>
        
        <?php if ($validation['valid']): ?>
            <div class="notice notice-success inline">
                <p><strong><?php _e('✓ Configuration Valid', 'utility-server-cdn'); ?></strong></p>
                <p><?php _e('Your CDN configuration is properly set up.', 'utility-server-cdn'); ?></p>
            </div>
        <?php else: ?>
            <div class="notice notice-error inline">
                <p><strong><?php _e('⚠ Configuration Issues Found', 'utility-server-cdn'); ?></strong></p>
                <ul>
                    <?php foreach ($validation['errors'] as $error): ?>
                        <li><?php echo esc_html($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- CDN Testing Tool -->
    <div class="uscdn-section">
        <h2><?php _e('Test CDN Connections', 'utility-server-cdn'); ?></h2>
        <p class="description"><?php _e('Verify that your CDN endpoints are accessible and working correctly.', 'utility-server-cdn'); ?></p>
        
        <div class="uscdn-test-tool">
            <?php if (USCDN_Settings::get('enable_image_cdn')): ?>
                <div class="uscdn-test-item">
                    <h3><?php _e('Image CDN', 'utility-server-cdn'); ?></h3>
                    <p><code><?php echo esc_html(USCDN_Settings::get('cdn_image_base')); ?></code></p>
                    <button type="button" class="button uscdn-test-btn" 
                            data-cdn-url="<?php echo esc_attr(USCDN_Settings::get('cdn_image_base')); ?>" 
                            data-cdn-type="image">
                        <?php _e('Test Connection', 'utility-server-cdn'); ?>
                    </button>
                    <div class="uscdn-test-result"></div>
                </div>
            <?php endif; ?>
            
            <?php if (USCDN_Settings::get('enable_static_cdn')): ?>
                <div class="uscdn-test-item">
                    <h3><?php _e('Static CDN', 'utility-server-cdn'); ?></h3>
                    <p><code><?php echo esc_html(USCDN_Settings::get('cdn_static_base')); ?></code></p>
                    <button type="button" class="button uscdn-test-btn" 
                            data-cdn-url="<?php echo esc_attr(USCDN_Settings::get('cdn_static_base')); ?>" 
                            data-cdn-type="static">
                        <?php _e('Test Connection', 'utility-server-cdn'); ?>
                    </button>
                    <div class="uscdn-test-result"></div>
                </div>
            <?php endif; ?>
            
            <?php if (USCDN_Settings::get('enable_link_cdn')): ?>
                <div class="uscdn-test-item">
                    <h3><?php _e('Link CDN', 'utility-server-cdn'); ?></h3>
                    <p><code><?php echo esc_html(USCDN_Settings::get('cdn_link_base')); ?></code></p>
                    <button type="button" class="button uscdn-test-btn" 
                            data-cdn-url="<?php echo esc_attr(USCDN_Settings::get('cdn_link_base')); ?>" 
                            data-cdn-type="link">
                        <?php _e('Test Connection', 'utility-server-cdn'); ?>
                    </button>
                    <div class="uscdn-test-result"></div>
                </div>
            <?php endif; ?>
            
            <?php if (!USCDN_Settings::get('enable_image_cdn') && !USCDN_Settings::get('enable_static_cdn') && !USCDN_Settings::get('enable_link_cdn')): ?>
                <div class="uscdn-empty-state">
                    <span class="dashicons dashicons-admin-tools"></span>
                    <p><?php _e('No CDN configured yet. Enable at least one CDN in settings to test.', 'utility-server-cdn'); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Cache Management -->
    <div class="uscdn-section">
        <h2><?php _e('Cache Management', 'utility-server-cdn'); ?></h2>
        <p class="description"><?php _e('Clear cached CSS files to force regeneration with updated URLs.', 'utility-server-cdn'); ?></p>
        
        <div class="uscdn-cache-info">
            <?php
            $cache_dir = WP_CONTENT_DIR . '/cache/uscdn-css';
            $cache_files = [];
            if (is_dir($cache_dir)) {
                $cache_files = glob($cache_dir . '/*.css');
            }
            $cache_count = count($cache_files);
            $cache_size = 0;
            foreach ($cache_files as $file) {
                $cache_size += filesize($file);
            }
            $cache_size_mb = round($cache_size / 1024 / 1024, 2);
            ?>
            
            <div class="uscdn-cache-stats">
                <div class="stat">
                    <span class="dashicons dashicons-media-document"></span>
                    <strong><?php echo $cache_count; ?></strong> <?php _e('cached files', 'utility-server-cdn'); ?>
                </div>
                <div class="stat">
                    <span class="dashicons dashicons-database"></span>
                    <strong><?php echo $cache_size_mb; ?> MB</strong> <?php _e('cache size', 'utility-server-cdn'); ?>
                </div>
            </div>
            
            <p>
                <button type="button" class="button button-secondary uscdn-clear-cache-btn">
                    <?php _e('Clear All Cache', 'utility-server-cdn'); ?>
                </button>
                <span class="description"><?php _e('This will send the X-Cache-Flush: TRUE header to your CDN.', 'utility-server-cdn'); ?></span>
            </p>
        </div>
    </div>
    
    
    <!-- Plugin Updates -->
    <div class="uscdn-section">
        <h2><?php _e('Plugin Updates', 'utility-server-cdn'); ?></h2>
        
        <div class="uscdn-cache-info">
            <!-- Update check result area -->
            <div id="uscdn-update-result"></div>
            
            <table class="widefat">
                <tbody>
                    <tr>
                        <td style="width: 250px;"><strong><?php _e('Current Version', 'utility-server-cdn'); ?></strong></td>
                        <td><code><?php echo USCDN_VERSION; ?></code></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e('Update Check URL', 'utility-server-cdn'); ?></strong></td>
                        <td><code style="font-size: 11px; word-break: break-all;">https://awsmarketplace-public-personal.s3.us-east-1.amazonaws.com/UtilS-Wordpress-RHINO-MARLIN-Plugin/update-info.json</code></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e('Last Check', 'utility-server-cdn'); ?></strong></td>
                        <td>
                            <?php 
                            $last_check = get_transient('uscdn_update_check');
                            if ($last_check) {
                                echo '<span style="color: #00a32a;">✓ Update info cached</span>';
                            } else {
                                echo '<span style="color: #999;">Not checked yet</span>';
                            }
                            ?>
                        </td>
                    </tr>
                </tbody>
            </table>
            
            <p style="margin-top: 20px;">
                <button type="button" class="button button-primary" id="uscdn-check-updates-btn">
                    <span class="dashicons dashicons-update" style="margin-top: 3px;"></span>
                    <?php _e('Check for Updates Now', 'utility-server-cdn'); ?>
                </button>
                <span class="description" style="margin-left: 10px;">
                    <?php _e('Manually check if a new version is available', 'utility-server-cdn'); ?>
                </span>
            </p>
            
            <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('#uscdn-check-updates-btn').on('click', function(e) {
                    e.preventDefault();
                    
                    var $btn = $(this);
                    var $result = $('#uscdn-update-result');
                    
                    // Disable button and show loading
                    $btn.prop('disabled', true);
                    $btn.find('.dashicons').addClass('dashicons-update-spin');
                    
                    $result.html('<div class="notice notice-info inline" style="margin: 0 0 20px 0;"><p>Checking for updates...</p></div>');
                    
                    // Make AJAX request
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'uscdn_check_updates',
                            nonce: '<?php echo wp_create_nonce('uscdn_check_updates'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                if (response.data.update_available) {
                                    $result.html(
                                        '<div class="notice notice-success inline" style="margin: 0 0 20px 0;">' +
                                        '<p><strong>✅ Update Available!</strong> Version ' + response.data.new_version + ' is available. ' +
                                        'Go to <a href="' + response.data.plugins_url + '">Plugins page</a> to update.</p>' +
                                        '</div>'
                                    );
                                } else {
                                    $result.html(
                                        '<div class="notice notice-info inline" style="margin: 0 0 20px 0;">' +
                                        '<p><strong>✓ You are using the latest version</strong> (v' + response.data.current_version + ')</p>' +
                                        '</div>'
                                    );
                                }
                            } else {
                                $result.html(
                                    '<div class="notice notice-error inline" style="margin: 0 0 20px 0;">' +
                                    '<p><strong>Error:</strong> ' + response.data.message + '</p>' +
                                    '</div>'
                                );
                            }
                        },
                        error: function() {
                            $result.html(
                                '<div class="notice notice-error inline" style="margin: 0 0 20px 0;">' +
                                '<p><strong>Error:</strong> Failed to check for updates. Please try again.</p>' +
                                '</div>'
                            );
                        },
                        complete: function() {
                            // Re-enable button and stop spinning
                            $btn.prop('disabled', false);
                            $btn.find('.dashicons').removeClass('dashicons-update-spin');
                        }
                    });
                });
            });
            </script>
            
            <style>
            .dashicons-update-spin {
                animation: dashicons-spin 1s infinite linear;
            }
            @keyframes dashicons-spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            </style>
            
            <div class="uscdn-tips" style="margin-top: 20px;">
                <div class="uscdn-tip">
                    <span class="dashicons dashicons-info"></span>
                    <p><strong>Automatic Updates:</strong> WordPress checks for updates every 12 hours automatically. You can also check anytime from <a href="<?php echo admin_url('update-core.php'); ?>">Dashboard → Updates</a>.</p>
                </div>
                <div class="uscdn-tip">
                    <span class="dashicons dashicons-shield"></span>
                    <p><strong>Safe Updates:</strong> The plugin will be deactivated before update and reactivated after successful installation. Your settings are preserved.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- System Information -->
    <div class="uscdn-section">
        <h2><?php _e('System Information', 'utility-server-cdn'); ?></h2>
        
        <table class="widefat">
            <tbody>
                <tr>
                    <td><strong><?php _e('Plugin Version', 'utility-server-cdn'); ?></strong></td>
                    <td><?php echo USCDN_VERSION; ?></td>
                </tr>
                <tr>
                    <td><strong><?php _e('WordPress Version', 'utility-server-cdn'); ?></strong></td>
                    <td><?php echo get_bloginfo('version'); ?></td>
                </tr>
                <tr>
                    <td><strong><?php _e('PHP Version', 'utility-server-cdn'); ?></strong></td>
                    <td><?php echo PHP_VERSION; ?></td>
                </tr>
                <tr>
                    <td><strong><?php _e('Site URL', 'utility-server-cdn'); ?></strong></td>
                    <td><?php echo home_url(); ?></td>
                </tr>
                <tr>
                    <td><strong><?php _e('Source Hosts', 'utility-server-cdn'); ?></strong></td>
                    <td><?php echo implode(', ', USCDN_Settings::get_source_hosts()); ?></td>
                </tr>
                <tr>
                    <td><strong><?php _e('Cache Directory', 'utility-server-cdn'); ?></strong></td>
                    <td>
                        <?php echo WP_CONTENT_DIR . '/cache/uscdn-css'; ?>
                        <?php if (is_writable($cache_dir)): ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span> <?php _e('Writable', 'utility-server-cdn'); ?>
                        <?php else: ?>
                            <span class="dashicons dashicons-warning" style="color: red;"></span> <?php _e('Not writable', 'utility-server-cdn'); ?>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <!-- Domain Mapping Status -->
    <div class="uscdn-section">
        <h2><?php _e('Domain Mapping Status', 'utility-server-cdn'); ?></h2>
        
        <?php $domain_info = USCDN_Domain_Mapper::get_domain_info(); ?>
        
        <table class="widefat">
            <tbody>
                <tr>
                    <td><strong><?php _e('Current Domain', 'utility-server-cdn'); ?></strong></td>
                    <td><code><?php echo esc_html($domain_info['current_host']); ?></code></td>
                </tr>
                <tr>
                    <td><strong><?php _e('Domain Type', 'utility-server-cdn'); ?></strong></td>
                    <td>
                        <?php if ($domain_info['is_admin_domain']): ?>
                            <span style="color: #2271b1;"><strong><?php _e('Admin Domain', 'utility-server-cdn'); ?></strong></span>
                        <?php elseif ($domain_info['is_cdn_domain']): ?>
                            <span style="color: #00a32a;"><strong><?php _e('CDN Domain', 'utility-server-cdn'); ?></strong></span>
                        <?php else: ?>
                            <span><?php _e('Main Site Domain', 'utility-server-cdn'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><strong><?php _e('Redirect Prevention', 'utility-server-cdn'); ?></strong></td>
                    <td>
                        <?php if ($domain_info['is_admin_domain'] || $domain_info['is_cdn_domain']): ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span> <?php _e('Active', 'utility-server-cdn'); ?>
                        <?php else: ?>
                            <span class="dashicons dashicons-minus" style="color: gray;"></span> <?php _e('Not needed', 'utility-server-cdn'); ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><strong><?php _e('Configured Admin URL', 'utility-server-cdn'); ?></strong></td>
                    <td>
                        <?php if ($domain_info['admin_url_configured']): ?>
                            <code><?php echo esc_html($domain_info['admin_url_configured']); ?></code>
                        <?php else: ?>
                            <span style="color: #999;"><?php _e('Not configured', 'utility-server-cdn'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
        
        <?php if ($domain_info['is_admin_domain'] || $domain_info['is_cdn_domain']): ?>
        <div class="notice notice-success inline" style="margin-top: 15px;">
            <p>
                <strong>✓ <?php _e('Domain mapping is working!', 'utility-server-cdn'); ?></strong><br>
                <?php _e('You are accessing WordPress via an alternative domain and redirects are being prevented.', 'utility-server-cdn'); ?>
            </p>
        </div>
        <?php endif; ?>
    </div>
</div>
