<?php
function book_author_blog_import_widgets_from_json_url($file_path = '') {
    // Default file path if none provided
    if (empty($file_path)) {
        $file_path = wp_upload_dir()['basedir'] . '/widgets-export.json';
    }

    // Check if file exists
    if (!file_exists($file_path)) {
        return new WP_Error('file_not_found', 'The widget export file could not be found.');
    }

    // Read and decode JSON file
    $json_data = file_get_contents($file_path);
    $import_data = json_decode($json_data, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return new WP_Error('json_error', 'Error decoding JSON file: ' . json_last_error_msg());
    }

    // Get current widget settings
    $sidebars_widgets = get_option('sidebars_widgets', []);

    // Process each sidebar
    foreach ($import_data as $sidebar => $widgets) {
        // Skip if sidebar is not valid
        if ($sidebar === 'wp_inactive_widgets') {
            $sidebars_widgets[$sidebar] = array_keys($widgets);
            continue;
        }

        $sidebar_widgets = [];
        foreach ($widgets as $widget_id => $widget_data) {
            // Extract base widget ID (e.g., rs_info_box_widget from rs_info_box_widget-2)
            $widget_base_id = preg_replace('/-\d+$/', '', $widget_id);

            // Get existing widget data or initialize it
            $existing_widget_data = get_option('widget_' . $widget_base_id, []);

            // Merge or update the widget instance data
            foreach ($widget_data as $instance_id => $instance_settings) {
                if ($instance_id === '_multiwidget') {
                    $existing_widget_data['_multiwidget'] = $instance_settings;
                } else {
                    $existing_widget_data[$instance_id] = $instance_settings;
                }
            }

            // Update the widget settings in the database
            update_option('widget_' . $widget_base_id, $existing_widget_data);

            // Add widget ID to the sidebar
            $sidebar_widgets[] = $widget_id;
        }

        // Assign widgets to the sidebar
        $sidebars_widgets[$sidebar] = $sidebar_widgets;
    }

    // Update the sidebars_widgets option
    update_option('sidebars_widgets', $sidebars_widgets);

    return true;
}


// Import Customizer Settings
// function book_author_blog_import_customizer_settings_from_json_url($json_file_path) {
//     if (!file_exists($json_file_path)) {
//         return false;
//     }

//     $json_data = file_get_contents($json_file_path);
//     $customizer_data = json_decode($json_data, true);

//     if (!is_array($customizer_data)) {
//         return false;
//     }

//     foreach ($customizer_data as $key => $value) {
//         set_theme_mod($key, $value);
//     }

//     return true;
// }

function book_author_blog_import_customizer_settings_from_json_url($json_file_path = '') {
   if (!file_exists($json_file_path)) {
        return false;
    }

    $json_data = file_get_contents($json_file_path);
    $customizer_data = json_decode($json_data, true);

    if (!is_array($customizer_data)) {
        return false;
    }

    foreach ($customizer_data as $key => $value) {
        // Handle logo settings with attachment ID validation and URL fallback
        if (in_array($key, ['custom_logo', 'footer_logo'])) {
            if (attachment_id_exists($value)) {
                set_theme_mod($key, $value);
            } else {
                // Fallback to URL if provided
                $image_url_key = $key . '_url';
                if (isset($customizer_data[$image_url_key]) && $new_id = import_image_from_url($customizer_data[$image_url_key])) {
                    set_theme_mod($key, $new_id);
                } else {
                    error_log("Attachment ID {$value} for '{$key}' not found and no valid URL provided.");
                    remove_theme_mod($key);
                }
            }
        } else {
            set_theme_mod($key, $value);
        }
    }

    return true;
}

// Helper function to check if an attachment ID exists
function attachment_id_exists($attachment_id) {
    return get_post($attachment_id) && 'attachment' === get_post_type($attachment_id);
}

function import_image_from_url($url) {
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $attachment_id = media_sideload_image($url, 0, null, 'id');
    return is_wp_error($attachment_id) ? false : $attachment_id;
}