<?php
/**
 * CastConductor Import Manager
 *
 * Handles importing content blocks, scenes, containers from JSON export files
 * with version compatibility checking and conflict resolution.
 *
 * @package CastConductor
 * @subpackage Import
 * @since 5.2.1
 */

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

class CastConductor_Import_Manager {

    /**
     * Import from JSON export file
     *
     * @param string $file_path Path to JSON export file
     * @param array $options Import options (conflict_mode, import_settings, etc.)
     * @return array Results with counts and errors
     * @throws Exception If file is invalid or incompatible
     */
    public function import_from_file($file_path, $options = array()) {
        // Read and validate file
        if (!file_exists($file_path)) {
            throw new Exception('Import file not found');
        }
        
        $json = file_get_contents($file_path);
        $data = json_decode($json, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON format: ' . json_last_error_msg());
        }
        
        // Validate export format
        if (!isset($data['castconductor_export'])) {
            throw new Exception('Invalid export file format - missing castconductor_export key');
        }
        
        $export = $data['castconductor_export'];
        
        // Version compatibility check
        if (!isset($export['version'])) {
            throw new Exception('Export file missing version information');
        }
        
        if (version_compare($export['version'], CASTCONDUCTOR_VERSION, '>')) {
            throw new Exception(
                'Export file is from newer version (' . $export['version'] . '). ' .
                'Current version: ' . CASTCONDUCTOR_VERSION
            );
        }
        
        // Initialize results
        $results = array(
            'content_blocks' => 0,
            'scenes' => 0,
            'containers' => 0,
            'settings' => false,
            'errors' => array(),
            'warnings' => array()
        );
        
        // Import content blocks
        if (!empty($export['content_blocks'])) {
            try {
                $results['content_blocks'] = $this->import_content_blocks(
                    $export['content_blocks'],
                    $options
                );
            } catch (Exception $e) {
                $results['errors'][] = 'Content Blocks: ' . $e->getMessage();
            }
        }
        
        // Import scenes
        if (!empty($export['scenes'])) {
            try {
                $results['scenes'] = $this->import_scenes($export['scenes'], $options);
            } catch (Exception $e) {
                $results['errors'][] = 'Scenes: ' . $e->getMessage();
            }
        }
        
        // Import containers
        if (!empty($export['containers'])) {
            try {
                $results['containers'] = $this->import_containers($export['containers'], $options);
            } catch (Exception $e) {
                $results['errors'][] = 'Containers: ' . $e->getMessage();
            }
        }
        
        // Import settings (optional)
        if (!empty($export['settings']) && !empty($options['import_settings'])) {
            try {
                $this->import_settings($export['settings']);
                $results['settings'] = true;
            } catch (Exception $e) {
                $results['errors'][] = 'Settings: ' . $e->getMessage();
            }
        }
        
        // Add warnings for media references
        if (!empty($export['media_references'])) {
            $results['warnings'][] = sprintf(
                '%d media file references found. Verify all media URLs are accessible.',
                count($export['media_references'])
            );
        }
        
        return $results;
    }

    /**
     * Import content blocks with conflict resolution
     *
     * @param array $blocks Array of content block data
     * @param array $options Import options
     * @return int Number of blocks imported
     * @throws Exception On database errors
     */
    public function import_content_blocks($blocks, $options = array()) {
        global $wpdb;
        
        $conflict_mode = isset($options['conflict_mode']) ? $options['conflict_mode'] : 'skip';
        $imported = 0;
        $table = $wpdb->prefix . 'castconductor_content_blocks';
        
        foreach ($blocks as $block) {
            // Validate required fields
            if (empty($block['name']) || empty($block['type'])) {
                continue;
            }
            
            // Check if block with same name exists
            $existing_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $table WHERE name = %s",
                $block['name']
            ));
            
            if ($existing_id) {
                switch ($conflict_mode) {
                    case 'skip':
                        continue 2; // Skip to next block
                        
                    case 'overwrite':
                        $result = $wpdb->update(
                            $table,
                            array(
                                'type' => $block['type'],
                                'config' => json_encode($block['config']),
                                'metadata' => json_encode($block['metadata']),
                                'updated_at' => current_time('mysql')
                            ),
                            array('id' => $existing_id),
                            array('%s', '%s', '%s', '%s'),
                            array('%d')
                        );
                        
                        if ($result !== false) {
                            $imported++;
                        }
                        continue 2;
                        
                    case 'duplicate':
                        // Add suffix to create duplicate
                        $block['name'] = $this->make_unique_name($block['name'], $table);
                        break;
                }
            }
            
            // Insert new block
            $result = $wpdb->insert(
                $table,
                array(
                    'name' => $block['name'],
                    'type' => $block['type'],
                    'config' => json_encode($block['config']),
                    'metadata' => json_encode($block['metadata']),
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ),
                array('%s', '%s', '%s', '%s', '%s', '%s')
            );
            
