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

$current_url = home_url();
$origin_url = USCDN_Settings::get('origin_url', '');
$suggestions = USCDN_Migrator::get_suggested_migrations();
?>

<div class="wrap uscdn-migration">
    <?php include USCDN_PLUGIN_DIR . 'admin/views/branding.php'; ?>
    
    <p class="description">
        <?php _e('Permanently update URLs in your database content (posts, pages, custom fields, comments).', 'utility-server-cdn'); ?>
    </p>
    
    <!-- Info Notice -->
    <div class="notice notice-info inline">
        <p>
            <strong>💡 <?php _e('Two Options Available:', 'utility-server-cdn'); ?></strong><br>
            <strong><?php _e('Database Migration (This Page):', 'utility-server-cdn'); ?></strong> <?php _e('Permanently updates URLs in database. Better for SEO and performance.', 'utility-server-cdn'); ?><br>
            <strong><?php _e('On-the-Fly Rewriting:', 'utility-server-cdn'); ?></strong> <?php _e('Replaces URLs dynamically without touching database. Go to CDN Manager → Settings → Content Rewriting.', 'utility-server-cdn'); ?>
        </p>
    </div>
    
    <!-- Warning Notice -->
    <div class="notice notice-warning inline">
        <p>
            <strong>⚠️ <?php _e('Important:', 'utility-server-cdn'); ?></strong> 
            <?php _e('Always backup your database before running a migration. This operation will modify your content permanently.', 'utility-server-cdn'); ?>
        </p>
    </div>
    
    <!-- Current Configuration -->
    <div class="uscdn-section">
        <h2><?php _e('Current Configuration', 'utility-server-cdn'); ?></h2>
        
        <table class="widefat">
            <tbody>
                <tr>
                    <td><strong><?php _e('Current Site URL', 'utility-server-cdn'); ?></strong></td>
                    <td><code><?php echo esc_html($current_url); ?></code></td>
                </tr>
                <?php if ($origin_url): ?>
                <tr>
                    <td><strong><?php _e('Origin URL', 'utility-server-cdn'); ?></strong></td>
                    <td><code><?php echo esc_html($origin_url); ?></code></td>
                </tr>
                <?php endif; ?>
                <tr>
                    <td><strong><?php _e('Image CDN', 'utility-server-cdn'); ?></strong></td>
                    <td>
                        <?php if (USCDN_Settings::get('enable_image_cdn')): ?>
                            <code><?php echo esc_html(USCDN_Settings::get('cdn_image_base')); ?></code>
                        <?php else: ?>
                            <span style="color: #999;"><?php _e('Not configured', 'utility-server-cdn'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><strong><?php _e('Static CDN', 'utility-server-cdn'); ?></strong></td>
                    <td>
                        <?php if (USCDN_Settings::get('enable_static_cdn')): ?>
                            <code><?php echo esc_html(USCDN_Settings::get('cdn_static_base')); ?></code>
                        <?php else: ?>
                            <span style="color: #999;"><?php _e('Not configured', 'utility-server-cdn'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <!-- Suggested Migrations -->
    <?php if (!empty($suggestions)): ?>
    <div class="uscdn-section">
        <h2><?php _e('Suggested Migrations', 'utility-server-cdn'); ?></h2>
        <p class="description"><?php _e('Based on your current configuration, here are recommended URL migrations:', 'utility-server-cdn'); ?></p>
        
        <div class="uscdn-suggestions">
            <?php foreach ($suggestions as $index => $suggestion): ?>
            <div class="uscdn-suggestion-card" style="background: #f6f7f7; padding: 15px; margin-bottom: 15px; border-radius: 4px;">
                <h3 style="margin-top: 0;"><?php echo esc_html($suggestion['description']); ?></h3>
                <p style="margin: 10px 0;">
                    <strong><?php _e('From:', 'utility-server-cdn'); ?></strong> <code><?php echo esc_html($suggestion['from']); ?></code><br>
                    <strong><?php _e('To:', 'utility-server-cdn'); ?></strong> <code><?php echo esc_html($suggestion['to']); ?></code>
                </p>
                <button type="button" class="button button-secondary uscdn-use-suggestion" 
                        data-from="<?php echo esc_attr($suggestion['from']); ?>"
                        data-to="<?php echo esc_attr($suggestion['to']); ?>">
                    <?php _e('Use This Migration', 'utility-server-cdn'); ?>
                </button>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Custom Migration Tool -->
    <div class="uscdn-section">
        <h2><?php _e('Custom URL Migration', 'utility-server-cdn'); ?></h2>
        
        <form id="uscdn-migration-form" style="max-width: 800px;">
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="old_url"><?php _e('Find URL', 'utility-server-cdn'); ?></label>
                    </th>
                    <td>
                        <input type="url" id="old_url" name="old_url" 
                               class="regular-text" 
                               placeholder="https://example.com"
                               value="<?php echo esc_attr($current_url); ?>">
                        <p class="description">
                            <?php _e('The URL to search for in your database content.', 'utility-server-cdn'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="new_url"><?php _e('Replace With', 'utility-server-cdn'); ?></label>
                    </th>
                    <td>
                        <input type="url" id="new_url" name="new_url" 
                               class="regular-text" 
                               placeholder="https://cdn.example.com"
                               value="<?php echo esc_attr($origin_url ? $origin_url : ''); ?>">
                        <p class="description">
                            <?php _e('The new URL that will replace the old one.', 'utility-server-cdn'); ?>
                        </p>
                    </td>
                </tr>
            </table>
            
            <div class="uscdn-actions">
                <button type="button" id="uscdn-scan-btn" class="button button-large">
                    <span class="dashicons dashicons-search"></span>
                    <?php _e('Scan Database', 'utility-server-cdn'); ?>
                </button>
                
                <button type="button" id="uscdn-dry-run-btn" class="button button-large" style="margin-left: 10px;">
                    <span class="dashicons dashicons-visibility"></span>
                    <?php _e('Preview Migration', 'utility-server-cdn'); ?>
                </button>
                
                <button type="button" id="uscdn-migrate-btn" class="button button-primary button-large" style="margin-left: 10px;" disabled>
                    <span class="dashicons dashicons-database-import"></span>
                    <?php _e('Run Migration', 'utility-server-cdn'); ?>
                </button>
            </div>
        </form>
        
        <!-- Results Display -->
        <div id="uscdn-migration-results" style="margin-top: 30px; display: none;">
            <h3><?php _e('Migration Results', 'utility-server-cdn'); ?></h3>
            <div id="uscdn-results-content"></div>
        </div>
    </div>
    
    <!-- Migration Info -->
    <div class="uscdn-section">
        <h2><?php _e('What Gets Migrated?', 'utility-server-cdn'); ?></h2>
        
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
            <div style="background: #f6f7f7; padding: 15px; border-radius: 4px;">
                <h4 style="margin-top: 0;">
                    <span class="dashicons dashicons-media-document"></span>
                    <?php _e('Posts & Pages', 'utility-server-cdn'); ?>
                </h4>
                <p style="margin-bottom: 0;">
                    <?php _e('Content and excerpts in all posts, pages, and custom post types.', 'utility-server-cdn'); ?>
                </p>
            </div>
            
            <div style="background: #f6f7f7; padding: 15px; border-radius: 4px;">
                <h4 style="margin-top: 0;">
                    <span class="dashicons dashicons-admin-settings"></span>
                    <?php _e('Custom Fields', 'utility-server-cdn'); ?>
                </h4>
                <p style="margin-bottom: 0;">
                    <?php _e('All post meta and custom field values (ACF, etc.).', 'utility-server-cdn'); ?>
                </p>
            </div>
            
            <div style="background: #f6f7f7; padding: 15px; border-radius: 4px;">
                <h4 style="margin-top: 0;">
                    <span class="dashicons dashicons-admin-comments"></span>
                    <?php _e('Comments', 'utility-server-cdn'); ?>
                </h4>
                <p style="margin-bottom: 0;">
                    <?php _e('Comment content and author URLs.', 'utility-server-cdn'); ?>
                </p>
            </div>
            
            <div style="background: #f6f7f7; padding: 15px; border-radius: 4px;">
                <h4 style="margin-top: 0;">
                    <span class="dashicons dashicons-admin-generic"></span>
                    <?php _e('Options', 'utility-server-cdn'); ?>
                </h4>
                <p style="margin-bottom: 0;">
                    <?php _e('WordPress options and settings (excluding transients).', 'utility-server-cdn'); ?>
                </p>
            </div>
        </div>
    </div>
    
    <!-- Safety Tips -->
    <div class="uscdn-section">
        <h2><?php _e('Safety Tips', 'utility-server-cdn'); ?></h2>
        
        <div class="uscdn-tips">
            <div class="uscdn-tip">
                <span class="dashicons dashicons-yes-alt"></span>
                <p><strong><?php _e('Always backup first:', 'utility-server-cdn'); ?></strong> <?php _e('Use your hosting control panel or a backup plugin to create a full database backup.', 'utility-server-cdn'); ?></p>
            </div>
            <div class="uscdn-tip">
                <span class="dashicons dashicons-yes-alt"></span>
                <p><strong><?php _e('Test on staging:', 'utility-server-cdn'); ?></strong> <?php _e('If possible, test the migration on a staging site before running on production.', 'utility-server-cdn'); ?></p>
            </div>
            <div class="uscdn-tip">
                <span class="dashicons dashicons-yes-alt"></span>
                <p><strong><?php _e('Use preview first:', 'utility-server-cdn'); ?></strong> <?php _e('Click "Preview Migration" to see how many items will be affected before running the actual migration.', 'utility-server-cdn'); ?></p>
            </div>
            <div class="uscdn-tip">
                <span class="dashicons dashicons-yes-alt"></span>
                <p><strong><?php _e('Be specific:', 'utility-server-cdn'); ?></strong> <?php _e('Use complete URLs including https:// to avoid unintended replacements.', 'utility-server-cdn'); ?></p>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Use suggestion button
    $('.uscdn-use-suggestion').on('click', function() {
        const from = $(this).data('from');
        const to = $(this).data('to');
        $('#old_url').val(from);
        $('#new_url').val(to);
        $('html, body').animate({
            scrollTop: $('#uscdn-migration-form').offset().top - 100
        }, 500);
    });
    
    // Scan database
    $('#uscdn-scan-btn').on('click', function() {
        const $btn = $(this);
        const oldUrl = $('#old_url').val();
        const newUrl = $('#new_url').val();
        
        if (!oldUrl || !newUrl) {
            alert('<?php _e('Please enter both URLs', 'utility-server-cdn'); ?>');
            return;
        }
        
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update dashicons-spin"></span> <?php _e('Scanning...', 'utility-server-cdn'); ?>');
        
        $.post(ajaxurl, {
            action: 'uscdn_scan_content',
            nonce: '<?php echo wp_create_nonce('uscdn_admin'); ?>',
            old_url: oldUrl,
            new_url: newUrl
        }, function(response) {
            if (response.success) {
                displayResults(response.data, true);
                $('#uscdn-migrate-btn').prop('disabled', false);
            } else {
                alert('<?php _e('Error:', 'utility-server-cdn'); ?> ' + response.data.message);
            }
        }).always(function() {
            $btn.prop('disabled', false).html('<span class="dashicons dashicons-search"></span> <?php _e('Scan Database', 'utility-server-cdn'); ?>');
        });
    });
    
    // Preview migration (dry run)
    $('#uscdn-dry-run-btn').on('click', function() {
        const $btn = $(this);
        const oldUrl = $('#old_url').val();
        const newUrl = $('#new_url').val();
        
        if (!oldUrl || !newUrl) {
            alert('<?php _e('Please enter both URLs', 'utility-server-cdn'); ?>');
            return;
        }
        
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update dashicons-spin"></span> <?php _e('Previewing...', 'utility-server-cdn'); ?>');
        
        $.post(ajaxurl, {
            action: 'uscdn_migrate_content',
            nonce: '<?php echo wp_create_nonce('uscdn_admin'); ?>',
            old_url: oldUrl,
            new_url: newUrl,
            dry_run: 'true'
        }, function(response) {
            if (response.success) {
                displayResults(response.data, true);
                $('#uscdn-migrate-btn').prop('disabled', false);
            } else {
                alert('<?php _e('Error:', 'utility-server-cdn'); ?> ' + response.data.message);
            }
        }).always(function() {
            $btn.prop('disabled', false).html('<span class="dashicons dashicons-visibility"></span> <?php _e('Preview Migration', 'utility-server-cdn'); ?>');
        });
    });
    
    // Run migration
    $('#uscdn-migrate-btn').on('click', function() {
        const $btn = $(this);
        const oldUrl = $('#old_url').val();
        const newUrl = $('#new_url').val();
        
        if (!confirm('<?php _e('Are you sure you want to run this migration? This will permanently modify your database. Make sure you have a backup!', 'utility-server-cdn'); ?>')) {
            return;
        }
        
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update dashicons-spin"></span> <?php _e('Migrating...', 'utility-server-cdn'); ?>');
        
        $.post(ajaxurl, {
            action: 'uscdn_migrate_content',
            nonce: '<?php echo wp_create_nonce('uscdn_admin'); ?>',
            old_url: oldUrl,
            new_url: newUrl,
            dry_run: 'false'
        }, function(response) {
            if (response.success) {
                displayResults(response.data, false);
                alert('<?php _e('Migration completed successfully!', 'utility-server-cdn'); ?>');
            } else {
                alert('<?php _e('Error:', 'utility-server-cdn'); ?> ' + response.data.message);
            }
        }).always(function() {
            $btn.prop('disabled', false).html('<span class="dashicons dashicons-database-import"></span> <?php _e('Run Migration', 'utility-server-cdn'); ?>');
        });
    });
    
    function displayResults(data, isPreview) {
        const mode = isPreview ? '<?php _e('Preview Mode', 'utility-server-cdn'); ?>' : '<?php _e('Migration Complete', 'utility-server-cdn'); ?>';
        const html = `
            <div class="notice notice-${isPreview ? 'info' : 'success'} inline">
                <p><strong>${mode}</strong></p>
            </div>
            <table class="widefat">
                <thead>
                    <tr>
                        <th><?php _e('Content Type', 'utility-server-cdn'); ?></th>
                        <th style="text-align: right;"><?php _e('Items Affected', 'utility-server-cdn'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><?php _e('Posts & Pages', 'utility-server-cdn'); ?></td>
                        <td style="text-align: right;"><strong>${data.posts}</strong></td>
                    </tr>
                    <tr>
                        <td><?php _e('Custom Fields (Post Meta)', 'utility-server-cdn'); ?></td>
                        <td style="text-align: right;"><strong>${data.postmeta}</strong></td>
                    </tr>
                    <tr>
                        <td><?php _e('Options', 'utility-server-cdn'); ?></td>
                        <td style="text-align: right;"><strong>${data.options}</strong></td>
                    </tr>
                    <tr>
                        <td><?php _e('Comments', 'utility-server-cdn'); ?></td>
                        <td style="text-align: right;"><strong>${data.comments}</strong></td>
                    </tr>
                    <tr style="background: #f6f7f7;">
                        <td><strong><?php _e('Total', 'utility-server-cdn'); ?></strong></td>
                        <td style="text-align: right;"><strong style="font-size: 16px;">${data.total}</strong></td>
                    </tr>
                </tbody>
            </table>
        `;
        
        $('#uscdn-results-content').html(html);
        $('#uscdn-migration-results').slideDown();
    }
});
</script>
