<?php
defined('ABSPATH') || die("Can't access directly");

/**
 * Images folder migration
 * Images folder path changed. This function moves the images folder to the new location
 * OLD: /images/
 * NEW: /wp-content/uploads/images/
 */

add_action('wp_loaded', 'arcade_images_folder_migration');
function arcade_images_folder_migration()
{
    // Define old and new directories
    $old_images_dir = ABSPATH . 'images/';
    $new_images_dir = trailingslashit(wp_upload_dir()['basedir']) . 'images/'; // Get new folder path using wp_upload_dir()

    // Check if the old folder exists
    if (!file_exists($old_images_dir)) {
        return;
    }

    // Create the new folder if it doesn't exist
    if (!file_exists($new_images_dir)) {
        wp_mkdir_p($new_images_dir); // Create new directory using WordPress function
    }

    // Initialize WP_Filesystem
    global $wp_filesystem;
    if (!isset($wp_filesystem)) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem(); // Initialize WordPress filesystem
    }

    // Copy files from the old folder to the new folder (including subdirectories)
    $old_files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($old_images_dir), RecursiveIteratorIterator::SELF_FIRST);
    foreach ($old_files as $file) {
        if ($file->isFile()) {
            $source = $file->getPathname();
            $destination = str_replace($old_images_dir, $new_images_dir, $source);
            $wp_filesystem->copy($source, $destination, true);
            if ( file_exists($destination)) unlink($source); // Delete source file after successful copy
        }
    }

    // Function to remove empty directories recursively
    arcade_removeEmptyDirectories($old_images_dir);

    // Remove the old folder if it's empty
    if (count(glob($old_images_dir . '*')) === 0) {
        rmdir($old_images_dir);
    }
}

function arcade_removeEmptyDirectories($dir)
{
    $files = glob($dir . '/*');
    if ($files === false) return;
    foreach ($files as $file) {
        if (is_dir($file)) {
            arcade_removeEmptyDirectories($file);
            if (count(glob($file . '/*')) === 0) {
                rmdir($file);
            }
        }
    }
}
