<?php
/**
 * CastConductor Export/Import Admin Page
 *
 * WordPress admin interface for exporting and importing
 * content blocks, scenes, containers, and settings.
 *
 * @package CastConductor
 * @subpackage Admin
 * @since 5.2.1
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register admin menu
 * Priority 20 ensures it loads after main CastConductor menu (priority 10)
 */
add_action('admin_menu', 'castconductor_register_export_import_menu', 20);

function castconductor_register_export_import_menu() {
    add_submenu_page(
        'castconductor',
        __('Export/Import', 'castconductor'),
        __('Export/Import', 'castconductor'),
        'manage_options',
        'castconductor-export-import',
        'castconductor_export_import_page'
    );
}

/**
 * Render export/import admin page
 */
function castconductor_export_import_page() {
    // Handle import form submission
    if (isset($_POST['castconductor_import_submit']) && check_admin_referer('castconductor_import')) {
        castconductor_handle_import();
    }
    
    ?>
    <div class="wrap">
        <h1>📦 CastConductor Export/Import</h1>
        
        <p>Export your content blocks, scenes, and containers for backup or migration. Import previously exported data to restore or transfer content between installations.</p>
        
        <!-- Export Section -->
        <div class="card" style="max-width: 800px; margin-bottom: 20px;">
            <h2>Export Content</h2>
            <form method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" style="margin: 20px 0;">
                <input type="hidden" name="action" value="castconductor_export">
                <?php wp_nonce_field('castconductor_export'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label>Export Type</label>
                        </th>
                        <td>
                            <fieldset>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="export_type" value="full" checked>
                                    <strong>Full Library</strong> - Everything (content blocks, scenes, containers, settings)
                                </label>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="export_type" value="content_blocks">
                                    <strong>Content Blocks Only</strong> - All content blocks and media references
                                </label>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="export_type" value="scenes">
                                    <strong>Scenes Only</strong> - All scene configurations
                                </label>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="export_type" value="containers">
                                    <strong>Containers Only</strong> - All container configurations
                                </label>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label>Options</label>
                        </th>
                        <td>
                            <label style="display: block; margin: 5px 0;">
                                <input type="checkbox" name="include_media" value="1" checked>
                                Include media file URLs and references
                            </label>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <button type="submit" class="button button-primary button-large">
                        📥 Download Export File
                    </button>
                    <span class="description" style="margin-left: 10px;">
                        Generates a JSON file you can save and import later
                    </span>
                </p>
            </form>
        </div>
        
        <!-- Import Section -->
        <div class="card" style="max-width: 800px; margin-bottom: 20px;">
            <h2>Import Content</h2>
            
            <?php if (isset($_SESSION['castconductor_import_results'])): ?>
                <?php 
                    $results = $_SESSION['castconductor_import_results'];
                    unset($_SESSION['castconductor_import_results']);
                ?>
                
                <div class="notice notice-success" style="margin: 20px 0;">
                    <p><strong>✅ Import Completed Successfully!</strong></p>
                    <ul style="margin: 10px 0; padding-left: 20px;">
                        <?php if ($results['content_blocks'] > 0): ?>
                            <li>Imported <?php echo $results['content_blocks']; ?> content block(s)</li>
                        <?php endif; ?>
                        <?php if ($results['scenes'] > 0): ?>
                            <li>Imported <?php echo $results['scenes']; ?> scene(s)</li>
                        <?php endif; ?>
                        <?php if ($results['containers'] > 0): ?>
                            <li>Imported <?php echo $results['containers']; ?> container(s)</li>
                        <?php endif; ?>
                        <?php if ($results['settings']): ?>
                            <li>Imported global settings</li>
                        <?php endif; ?>
                    </ul>
                    <?php if (!empty($results['warnings'])): ?>
                        <p><strong>Warnings:</strong></p>
                        <ul style="margin: 10px 0; padding-left: 20px;">
                            <?php foreach ($results['warnings'] as $warning): ?>
                                <li><?php echo esc_html($warning); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['castconductor_import_error'])): ?>
                <div class="notice notice-error" style="margin: 20px 0;">
                    <p><strong>❌ Import Failed</strong></p>
                    <p><?php echo esc_html($_SESSION['castconductor_import_error']); ?></p>
                </div>
                <?php unset($_SESSION['castconductor_import_error']); ?>
            <?php endif; ?>
            
            <form method="post" enctype="multipart/form-data" style="margin: 20px 0;">
                <?php wp_nonce_field('castconductor_import'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="import_file">Import File</label>
                        </th>
                        <td>
                            <input type="file" id="import_file" name="import_file" accept=".json" required style="margin-bottom: 10px;">
                            <p class="description">
                                Select a CastConductor export JSON file (generated from the export section above)
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label>Conflict Resolution</label>
                        </th>
                        <td>
                            <fieldset>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="conflict_mode" value="skip" checked>
                                    <strong>Skip Existing</strong> - Don't import items with duplicate names
                                </label>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="conflict_mode" value="overwrite">
                                    <strong>Overwrite Existing</strong> - Replace items with same name
                                </label>
                                <label style="display: block; margin: 5px 0;">
                                    <input type="radio" name="conflict_mode" value="duplicate">
                                    <strong>Create Duplicates</strong> - Import as new items with "(Imported)" suffix
                                </label>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label>Import Settings</label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="import_settings" value="1">
                                Import global settings (stream URL, metadata URL, canvas dimensions)
                            </label>
                            <p class="description">
                                ⚠️ This will overwrite your current global settings
                            </p>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <button type="submit" name="castconductor_import_submit" class="button button-primary button-large">
                        📤 Import Content
                    </button>
                </p>
            </form>
        </div>
        
        <!-- Database Backup Section -->
        <div class="card" style="max-width: 800px; margin-bottom: 20px;">
            <h2>💾 Database Backup</h2>
            <p>Create a complete SQL backup of all CastConductor tables for disaster recovery or migration.</p>
            
            <div id="cc-backup-stats" style="margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 5px;">
                <p><strong>Loading backup statistics...</strong></p>
            </div>
            
            <form id="cc-backup-form" style="margin: 20px 0;">
                <?php wp_nonce_field('castconductor_database_backup', 'cc_backup_nonce'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label>Backup Options</label>
                        </th>
                        <td>
                            <label style="display: block; margin: 5px 0;">
                                <input type="checkbox" name="include_analytics" value="1">
                                Include analytics data (may be large)
                            </label>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <button type="submit" class="button button-primary button-large">
                        💾 Download SQL Backup
                    </button>
                    <span class="description" style="margin-left: 10px;">
                        Generates a .sql file containing all CastConductor tables
                    </span>
                </p>
            </form>
        </div>
        
        <!-- Database Restore Section -->
        <div class="card" style="max-width: 800px; margin-bottom: 20px;">
            <h2>🔄 Restore from Backup</h2>
            <p>Restore CastConductor tables from a previously downloaded SQL backup.</p>
            
            <?php
            // Check license status for restore capability
            require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-license-manager.php';
            $license_manager = CastConductor_License_Manager::instance();
            $is_licensed = $license_manager->is_license_valid();
            
            if (!$is_licensed):
            ?>
            <div class="notice notice-error inline" style="margin: 15px 0;">
                <p>
                    <strong>🔒 License Required:</strong> Restoring from backup requires a valid CastConductor license.
                    <a href="<?php echo admin_url('admin.php?page=castconductor'); ?>">Activate your license</a> to enable restore functionality.
                </p>
                <p class="description" style="margin-top: 5px;">
                    This prevents unauthorized copying of CastConductor data between installations.
                    Backup download is always available to protect your data.
                </p>
            </div>
            <?php else: ?>
            
            <div class="notice notice-warning inline" style="margin: 15px 0;">
                <p>
                    <strong>⚠️ Warning:</strong> Restoring will <strong>completely replace</strong> all current CastConductor data.
                    A pre-restore backup will be created automatically before restoration.
                </p>
            </div>
            <?php endif; ?>
            
            <?php
            // Show pre-restore backups if any exist
            require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-database-backup.php';
            $backup_manager = new CastConductor_Database_Backup();
            $pre_restore_backups = $backup_manager->list_pre_restore_backups();
            if (!empty($pre_restore_backups)):
            ?>
            <div style="margin: 15px 0; padding: 15px; background: #e7f5e7; border: 1px solid #46b450; border-radius: 5px;">
                <p><strong>📁 Pre-Restore Backups Available:</strong></p>
                <ul style="margin: 10px 0 0 20px;">
                    <?php foreach (array_slice($pre_restore_backups, 0, 3) as $backup): ?>
                        <li>
                            <?php echo esc_html($backup['filename']); ?>
                            (<?php echo size_format($backup['size']); ?>) -
                            <?php echo esc_html($backup['date_formatted']); ?>
                            <a href="#" class="cc-download-pre-restore" data-file="<?php echo esc_attr($backup['filename']); ?>">
                                Download
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <p class="description" style="margin-top: 10px;">
                    These are automatic snapshots taken before previous restores. Use to undo a restore if needed.
                </p>
            </div>
            <?php endif; ?>
            
            <form id="cc-restore-form" method="post" enctype="multipart/form-data" style="margin: 20px 0; <?php echo !$is_licensed ? 'opacity: 0.5; pointer-events: none;' : ''; ?>">
                <?php wp_nonce_field('castconductor_database_restore', 'cc_restore_nonce'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="restore_file">Backup File</label>
                        </th>
                        <td>
                            <input type="file" id="restore_file" name="restore_file" accept=".sql" required style="margin-bottom: 10px;" <?php echo !$is_licensed ? 'disabled' : ''; ?>>
                            <p class="description">
                                Select a CastConductor SQL backup file (.sql)
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label>Safety Options</label>
                        </th>
                        <td>
                            <label style="display: block; margin: 5px 0;">
                                <input type="checkbox" name="create_pre_backup" value="1" checked <?php echo !$is_licensed ? 'disabled' : ''; ?>>
                                Create pre-restore backup (recommended)
                            </label>
                            <label style="display: block; margin: 5px 0; color: #d63638;">
                                <input type="checkbox" name="confirm_restore" value="1" required <?php echo !$is_licensed ? 'disabled' : ''; ?>>
                                <strong>I understand this will overwrite all current CastConductor data</strong>
                            </label>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <button type="submit" class="button button-secondary button-large" style="background: #d63638; border-color: #d63638; color: #fff;" <?php echo !$is_licensed ? 'disabled' : ''; ?>>
                        🔄 Restore from Backup
                    </button>
                    <?php if (!$is_licensed): ?>
                        <span class="description" style="margin-left: 10px; color: #d63638;">
                            🔒 License required
                        </span>
                    <?php endif; ?>
                </p>
            </form>
            
            <div id="cc-restore-result" style="display: none; margin: 20px 0;"></div>
        </div>
        
        <!-- Export File Format Documentation -->
        <div class="card" style="max-width: 800px;">
            <h2>Export File Format</h2>
            <p>Export files are JSON formatted and contain:</p>
            <ul style="margin: 10px 0 10px 20px;">
                <li><strong>Version Information</strong> - CastConductor version and export date</li>
                <li><strong>Content Blocks</strong> - All layers, artwork, animations, and configurations</li>
                <li><strong>Scenes</strong> - Scene layouts and container relationships</li>
                <li><strong>Containers</strong> - Container configurations and content block assignments</li>
                <li><strong>Media References</strong> - URLs of all images, videos, and fonts used</li>
                <li><strong>Settings</strong> - Global CastConductor settings (optional)</li>
            </ul>
            <p>
                <strong>File Portability:</strong> Export files can be transferred between CastConductor installations.
                Media files (images, videos, fonts) are referenced by URL and must be accessible at those locations.
            </p>
        </div>
    </div>
    
    <style>
        .castconductor-export-import .card {
            padding: 20px;
        }
        .castconductor-export-import .form-table th {
            padding-top: 15px;
            vertical-align: top;
        }
        .castconductor-export-import fieldset label {
            font-size: 14px;
        }
        .castconductor-export-import .description {
            color: #666;
            font-style: italic;
        }
    </style>
    <?php
}

/**
 * Handle import form submission
 */
function castconductor_handle_import() {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized access');
    }
    
    // Check if file was uploaded
    if (empty($_FILES['import_file']['tmp_name'])) {
        $_SESSION['castconductor_import_error'] = 'No file uploaded';
        return;
    }
    
    $file = $_FILES['import_file'];
    
    // Validate file type
    if ($file['type'] !== 'application/json' && pathinfo($file['name'], PATHINFO_EXTENSION) !== 'json') {
        $_SESSION['castconductor_import_error'] = 'Invalid file type. Please upload a JSON file.';
        return;
    }
    
    // Validate file size (max 10MB)
    if ($file['size'] > 10 * 1024 * 1024) {
        $_SESSION['castconductor_import_error'] = 'File too large. Maximum size is 10MB.';
        return;
    }
    
    try {
        // Load import manager
        require_once plugin_dir_path(__FILE__) . 'class-castconductor-import-manager.php';
        $importer = new CastConductor_Import_Manager();
        
        // Prepare import options
        $options = array(
            'conflict_mode' => isset($_POST['conflict_mode']) ? sanitize_text_field($_POST['conflict_mode']) : 'skip',
            'import_settings' => isset($_POST['import_settings']) ? true : false
        );
        
        // Import from file
        $results = $importer->import_from_file($file['tmp_name'], $options);
        
        // Check for errors
        if (!empty($results['errors'])) {
            $_SESSION['castconductor_import_error'] = 'Import completed with errors: ' . implode(', ', $results['errors']);
        } else {
            $_SESSION['castconductor_import_results'] = $results;
        }
        
    } catch (Exception $e) {
        $_SESSION['castconductor_import_error'] = $e->getMessage();
    }
    
    // Clean up temp file
    if (file_exists($file['tmp_name'])) {
        unlink($file['tmp_name']);
    }
}

/**
 * Handle AJAX export request
 */
add_action('wp_ajax_castconductor_export', 'castconductor_handle_export_ajax');

function castconductor_handle_export_ajax() {
    check_ajax_referer('castconductor_export');
    
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized access');
    }
    
    // Load export manager (in includes/ directory, not admin/)
    require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-export-manager.php';
    $exporter = new CastConductor_Export_Manager();
    
    // Get export parameters
    $export_type = isset($_POST['export_type']) ? sanitize_text_field($_POST['export_type']) : 'full';
    $include_media = isset($_POST['include_media']) ? true : false;
    
    // Download export file (this will exit)
    $exporter->download_export($export_type, null, $include_media);
}
/**
 * Handle AJAX database backup request
 */
