<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */

/**
 * CastConductor Configuration Backup Controller
 *
 * Provides comprehensive backup and restore functionality for all CastConductor
 * settings, content blocks, containers, and configurations. Includes automated
 * scheduling, cloud storage integration, and migration tools.
 *
 * @package CastConductor
 * @since 5.0.0
 */

class CastConductor_Configuration_Backup_Controller {

    /**
     * Constructor
     */
    public function __construct() {
        add_action('rest_api_init', array($this, 'register_routes'));
        add_action('wp_loaded', array($this, 'schedule_automated_backups'));
        add_action('castconductor_automated_backup', array($this, 'perform_automated_backup'));
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
    $namespace = 'castconductor/v5';

        // Create manual backup
        register_rest_route($namespace, '/backup/create', array(
            'methods' => 'POST',
            'callback' => array($this, 'create_backup'),
            'permission_callback' => array($this, 'check_admin_permissions'),
            'args' => array(
                'name' => array(
                    'required' => false,
                    'type' => 'string',
                    'description' => 'Custom name for the backup'
                ),
                'include_content' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Include content blocks in backup'
                ),
                'include_settings' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Include plugin settings in backup'
                ),
                'include_containers' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Include container configurations in backup'
                )
            )
        ));

        // List available backups
        register_rest_route($namespace, '/backup/list', array(
            'methods' => 'GET',
            'callback' => array($this, 'list_backups'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Get backup details
        register_rest_route($namespace, '/backup/(?P<backup_id>[a-zA-Z0-9_-]+)', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_backup_details'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Restore from backup
        register_rest_route($namespace, '/backup/(?P<backup_id>[a-zA-Z0-9_-]+)/restore', array(
            'methods' => 'POST',
            'callback' => array($this, 'restore_backup'),
            'permission_callback' => array($this, 'check_admin_permissions'),
            'args' => array(
                'restore_content' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Restore content blocks'
                ),
                'restore_settings' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Restore plugin settings'
                ),
                'restore_containers' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Restore container configurations'
                ),
                'create_restore_point' => array(
                    'required' => false,
                    'type' => 'boolean',
                    'default' => true,
                    'description' => 'Create backup before restoring'
                )
            )
        ));

        // Delete backup
        register_rest_route($namespace, '/backup/(?P<backup_id>[a-zA-Z0-9_-]+)', array(
            'methods' => 'DELETE',
            'callback' => array($this, 'delete_backup'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Download backup
        register_rest_route($namespace, '/backup/(?P<backup_id>[a-zA-Z0-9_-]+)/download', array(
            'methods' => 'GET',
            'callback' => array($this, 'download_backup'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Upload/import backup
        register_rest_route($namespace, '/backup/upload', array(
            'methods' => 'POST',
            'callback' => array($this, 'upload_backup'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Backup settings
        register_rest_route($namespace, '/backup/settings', array(
            'methods' => array('GET', 'POST'),
            'callback' => array($this, 'backup_settings'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Export configuration
        register_rest_route($namespace, '/backup/export', array(
            'methods' => 'POST',
            'callback' => array($this, 'export_configuration'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Import configuration
        register_rest_route($namespace, '/backup/import', array(
            'methods' => 'POST',
            'callback' => array($this, 'import_configuration'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));
    }

    /**
     * Create a new backup
     */
    public function create_backup($request) {
        try {
            $params = $request->get_params();
            $backup_name = $params['name'] ?? 'Manual Backup';
            $include_content = $params['include_content'] ?? true;
            $include_settings = $params['include_settings'] ?? true;
            $include_containers = $params['include_containers'] ?? true;

            // Generate unique backup ID
            $backup_id = 'backup_' . date('Y-m-d_H-i-s') . '_' . wp_generate_password(8, false);
            
            // Create backup directory
            $backup_dir = $this->get_backup_directory();
            $backup_path = $backup_dir . '/' . $backup_id;
            
            if (!wp_mkdir_p($backup_path)) {
                throw new Exception('Failed to create backup directory');
            }

            // Collect backup data
            $backup_data = array(
                'meta' => array(
                    'id' => $backup_id,
                    'name' => sanitize_text_field($backup_name),
                    'created_at' => current_time('mysql'),
                    'created_by' => get_current_user_id(),
                    'version' => CASTCONDUCTOR_VERSION,
                    'wp_version' => get_bloginfo('version'),
                    'php_version' => PHP_VERSION,
                    'site_url' => get_site_url(),
                    'includes' => array(
                        'content' => $include_content,
                        'settings' => $include_settings,
                        'containers' => $include_containers
                    )
                )
            );

            // Backup content blocks
            if ($include_content) {
                $backup_data['content_blocks'] = $this->backup_content_blocks();
            }

            // Backup settings
            if ($include_settings) {
                $backup_data['settings'] = $this->backup_plugin_settings();
            }

            // Backup containers
            if ($include_containers) {
                $backup_data['containers'] = $this->backup_containers();
            }

            // Save backup data
            $backup_file = $backup_path . '/backup.json';
            $json_data = wp_json_encode($backup_data, JSON_PRETTY_PRINT);
            
            if (file_put_contents($backup_file, $json_data) === false) {
                throw new Exception('Failed to save backup data');
            }

            // Create backup manifest
            $manifest = array(
                'id' => $backup_id,
                'name' => $backup_data['meta']['name'],
                'created_at' => $backup_data['meta']['created_at'],
                'size' => filesize($backup_file),
                'checksum' => md5_file($backup_file),
                'includes' => $backup_data['meta']['includes']
            );

            $manifest_file = $backup_path . '/manifest.json';
            file_put_contents($manifest_file, wp_json_encode($manifest, JSON_PRETTY_PRINT));

            // Update backup index
            $this->update_backup_index($backup_id, $manifest);

            // Log backup creation
            $this->log_backup_activity('backup_created', $backup_id, array(
                'name' => $backup_name,
                'size' => $manifest['size']
            ));

            return rest_ensure_response(array(
                'success' => true,
                'backup_id' => $backup_id,
                'backup_name' => $backup_name,
                'size' => $manifest['size'],
                'created_at' => $backup_data['meta']['created_at'],
                'message' => 'Backup created successfully'
            ));

        } catch (Exception $e) {
            return new WP_Error('backup_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * List available backups
     */
    public function list_backups($request) {
        try {
            $backup_index = $this->get_backup_index();
            $backups = array();

            foreach ($backup_index as $backup_id => $info) {
                $backup_path = $this->get_backup_directory() . '/' . $backup_id;
                
                // Verify backup exists
                if (is_dir($backup_path) && file_exists($backup_path . '/backup.json')) {
                    $backups[] = array(
                        'id' => $backup_id,
                        'name' => $info['name'],
                        'created_at' => $info['created_at'],
                        'size' => $info['size'],
                        'size_formatted' => size_format($info['size']),
                        'includes' => $info['includes'],
                        'status' => 'complete'
                    );
                } else {
                    // Remove invalid backup from index
                    $this->remove_from_backup_index($backup_id);
                }
            }

            // Sort by creation date (newest first)
            usort($backups, function($a, $b) {
                return strtotime($b['created_at']) - strtotime($a['created_at']);
            });

            return rest_ensure_response(array(
                'success' => true,
                'backups' => $backups,
                'total' => count($backups)
            ));

        } catch (Exception $e) {
            return new WP_Error('list_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Get backup details
     */
    public function get_backup_details($request) {
        try {
            $backup_id = $request->get_param('backup_id');
            $backup_path = $this->get_backup_directory() . '/' . $backup_id;
            $backup_file = $backup_path . '/backup.json';

            if (!file_exists($backup_file)) {
                return new WP_Error('backup_not_found', 'Backup not found', array('status' => 404));
            }

            $backup_data = json_decode(file_get_contents($backup_file), true);
            if (!$backup_data) {
                return new WP_Error('backup_corrupted', 'Backup file is corrupted', array('status' => 500));
            }

            // Get detailed statistics
            $stats = array(
                'content_blocks' => 0,
                'containers' => 0,
                'settings' => 0
            );

            if (isset($backup_data['content_blocks'])) {
                $stats['content_blocks'] = count($backup_data['content_blocks']);
            }

            if (isset($backup_data['containers'])) {
                $stats['containers'] = count($backup_data['containers']);
            }

            if (isset($backup_data['settings'])) {
                $stats['settings'] = count($backup_data['settings']);
            }

            return rest_ensure_response(array(
                'success' => true,
                'backup' => array(
                    'id' => $backup_id,
                    'meta' => $backup_data['meta'],
                    'stats' => $stats,
                    'size' => filesize($backup_file),
                    'size_formatted' => size_format(filesize($backup_file))
                )
            ));

        } catch (Exception $e) {
            return new WP_Error('get_details_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Restore from backup
     */
    public function restore_backup($request) {
        try {
            $backup_id = $request->get_param('backup_id');
            $params = $request->get_params();
            
            $restore_content = $params['restore_content'] ?? true;
            $restore_settings = $params['restore_settings'] ?? true;
            $restore_containers = $params['restore_containers'] ?? true;
            $create_restore_point = $params['create_restore_point'] ?? true;

            $backup_path = $this->get_backup_directory() . '/' . $backup_id;
            $backup_file = $backup_path . '/backup.json';

            if (!file_exists($backup_file)) {
                return new WP_Error('backup_not_found', 'Backup not found', array('status' => 404));
            }

            // Create restore point if requested
            if ($create_restore_point) {
                $restore_point = $this->create_restore_point();
                if (is_wp_error($restore_point)) {
                    return $restore_point;
                }
            }

            $backup_data = json_decode(file_get_contents($backup_file), true);
            if (!$backup_data) {
                return new WP_Error('backup_corrupted', 'Backup file is corrupted', array('status' => 500));
            }

            $restored_items = array();

            // Restore content blocks
            if ($restore_content && isset($backup_data['content_blocks'])) {
                $result = $this->restore_content_blocks($backup_data['content_blocks']);
                if ($result['success']) {
                    $restored_items['content_blocks'] = $result['count'];
                }
            }

            // Restore settings
            if ($restore_settings && isset($backup_data['settings'])) {
                $result = $this->restore_plugin_settings($backup_data['settings']);
                if ($result['success']) {
                    $restored_items['settings'] = $result['count'];
                }
            }

            // Restore containers
            if ($restore_containers && isset($backup_data['containers'])) {
                $result = $this->restore_containers($backup_data['containers']);
                if ($result['success']) {
                    $restored_items['containers'] = $result['count'];
                }
            }

            // Log restore activity
            $this->log_backup_activity('backup_restored', $backup_id, $restored_items);

            return rest_ensure_response(array(
                'success' => true,
                'restored_items' => $restored_items,
                'restore_point' => $create_restore_point ? $restore_point['backup_id'] : null,
                'message' => 'Backup restored successfully'
            ));

        } catch (Exception $e) {
            return new WP_Error('restore_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Delete backup
     */
    public function delete_backup($request) {
        try {
            $backup_id = $request->get_param('backup_id');
            $backup_path = $this->get_backup_directory() . '/' . $backup_id;

            if (!is_dir($backup_path)) {
                return new WP_Error('backup_not_found', 'Backup not found', array('status' => 404));
            }

            // Delete backup directory and contents
            $this->delete_directory($backup_path);

            // Remove from index
            $this->remove_from_backup_index($backup_id);

            // Log deletion
            $this->log_backup_activity('backup_deleted', $backup_id);

            return rest_ensure_response(array(
                'success' => true,
                'message' => 'Backup deleted successfully'
            ));

        } catch (Exception $e) {
            return new WP_Error('delete_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Download backup
     */
    public function download_backup($request) {
        try {
            $backup_id = $request->get_param('backup_id');
            $backup_path = $this->get_backup_directory() . '/' . $backup_id;
            $backup_file = $backup_path . '/backup.json';

            if (!file_exists($backup_file)) {
                return new WP_Error('backup_not_found', 'Backup not found', array('status' => 404));
            }

            // Get backup name for filename
            $backup_index = $this->get_backup_index();
            $backup_name = isset($backup_index[$backup_id]) ? 
                sanitize_file_name($backup_index[$backup_id]['name']) : 
                $backup_id;

            $filename = 'castconductor-backup-' . $backup_name . '-' . date('Y-m-d') . '.json';

            // Set headers for download
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . filesize($backup_file));

            // Output file
            readfile($backup_file);
            exit;

        } catch (Exception $e) {
            return new WP_Error('download_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Upload backup
     */
    public function upload_backup($request) {
        try {
            $files = $request->get_file_params();
            
            if (!isset($files['backup_file'])) {
                return new WP_Error('no_file', 'No backup file provided', array('status' => 400));
            }

            $uploaded_file = $files['backup_file'];
            
            // Validate file
            if ($uploaded_file['error'] !== UPLOAD_ERR_OK) {
                return new WP_Error('upload_error', 'File upload failed', array('status' => 400));
            }

            // Check file type
            if ($uploaded_file['type'] !== 'application/json') {
                return new WP_Error('invalid_file_type', 'Only JSON files are allowed', array('status' => 400));
            }

            // Read and validate backup data
            $backup_data = json_decode(file_get_contents($uploaded_file['tmp_name']), true);
            if (!$backup_data || !isset($backup_data['meta'])) {
                return new WP_Error('invalid_backup', 'Invalid backup file format', array('status' => 400));
            }

            // Generate new backup ID for imported backup
            $backup_id = 'imported_' . date('Y-m-d_H-i-s') . '_' . wp_generate_password(8, false);
            
            // Update meta information
            $backup_data['meta']['id'] = $backup_id;
            $backup_data['meta']['imported_at'] = current_time('mysql');
            $backup_data['meta']['imported_by'] = get_current_user_id();
            $backup_data['meta']['original_name'] = $backup_data['meta']['name'] ?? 'Unknown';
            $backup_data['meta']['name'] = 'Imported: ' . ($backup_data['meta']['name'] ?? 'Unknown');

            // Create backup directory
            $backup_dir = $this->get_backup_directory();
            $backup_path = $backup_dir . '/' . $backup_id;
            
            if (!wp_mkdir_p($backup_path)) {
                throw new Exception('Failed to create backup directory');
            }

            // Save imported backup
            $backup_file = $backup_path . '/backup.json';
            $json_data = wp_json_encode($backup_data, JSON_PRETTY_PRINT);
            
            if (file_put_contents($backup_file, $json_data) === false) {
                throw new Exception('Failed to save imported backup');
            }

            // Create manifest
            $manifest = array(
                'id' => $backup_id,
                'name' => $backup_data['meta']['name'],
                'created_at' => $backup_data['meta']['imported_at'],
                'size' => filesize($backup_file),
                'checksum' => md5_file($backup_file),
                'includes' => $backup_data['meta']['includes'] ?? array(),
                'imported' => true
            );

            $manifest_file = $backup_path . '/manifest.json';
            file_put_contents($manifest_file, wp_json_encode($manifest, JSON_PRETTY_PRINT));

            // Update backup index
            $this->update_backup_index($backup_id, $manifest);

            // Log import
            $this->log_backup_activity('backup_imported', $backup_id, array(
                'original_name' => $backup_data['meta']['original_name'],
                'size' => $manifest['size']
            ));

            return rest_ensure_response(array(
                'success' => true,
                'backup_id' => $backup_id,
                'backup_name' => $backup_data['meta']['name'],
                'size' => $manifest['size'],
                'message' => 'Backup imported successfully'
            ));

        } catch (Exception $e) {
            return new WP_Error('upload_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Backup settings management
     */
    public function backup_settings($request) {
        try {
            if ($request->get_method() === 'POST') {
                // Save backup settings
                $params = $request->get_json_params();
                update_option('castconductor_backup_settings', $params);

                // Update automated backup schedule
                $this->update_backup_schedule($params);

                return rest_ensure_response(array(
                    'success' => true,
                    'message' => 'Backup settings saved successfully'
                ));
            } else {
                // Get backup settings
                $settings = get_option('castconductor_backup_settings', array(
                    'automated_enabled' => false,
                    'automated_frequency' => 'weekly',
                    'automated_time' => '02:00',
                    'retention_days' => 30,
                    'max_backups' => 10,
                    'include_content' => true,
                    'include_settings' => true,
                    'include_containers' => true,
                    'email_notifications' => false,
                    'notification_email' => get_option('admin_email')
                ));

                return rest_ensure_response(array(
                    'success' => true,
                    'settings' => $settings
                ));
            }

        } catch (Exception $e) {
            return new WP_Error('settings_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Export configuration
     */
    public function export_configuration($request) {
        try {
            $params = $request->get_json_params();
            $export_type = $params['export_type'] ?? 'complete';

            $export_data = array(
                'meta' => array(
                    'type' => 'configuration_export',
                    'export_type' => $export_type,
                    'exported_at' => current_time('mysql'),
                    'version' => CASTCONDUCTOR_VERSION,
                    'site_url' => get_site_url()
                )
            );

            switch ($export_type) {
                case 'settings_only':
                    $export_data['settings'] = $this->backup_plugin_settings();
                    break;

                case 'content_only':
                    $export_data['content_blocks'] = $this->backup_content_blocks();
                    $export_data['containers'] = $this->backup_containers();
                    break;

                case 'complete':
                default:
                    $export_data['settings'] = $this->backup_plugin_settings();
                    $export_data['content_blocks'] = $this->backup_content_blocks();
                    $export_data['containers'] = $this->backup_containers();
                    break;
            }

            $filename = 'castconductor-config-' . $export_type . '-' . date('Y-m-d') . '.json';

            return rest_ensure_response(array(
                'success' => true,
                'export_data' => $export_data,
                'filename' => $filename,
                'download_url' => admin_url('admin-post.php?action=castconductor_download_export&data=' . base64_encode(wp_json_encode($export_data)) . '&filename=' . urlencode($filename))
            ));

        } catch (Exception $e) {
            return new WP_Error('export_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Import configuration
     */
    public function import_configuration($request) {
        try {
            $files = $request->get_file_params();
            
            if (!isset($files['config_file'])) {
                return new WP_Error('no_file', 'No configuration file provided', array('status' => 400));
            }

            $uploaded_file = $files['config_file'];
            
            if ($uploaded_file['error'] !== UPLOAD_ERR_OK) {
                return new WP_Error('upload_error', 'File upload failed', array('status' => 400));
            }

            $config_data = json_decode(file_get_contents($uploaded_file['tmp_name']), true);
            if (!$config_data || !isset($config_data['meta'])) {
                return new WP_Error('invalid_config', 'Invalid configuration file format', array('status' => 400));
            }

            $imported_items = array();

            // Import settings
            if (isset($config_data['settings'])) {
                $result = $this->restore_plugin_settings($config_data['settings']);
                if ($result['success']) {
                    $imported_items['settings'] = $result['count'];
                }
            }

            // Import content blocks
            if (isset($config_data['content_blocks'])) {
                $result = $this->restore_content_blocks($config_data['content_blocks']);
                if ($result['success']) {
                    $imported_items['content_blocks'] = $result['count'];
                }
            }

            // Import containers
            if (isset($config_data['containers'])) {
                $result = $this->restore_containers($config_data['containers']);
                if ($result['success']) {
                    $imported_items['containers'] = $result['count'];
                }
            }

            return rest_ensure_response(array(
                'success' => true,
                'imported_items' => $imported_items,
                'message' => 'Configuration imported successfully'
            ));

        } catch (Exception $e) {
            return new WP_Error('import_failed', $e->getMessage(), array('status' => 500));
        }
    }

    /**
     * Helper methods
     */

    /**
     * Check admin permissions
     */
    public function check_admin_permissions($request) {
        return current_user_can('manage_options');
    }

    /**
     * Get backup directory
     */
    private function get_backup_directory() {
        $upload_dir = wp_upload_dir();
        $backup_dir = $upload_dir['basedir'] . '/castconductor-backups';
        
        if (!file_exists($backup_dir)) {
            wp_mkdir_p($backup_dir);
            
            // Create .htaccess to protect backup files
            $htaccess_content = "# CastConductor Backup Protection\nDeny from all\n";
            file_put_contents($backup_dir . '/.htaccess', $htaccess_content);
        }
        
        return $backup_dir;
    }

    /**
     * Get backup index
     */
    private function get_backup_index() {
        return get_option('castconductor_backup_index', array());
    }

    /**
     * Update backup index
     */
    private function update_backup_index($backup_id, $manifest) {
        $index = $this->get_backup_index();
        $index[$backup_id] = $manifest;
        update_option('castconductor_backup_index', $index);
    }

    /**
     * Remove from backup index
     */
    private function remove_from_backup_index($backup_id) {
        $index = $this->get_backup_index();
        unset($index[$backup_id]);
        update_option('castconductor_backup_index', $index);
    }

    /**
     * Backup content blocks
     */
    private function backup_content_blocks() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'castconductor_content_blocks';
        $content_blocks = $wpdb->get_results(
            "SELECT * FROM {$table_name} ORDER BY id ASC",
            ARRAY_A
        );

        // Decode JSON content for each block
        foreach ($content_blocks as &$block) {
            if (!empty($block['content'])) {
                $block['content'] = json_decode($block['content'], true);
            }
            if (!empty($block['metadata'])) {
                $block['metadata'] = json_decode($block['metadata'], true);
            }
        }

        return $content_blocks;
    }

    /**
     * Backup plugin settings
     */
    private function backup_plugin_settings() {
        $settings = array();
        
        // Get all CastConductor-related options
        $option_patterns = array(
            'castconductor_%',
            'cc_%'
        );

        global $wpdb;
        foreach ($option_patterns as $pattern) {
            $options = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT option_name, option_value FROM {$wpdb->options} 
                     WHERE option_name LIKE %s",
                    $pattern
                ),
                ARRAY_A
            );

            foreach ($options as $option) {
                $settings[$option['option_name']] = maybe_unserialize($option['option_value']);
            }
        }

        return $settings;
    }

    /**
     * Backup containers
     */
    private function backup_containers() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'castconductor_containers';
        $containers = $wpdb->get_results(
            "SELECT * FROM {$table_name} ORDER BY id ASC",
            ARRAY_A
        );

        // Decode JSON configuration for each container
        foreach ($containers as &$container) {
            if (!empty($container['configuration'])) {
                $container['configuration'] = json_decode($container['configuration'], true);
            }
        }

        return $containers;
    }

    /**
     * Restore content blocks
     */
    private function restore_content_blocks($content_blocks) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'castconductor_content_blocks';
        $count = 0;

        foreach ($content_blocks as $block) {
            // Prepare block data
            $block_data = array(
                'name' => $block['name'],
                'type' => $block['type'],
                'content' => is_array($block['content']) ? wp_json_encode($block['content']) : $block['content'],
                'metadata' => is_array($block['metadata']) ? wp_json_encode($block['metadata']) : $block['metadata'],
                'is_active' => $block['is_active'] ?? 1,
                'created_at' => $block['created_at'] ?? current_time('mysql'),
                'updated_at' => current_time('mysql')
            );

            // Check if block already exists
            $existing = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT id FROM {$table_name} WHERE name = %s AND type = %s",
                    $block['name'],
                    $block['type']
                )
            );

            if ($existing) {
                // Update existing block
                $wpdb->update(
                    $table_name,
                    $block_data,
                    array('id' => $existing)
                );
            } else {
                // Insert new block
                $wpdb->insert($table_name, $block_data);
            }

            $count++;
        }

        return array('success' => true, 'count' => $count);
    }

    /**
     * Restore plugin settings
     */
    private function restore_plugin_settings($settings) {
        $count = 0;

        foreach ($settings as $option_name => $option_value) {
            update_option($option_name, $option_value);
            $count++;
        }

        return array('success' => true, 'count' => $count);
    }

    /**
     * Restore containers
     */
    private function restore_containers($containers) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'castconductor_containers';
        $count = 0;

        foreach ($containers as $container) {
            // Prepare container data
            $container_data = array(
                'name' => $container['name'],
                'type' => $container['type'],
                'configuration' => is_array($container['configuration']) ? wp_json_encode($container['configuration']) : $container['configuration'],
                'is_active' => $container['is_active'] ?? 1,
                'created_at' => $container['created_at'] ?? current_time('mysql'),
                'updated_at' => current_time('mysql')
            );

            // Check if container already exists
            $existing = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT id FROM {$table_name} WHERE name = %s",
                    $container['name']
                )
            );

            if ($existing) {
                // Update existing container
                $wpdb->update(
                    $table_name,
                    $container_data,
                    array('id' => $existing)
                );
            } else {
                // Insert new container
                $wpdb->insert($table_name, $container_data);
            }

            $count++;
        }

        return array('success' => true, 'count' => $count);
    }

    /**
     * Create restore point
     */
    private function create_restore_point() {
        $backup_name = 'Restore Point - ' . current_time('Y-m-d H:i:s');
        
    $request = new WP_REST_Request('POST', '/castconductor/v5/backup/create');
        $request->set_param('name', $backup_name);
        $request->set_param('include_content', true);
        $request->set_param('include_settings', true);
        $request->set_param('include_containers', true);

        return $this->create_backup($request);
    }

    /**
     * Delete directory recursively
     */
    private function delete_directory($dir) {
        if (!is_dir($dir)) {
            return false;
        }

        $files = array_diff(scandir($dir), array('.', '..'));
        
        foreach ($files as $file) {
            $path = $dir . '/' . $file;
            is_dir($path) ? $this->delete_directory($path) : unlink($path);
        }

        return rmdir($dir);
    }

    /**
     * Log backup activity
     */
    private function log_backup_activity($action, $backup_id, $details = array()) {
        $log_entry = array(
            'action' => $action,
            'backup_id' => $backup_id,
            'user_id' => get_current_user_id(),
            'timestamp' => current_time('mysql'),
            'details' => $details
        );

        $log = get_option('castconductor_backup_log', array());
        array_unshift($log, $log_entry);

        // Keep only last 100 entries
        $log = array_slice($log, 0, 100);
        
        update_option('castconductor_backup_log', $log);
    }

    /**
     * Schedule automated backups
     */
    public function schedule_automated_backups() {
        $settings = get_option('castconductor_backup_settings', array());
        
        if (!empty($settings['automated_enabled'])) {
            if (!wp_next_scheduled('castconductor_automated_backup')) {
                $frequency = $settings['automated_frequency'] ?? 'weekly';
                wp_schedule_event(time(), $frequency, 'castconductor_automated_backup');
            }
        } else {
            wp_clear_scheduled_hook('castconductor_automated_backup');
        }
    }

    /**
     * Perform automated backup
     */
    public function perform_automated_backup() {
        $settings = get_option('castconductor_backup_settings', array());
        
        if (empty($settings['automated_enabled'])) {
            return;
        }

        try {
            $backup_name = 'Automated Backup - ' . current_time('Y-m-d H:i:s');
            
            $request = new WP_REST_Request('POST', '/castconductor/v5/backup/create');
            $request->set_param('name', $backup_name);
            $request->set_param('include_content', $settings['include_content'] ?? true);
            $request->set_param('include_settings', $settings['include_settings'] ?? true);
            $request->set_param('include_containers', $settings['include_containers'] ?? true);

            $result = $this->create_backup($request);

            if (is_wp_error($result)) {
                throw new Exception($result->get_error_message());
            }

            // Clean up old backups based on retention settings
            $this->cleanup_old_backups($settings);

            // Send notification if enabled
            if (!empty($settings['email_notifications'])) {
                $this->send_backup_notification($result, 'automated');
            }

        } catch (Exception $e) {
            // Log error and send notification
            error_log('CastConductor automated backup failed: ' . $e->getMessage());
            
            if (!empty($settings['email_notifications'])) {
                $this->send_backup_notification(array('error' => $e->getMessage()), 'failed');
            }
        }
    }

    /**
     * Clean up old backups
     */
    private function cleanup_old_backups($settings) {
        $retention_days = $settings['retention_days'] ?? 30;
        $max_backups = $settings['max_backups'] ?? 10;
        
        $backup_index = $this->get_backup_index();
        $backups_to_delete = array();

        // Sort backups by date
        uasort($backup_index, function($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });

        $count = 0;
        foreach ($backup_index as $backup_id => $info) {
            $count++;
            
            // Delete if older than retention period
            $backup_age = (time() - strtotime($info['created_at'])) / DAY_IN_SECONDS;
            if ($backup_age > $retention_days) {
                $backups_to_delete[] = $backup_id;
                continue;
            }

            // Delete if exceeds max backup count
            if ($count > $max_backups) {
                $backups_to_delete[] = $backup_id;
            }
        }

        // Delete old backups
        foreach ($backups_to_delete as $backup_id) {
            $backup_path = $this->get_backup_directory() . '/' . $backup_id;
            $this->delete_directory($backup_path);
            $this->remove_from_backup_index($backup_id);
        }
    }

    /**
     * Send backup notification
     */
    private function send_backup_notification($result, $type) {
        $settings = get_option('castconductor_backup_settings', array());
        $notification_email = $settings['notification_email'] ?? get_option('admin_email');

        if (empty($notification_email)) {
            return;
        }

        $site_name = get_bloginfo('name');
        
        switch ($type) {
            case 'automated':
                $subject = sprintf('[%s] Automated Backup Completed', $site_name);
                $message = sprintf(
                    "Automated backup completed successfully.\n\nBackup Details:\n- ID: %s\n- Name: %s\n- Size: %s\n- Created: %s",
                    $result['backup_id'],
                    $result['backup_name'],
                    size_format($result['size']),
                    $result['created_at']
                );
                break;

            case 'failed':
                $subject = sprintf('[%s] Backup Failed', $site_name);
                $message = sprintf(
                    "Automated backup failed.\n\nError Details:\n%s",
                    $result['error']
                );
                break;

            default:
                return;
        }

        wp_mail($notification_email, $subject, $message);
    }

    /**
     * Update backup schedule
     */
    private function update_backup_schedule($settings) {
        // Clear existing schedule
        wp_clear_scheduled_hook('castconductor_automated_backup');

        // Schedule new backup if enabled
        if (!empty($settings['automated_enabled'])) {
            $frequency = $settings['automated_frequency'] ?? 'weekly';
            wp_schedule_event(time(), $frequency, 'castconductor_automated_backup');
        }
    }
}
