<?php
namespace IntentDeep\VirtualFiles\Traits;

use IntentDeep\VirtualFiles\Controllers\DuplicateFileException;
use Exception;

/**
 * Helper trait for import/export functionality
 */
trait ImportExportHelper {

    /**
     * Import virtual files from JSON
     */
    private function importFromJson(string $json_content): array {
        $data = json_decode($json_content, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception(esc_html__('Invalid JSON format: ', 'intentdeep-virtual-files') . esc_html(json_last_error_msg()));
        }

        if (!isset($data['files']) || !is_array($data['files'])) {
            throw new Exception(esc_html__('Invalid export format. Missing files array.', 'intentdeep-virtual-files'));
        }

        $result = [
            'processed' => 0,
            'imported' => 0,
            'skipped' => 0,
            'errors' => 0,
            'details' => []
        ];

        foreach ($data['files'] as $file_data) {
            $result['processed']++;

            try {
                $this->importSingleFile($file_data);
                $result['imported']++;
                $result['details'][] = [
                    'filename' => $file_data['filename'] ?? 'Unknown',
                    'status' => 'imported',
                    'message' => __('Imported successfully', 'intentdeep-virtual-files')
                ];
            } catch (DuplicateFileException $e) {
                $result['skipped']++;
                $result['details'][] = [
                    'filename' => $file_data['filename'] ?? 'Unknown',
                    'status' => 'skipped',
                    'message' => __('File already exists', 'intentdeep-virtual-files')
                ];
            } catch (Exception $e) {
                $result['errors']++;
                $result['details'][] = [
                    'filename' => $file_data['filename'] ?? 'Unknown',
                    'status' => 'error',
                    'message' => $e->getMessage()
                ];
            }
        }

        return $result;
    }

    /**
     * Import virtual files from ZIP
     */
    private function importFromZip(string $zip_content, string $zip_path): array {
        // For now, we'll handle ZIP as multiple JSON files
        // This could be expanded to handle direct file content
        throw new Exception(esc_html__('ZIP import not yet implemented. Please export as JSON file.', 'intentdeep-virtual-files'));
    }

    /**
     * Import a single virtual file
     */
    private function importSingleFile(array $file_data): void {
        // Validate required data
        if (empty($file_data['filename']) || empty($file_data['content'])) {
            throw new Exception(esc_html__('Missing filename or content', 'intentdeep-virtual-files'));
        }

        // Validate filename for security
        $filename = sanitize_file_name($file_data['filename']);
        if (empty($filename)) {
            throw new Exception(esc_html__('Invalid filename', 'intentdeep-virtual-files'));
        }

        // Check if file already exists in NEW post type only
        // This allows importing from old backups (virtual_file) to new post type (idep_virtual_file)
        // Even if old posts still exist in database, we create new ones with the new post type
        $existing = get_posts([
            'post_type' => 'idep_virtual_file',
            'meta_key' => '_vf_filename',
            'meta_value' => $filename,
            'posts_per_page' => 1
        ]);

        if (!empty($existing)) {
            // File already exists in NEW post type - skip it
            throw new DuplicateFileException(esc_html__('File already exists: ', 'intentdeep-virtual-files') . esc_html($filename));
        }

        // Create post
        // Always create with new post type 'idep_virtual_file', even if importing from legacy 'virtual_file' backup
        $post_data = [
            'post_title' => sanitize_text_field($file_data['title'] ?? $filename),
            'post_content' => '',
            'post_status' => $file_data['status'] ?? 'publish',
            'post_type' => 'idep_virtual_file',
            'post_name' => sanitize_title($file_data['slug'] ?? $filename),
        ];

        $post_id = wp_insert_post($post_data);
        if (is_wp_error($post_id)) {
            throw new Exception(esc_html__('Failed to create virtual file: ', 'intentdeep-virtual-files') . esc_html($post_id->get_error_message()));
        }

        // Sanitize content
        $content = $this->sanitizeVirtualFileContent($file_data['content'], pathinfo($filename, PATHINFO_EXTENSION));

        // Save metadata
        update_post_meta($post_id, '_vf_filename', $filename);
        update_post_meta($post_id, '_vf_content', $content);
        update_post_meta($post_id, '_vf_mime_type', sanitize_text_field($file_data['mime_type'] ?? 'text/plain'));
        update_post_meta($post_id, '_vf_status', sanitize_text_field($file_data['status_meta'] ?? 'active'));
        update_post_meta($post_id, '_vf_modified', current_time('mysql'));

        // Schedule rewrite rules flush
        $this->scheduleRewriteFlush();
    }
}