add_action('wp_ajax_castconductor_database_backup', 'castconductor_handle_database_backup_ajax');

function castconductor_handle_database_backup_ajax() {
    check_ajax_referer('castconductor_database_backup', 'cc_backup_nonce');
    
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized access');
    }
    
    require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-database-backup.php';
    $backup_manager = new CastConductor_Database_Backup();
    
    $include_analytics = isset($_POST['include_analytics']) && $_POST['include_analytics'] === '1';
    
    // Download backup file (this will exit)
    $backup_manager->download_backup($include_analytics);
}

/**
 * Handle AJAX database restore request
 */
add_action('wp_ajax_castconductor_database_restore', 'castconductor_handle_database_restore_ajax');

function castconductor_handle_database_restore_ajax() {
    check_ajax_referer('castconductor_database_restore', 'cc_restore_nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Unauthorized access'));
    }
    
    // LICENSE VALIDATION: Restore requires valid license to prevent domain bypass
    require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-license-manager.php';
    $license_manager = CastConductor_License_Manager::instance();
    if (!$license_manager->is_license_valid()) {
        wp_send_json_error(array(
            'message' => 'Restore requires a valid CastConductor license. Please activate your license on the Settings page before restoring data.'
        ));
    }
    
    // Validate confirmation checkbox
    if (empty($_POST['confirm_restore'])) {
        wp_send_json_error(array('message' => 'Please confirm you understand this will overwrite all data'));
    }
    
    // Check if file was uploaded
    if (empty($_FILES['restore_file']['tmp_name'])) {
        wp_send_json_error(array('message' => 'No file uploaded'));
    }
    
    $file = $_FILES['restore_file'];
    
    // Validate file type
    if (pathinfo($file['name'], PATHINFO_EXTENSION) !== 'sql') {
        wp_send_json_error(array('message' => 'Invalid file type. Please upload a .sql file.'));
    }
    
    // Validate file size (max 100MB for SQL)
    if ($file['size'] > 100 * 1024 * 1024) {
        wp_send_json_error(array('message' => 'File too large. Maximum size is 100MB.'));
    }
    
    try {
        require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-database-backup.php';
        $backup_manager = new CastConductor_Database_Backup();
        
        $create_pre_backup = isset($_POST['create_pre_backup']) && $_POST['create_pre_backup'] === '1';
        
        $result = $backup_manager->restore_from_file($file['tmp_name'], $create_pre_backup);
        
        // Clean up temp file
        if (file_exists($file['tmp_name'])) {
            unlink($file['tmp_name']);
        }
        
        if ($result['success']) {
            wp_send_json_success(array(
                'message' => 'Restore completed successfully!',
                'tables_restored' => $result['tables_restored'],
                'rows_inserted' => $result['rows_inserted'],
                'pre_backup_path' => $result['pre_backup_path'],
                'warnings' => $result['warnings']
            ));
        } else {
            wp_send_json_error(array(
                'message' => 'Restore failed: ' . implode(', ', $result['errors']),
                'warnings' => $result['warnings']
            ));
        }
        
    } catch (Exception $e) {
        wp_send_json_error(array('message' => 'Restore failed: ' . $e->getMessage()));
    }
}