            if ($result) {
                $imported++;
            }
        }
        
        return $imported;
    }

    /**
     * Import scenes
     *
     * @param array $scenes Array of scene data
     * @param array $options Import options
     * @return int Number of scenes imported
     */
    public function import_scenes($scenes, $options = array()) {
        global $wpdb;
        
        $conflict_mode = isset($options['conflict_mode']) ? $options['conflict_mode'] : 'skip';
        $imported = 0;
        $table = $wpdb->prefix . 'castconductor_scenes';
        
        foreach ($scenes as $scene) {
            if (empty($scene['name'])) {
                continue;
            }
            
            $existing_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $table WHERE name = %s",
                $scene['name']
            ));
            
            if ($existing_id) {
                switch ($conflict_mode) {
                    case 'skip':
                        continue 2;
                        
                    case 'overwrite':
                        $result = $wpdb->update(
                            $table,
                            array(
                                'config' => json_encode($scene['config']),
                                'metadata' => json_encode($scene['metadata']),
                                'updated_at' => current_time('mysql')
                            ),
                            array('id' => $existing_id),
                            array('%s', '%s', '%s'),
                            array('%d')
                        );
                        
                        if ($result !== false) {
                            $imported++;
                        }
                        continue 2;
                        
                    case 'duplicate':
                        $scene['name'] = $this->make_unique_name($scene['name'], $table);
                        break;
                }
            }
            
            $result = $wpdb->insert(
                $table,
                array(
                    'name' => $scene['name'],
                    'config' => json_encode($scene['config']),
                    'metadata' => json_encode($scene['metadata']),
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ),
                array('%s', '%s', '%s', '%s', '%s')
            );
            
            if ($result) {
                $imported++;
            }
        }
        
        return $imported;
    }

    /**
     * Import containers
     *
     * @param array $containers Array of container data
     * @param array $options Import options
     * @return int Number of containers imported
     */
    public function import_containers($containers, $options = array()) {
        global $wpdb;
        
        $conflict_mode = isset($options['conflict_mode']) ? $options['conflict_mode'] : 'skip';
        $imported = 0;
        $table = $wpdb->prefix . 'castconductor_containers';
        
        foreach ($containers as $container) {
            if (empty($container['name'])) {
                continue;
            }
            
            $existing_id = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $table WHERE name = %s",
                $container['name']
            ));
            
            if ($existing_id) {
                switch ($conflict_mode) {
                    case 'skip':
                        continue 2;
                        
                    case 'overwrite':
                        $result = $wpdb->update(
                            $table,
                            array(
                                'type' => $container['type'],
                                'config' => json_encode($container['config']),
                                'content_block_ids' => json_encode($container['content_block_ids']),
                                'metadata' => json_encode($container['metadata']),
                                'updated_at' => current_time('mysql')
                            ),
                            array('id' => $existing_id),
                            array('%s', '%s', '%s', '%s', '%s'),
                            array('%d')
                        );
                        
                        if ($result !== false) {
                            $imported++;
                        }
                        continue 2;
                        
                    case 'duplicate':
                        $container['name'] = $this->make_unique_name($container['name'], $table);
                        break;
                }
            }
            
            $result = $wpdb->insert(
                $table,
                array(
                    'name' => $container['name'],
                    'type' => $container['type'],
                    'config' => json_encode($container['config']),
                    'content_block_ids' => json_encode($container['content_block_ids']),
                    'metadata' => json_encode($container['metadata']),
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ),
                array('%s', '%s', '%s', '%s', '%s', '%s', '%s')
            );
            
            if ($result) {
                $imported++;
            }
        }
        
        return $imported;
    }

    /**
     * Import global settings
     *
     * @param array $settings Settings data
     */
    public function import_settings($settings) {
        // Only import if values are not empty
        if (!empty($settings['stream_url'])) {
            update_option('castconductor_stream_url', sanitize_url($settings['stream_url']));
        }
        
        if (!empty($settings['metadata_url'])) {
            update_option('castconductor_metadata_url', sanitize_url($settings['metadata_url']));
        }
        
        if (!empty($settings['default_duration'])) {
            update_option('castconductor_default_duration', intval($settings['default_duration']));
        }
        
        if (!empty($settings['canvas_width'])) {
            update_option('castconductor_canvas_width', intval($settings['canvas_width']));
        }
        
        if (!empty($settings['canvas_height'])) {
            update_option('castconductor_canvas_height', intval($settings['canvas_height']));
        }
    }

    /**
     * Make unique name by adding suffix
     *
     * @param string $name Base name
     * @param string $table Database table to check
     * @return string Unique name
     */
    private function make_unique_name($name, $table) {
        global $wpdb;
        
        $base_name = $name;
        $suffix = 1;
        
        // If name already has (Imported N) suffix, extract it
        if (preg_match('/^(.+)\s+\(Imported\s+(\d+)\)$/', $name, $matches)) {
            $base_name = $matches[1];
            $suffix = intval($matches[2]) + 1;
        } else {
            $base_name = $name . ' (Imported';
        }
        
        // Find next available number
        while (true) {
            $test_name = $base_name . ' ' . $suffix . ')';
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM $table WHERE name = %s",
                $test_name
            ));
            
            if (!$exists) {
                return $test_name;
            }
            
            $suffix++;
        }
    }

    /**
     * Validate export file before importing
     *
     * @param string $file_path Path to JSON file
     * @return array Validation results with counts and warnings
     */
    public function validate_export_file($file_path) {
        try {
            $json = file_get_contents($file_path);
            $data = json_decode($json, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                return array(
                    'valid' => false,
                    'error' => 'Invalid JSON: ' . json_last_error_msg()
                );
            }
            
            if (!isset($data['castconductor_export'])) {
                return array(
                    'valid' => false,
                    'error' => 'Not a CastConductor export file'
                );
            }
            
            $export = $data['castconductor_export'];
            
            return array(
                'valid' => true,
                'version' => $export['version'],
                'export_date' => $export['export_date'],
                'export_type' => $export['export_type'],
                'counts' => array(
                    'content_blocks' => isset($export['content_blocks']) ? count($export['content_blocks']) : 0,
                    'scenes' => isset($export['scenes']) ? count($export['scenes']) : 0,
                    'containers' => isset($export['containers']) ? count($export['containers']) : 0,
                    'media_references' => isset($export['media_references']) ? count($export['media_references']) : 0
                )
            );
            
        } catch (Exception $e) {
            return array(
                'valid' => false,
                'error' => $e->getMessage()
            );
        }
    }
}
