<?php

namespace Lcmigrator\LcMigrator\ImporterV2;
use Lcmigrator\LcMigrator\Logger\Logger;


class RestoreFiles {
    public static function execute( &$params ) {
        $logger = Logger::getInstance();
        $logger->info("Restoring files...");
        $file = $params['extract_path'];

        $logger->info("Restoring files from: {$file}");

        $current_wp_content = WP_CONTENT_DIR;
        $backup_wp_content = $params['extract_path'] . 'wp-content/';
    
        // Priority folders that need special handling
        $priority_folders = [
            'plugins',
            'uploads'
        ];

        // Protected folders that should not be replaced
        $protected_folders = [
            'lc-migrator',
            'revex-wordpress-lc-easy-migrator',
        ];
    
        if (is_dir($backup_wp_content)) {
            $backup_items = array_diff(scandir($backup_wp_content), ['.', '..']);
            
            foreach ($backup_items as $item) {
                // Skip protected folders
                if (in_array($item, $protected_folders)) {
                    continue;
                }

                $source_path = rtrim($backup_wp_content, '/') . '/' . $item;
                $destination_path = rtrim($current_wp_content, '/') . '/' . $item;
    
                if (in_array($item, $priority_folders)) {
                    // For priority folders, merge contents instead of replacing
                    if (is_dir($source_path) && is_dir($destination_path)) {
                        self::merge_directory($source_path, $destination_path);
                    }
                } else {
                    // For non-priority items, replace completely
                    if (file_exists($destination_path)) {
                        if (is_dir($destination_path)) {
                            self::delete_directory($destination_path);
                        } else {
                            unlink($destination_path);
                        }
                    }
    
                    if (is_dir($source_path)) {
                        self::copy_directory($source_path, $destination_path);
                    } else {
                        copy($source_path, $destination_path);
                    }
                }
            }
        }

        $logger->info("Files restored successfully");
        return $params;
    }
    
    private static function merge_directory($source, $destination) 
    {
        if (!file_exists($destination)) {
            wp_mkdir_p($destination);
        }
    
        $files = array_diff(scandir($source), ['.', '..']);
        
        foreach ($files as $file) {
            $src_file = rtrim($source, '/') . '/' . $file;
            $dest_file = rtrim($destination, '/') . '/' . $file;
    
            if (is_dir($src_file)) {
                // Recursively merge subdirectories
                self::merge_directory($src_file, $dest_file);
            } else {
                // For files, only copy if they don't exist or are different
                if (!file_exists($dest_file) || md5_file($src_file) !== md5_file($dest_file)) {
                    copy($src_file, $dest_file);
                }
            }
        }
    }
    
    private static function copy_directory($source, $destination) 
    {
        if (!file_exists($destination)) {
            wp_mkdir_p($destination);
        }
    
        $files = array_diff(scandir($source), ['.', '..']);
        
        foreach ($files as $file) {
            $src_file = rtrim($source, '/') . '/' . $file;
            $dest_file = rtrim($destination, '/') . '/' . $file;
    
            if (is_dir($src_file)) {
                self::copy_directory($src_file, $dest_file);
            } else {
                copy($src_file, $dest_file);
            }
        }
    }

    private static function delete_directory($path)
    {
        if (!is_dir($path)) return;

        $files = array_diff(scandir($path), ['.', '..']);

        foreach ($files as $file) {
            $file_path = $path . '/' . $file;

            // Skip certain critical directories
            if (in_array($file, ['plugins', 'uploads', 'languages'])) continue;

            if (is_dir($file_path)) {
                self::delete_directory($file_path);
            } else {
                if (file_exists($file_path)) {
                    @unlink($file_path);
                }
            }
        }

        // Only remove directory if not a critical system folder and empty
        $critical_dirs = ['plugins', 'uploads', 'languages'];
        if (!in_array(basename($path), $critical_dirs)) {
            // Check if directory is empty before trying to remove
            $remaining_files = array_diff(scandir($path), ['.', '..']);
            if (empty($remaining_files)) {
                @rmdir($path);
            }
        }
    }

    
}