/**
 * Handle AJAX get backup stats
 */
add_action('wp_ajax_castconductor_backup_stats', 'castconductor_handle_backup_stats_ajax');

function castconductor_handle_backup_stats_ajax() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Unauthorized access'));
    }
    
    require_once CASTCONDUCTOR_PLUGIN_DIR . 'includes/class-castconductor-database-backup.php';
    $backup_manager = new CastConductor_Database_Backup();
    
    $stats = $backup_manager->get_backup_stats();
    
    wp_send_json_success($stats);
}

/**
 * Handle AJAX download pre-restore backup
 */
add_action('wp_ajax_castconductor_download_pre_restore', 'castconductor_handle_download_pre_restore_ajax');

function castconductor_handle_download_pre_restore_ajax() {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized access');
    }
    
    $filename = isset($_GET['file']) ? sanitize_file_name($_GET['file']) : '';
    
    if (empty($filename) || strpos($filename, 'pre-restore-') !== 0) {
        wp_die('Invalid file');
    }
    
    $upload_dir = wp_upload_dir();
    $filepath = $upload_dir['basedir'] . '/castconductor-backups/' . $filename;
    
    if (!file_exists($filepath)) {
        wp_die('File not found');
    }
    
    header('Content-Type: application/sql');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($filepath));
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: 0');
    
    readfile($filepath);
    exit;
}

/**
 * Enqueue admin scripts for Export/Import page
 */
add_action('admin_enqueue_scripts', 'castconductor_export_import_enqueue_scripts');

function castconductor_export_import_enqueue_scripts($hook) {
    if ($hook !== 'castconductor_page_castconductor-export-import') {
        return;
    }
    
    // Inline JavaScript for backup/restore functionality
    wp_add_inline_script('jquery', '
        jQuery(document).ready(function($) {
            // Load backup stats
            $.ajax({
                url: ajaxurl,
                type: "POST",
                data: { action: "castconductor_backup_stats" },
                success: function(response) {
                    if (response.success) {
                        var stats = response.data;
                        var html = "<p><strong>📊 Backup Summary:</strong></p>";
                        html += "<ul style=\"margin: 10px 0 0 20px;\">";
                        html += "<li><strong>Total Tables:</strong> " + Object.keys(stats.tables).length + "</li>";
                        html += "<li><strong>Total Rows:</strong> " + stats.total_rows.toLocaleString() + "</li>";
                        html += "<li><strong>Estimated Size:</strong> " + formatBytes(stats.estimated_size) + "</li>";
                        html += "</ul>";
                        html += "<details style=\"margin-top: 10px;\"><summary style=\"cursor: pointer;\">Table Details</summary><ul style=\"margin: 10px 0 0 20px;\">";
                        for (var table in stats.tables) {
                            html += "<li>" + table + ": " + stats.tables[table].rows.toLocaleString() + " rows (" + formatBytes(stats.tables[table].size) + ")</li>";
                        }
                        html += "</ul></details>";
                        $("#cc-backup-stats").html(html);
                    }
                }
            });
            
            function formatBytes(bytes) {
                if (bytes === 0) return "0 Bytes";
                var k = 1024;
                var sizes = ["Bytes", "KB", "MB", "GB"];
                var i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
            }
            
            // Handle backup form submission
            $("#cc-backup-form").on("submit", function(e) {
                e.preventDefault();
                
                var form = $(this);
                var formData = new FormData(form[0]);
                formData.append("action", "castconductor_database_backup");
                
                // Create hidden form and submit for file download
                var hiddenForm = $("<form>", {
                    method: "POST",
                    action: ajaxurl,
                    style: "display: none;"
                });
                
                hiddenForm.append($("<input>", {
                    type: "hidden",
                    name: "action",
                    value: "castconductor_database_backup"
                }));
                
                hiddenForm.append($("<input>", {
                    type: "hidden",
                    name: "cc_backup_nonce",
                    value: form.find("[name=cc_backup_nonce]").val()
                }));
                
                if (form.find("[name=include_analytics]").is(":checked")) {
                    hiddenForm.append($("<input>", {
                        type: "hidden",
                        name: "include_analytics",
                        value: "1"
                    }));
                }
                
                $("body").append(hiddenForm);
                hiddenForm.submit();
                hiddenForm.remove();
            });
            
            // Handle restore form submission
            $("#cc-restore-form").on("submit", function(e) {
                e.preventDefault();
                
                var form = $(this);
                var formData = new FormData(form[0]);
                formData.append("action", "castconductor_database_restore");
                
                var $result = $("#cc-restore-result");
                var $button = form.find("button[type=submit]");
                var originalText = $button.html();
                
                $button.prop("disabled", true).html("⏳ Restoring...");
                $result.hide();
                
                $.ajax({
                    url: ajaxurl,
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            var html = "<div class=\"notice notice-success\"><p><strong>✅ " + response.data.message + "</strong></p>";
                            html += "<ul style=\"margin: 10px 0 0 20px;\">";
                            html += "<li>Tables restored: " + response.data.tables_restored + "</li>";
                            html += "<li>Rows inserted: " + response.data.rows_inserted.toLocaleString() + "</li>";
                            if (response.data.pre_backup_path) {
                                html += "<li>Pre-restore backup created</li>";
                            }
                            html += "</ul>";
                            if (response.data.warnings && response.data.warnings.length > 0) {
                                html += "<p><strong>Warnings:</strong></p><ul style=\"margin: 10px 0 0 20px;\">";
                                response.data.warnings.forEach(function(w) {
                                    html += "<li>" + w + "</li>";
                                });
                                html += "</ul>";
                            }
                            html += "</div>";
                            $result.html(html).show();
                            
                            // Refresh stats
                            location.reload();
                        } else {
                            $result.html("<div class=\"notice notice-error\"><p><strong>❌ " + response.data.message + "</strong></p></div>").show();
                        }
                    },
                    error: function() {
                        $result.html("<div class=\"notice notice-error\"><p><strong>❌ Request failed. Please try again.</strong></p></div>").show();
                    },
                    complete: function() {
                        $button.prop("disabled", false).html(originalText);
                    }
                });
            });
            
            // Handle pre-restore backup download
            $(".cc-download-pre-restore").on("click", function(e) {
                e.preventDefault();
                var file = $(this).data("file");
                window.location.href = ajaxurl + "?action=castconductor_download_pre_restore&file=" + encodeURIComponent(file);
            });
        });
    ');
}