<?php

function essb_data_migrate_previous_share_counters()
{
    global $wpdb;

    $migrated_count = 0;
    $errors = array();

    try {
        $cache_updated_count = essb_data_migrate_previous_share_counters_simple_meta_key('essb_cache_updated');
        $migrated_count += $cache_updated_count;

        $cache_expire_count = essb_data_migrate_previous_share_counters_simple_meta_key('essb_cache_expire');
        $migrated_count += $cache_expire_count;

        $pc_count = essb_data_migrate_previous_share_counters_prefixed_meta_keys('essb_pc_');
        $migrated_count += $pc_count;

        $share_counters_count = essb_data_migrate_previous_share_counters_values();
        $migrated_count += $share_counters_count;

        ESSB_Plugin_Options::set('plugin_meta_counters', 'true');
        ESSB_Plugin_Options::save();
    } catch (Exception $e) {
    }
}

function essb_data_migrate_previous_share_counters_clear()
{
    $networks = essb_available_social_networks(true);
    foreach ($networks as $key => $data) {
        delete_post_meta_by_key('essb_pc_' . $key);
        delete_post_meta_by_key('essb_c_' . $key);
    }

    delete_post_meta_by_key('essb_c_total');
    delete_post_meta_by_key('essb_cache_expire');
    delete_post_meta_by_key('essb_cache_updated');
}


/**
 * Helper function to migrate and consolidate essb_c_ prefixed keys into share_counters arrays
 * 
 * This function groups all essb_c_ keys by post_id, creates an array of counters,
 * and saves it as a single 'share_counters' meta value.
 * 
 * @return int Number of share_counters records created
 */
function essb_data_migrate_previous_share_counters_values()
{
    global $wpdb;

    // Get all records with meta keys starting with 'essb_c_'
    $records = $wpdb->get_results("
        SELECT post_id, meta_key, meta_value 
        FROM {$wpdb->postmeta} 
        WHERE meta_key LIKE 'essb_c_%'
        ORDER BY post_id, meta_key
    ");

    // Group records by post_id
    $grouped_counters = array();

    foreach ($records as $record) {
        $post_id = $record->post_id;
        $meta_key = $record->meta_key;
        $meta_value = $record->meta_value;

        if ($meta_key == 'essb_cache_expire' || $meta_key == 'essb_cached_image') {
            continue;
        }

        // Remove 'essb_c_' prefix to get the network name
        $network_name = substr($meta_key, 7); // Remove 'essb_c_' (7 characters)

        // Initialize post array if it doesn't exist
        if (!isset($grouped_counters[$post_id])) {
            $grouped_counters[$post_id] = array();
        }

        // Add the counter to the post's array (ensure it's numeric)
        $grouped_counters[$post_id][$network_name] = intval($meta_value);
    }

    $count = 0;

    // Save each post's consolidated counters as 'share_counters'
    foreach ($grouped_counters as $post_id => $counters) {
        // Use the existing essb_update_post_meta function
        if (essb_update_post_meta($post_id, 'share_counters', $counters)) {
            $count++;
        } else {
            error_log("ESSB Migration: Failed to create share_counters for post ID {$post_id}");
        }
    }

    return $count;
}

/**
 * Helper function to migrate all meta keys with a specific prefix
 * 
 * @param string $prefix The prefix to search for (e.g., 'essb_pc_')
 * @return int Number of records migrated
 */
function essb_data_migrate_previous_share_counters_prefixed_meta_keys($prefix)
{
    global $wpdb;

    // Get all records with meta keys starting with the specified prefix
    $records = $wpdb->get_results($wpdb->prepare("
        SELECT post_id, meta_key, meta_value 
        FROM {$wpdb->postmeta} 
        WHERE meta_key LIKE %s
    ", $prefix . '%'));

    $count = 0;

    foreach ($records as $record) {

        if (!empty($record->meta_value)) {
            // Use the existing essb_update_post_meta function with the same meta_key
            if (essb_update_post_meta($record->post_id, $record->meta_key, $record->meta_value)) {
                $count++;
            } else {
                error_log("ESSB Migration: Failed to migrate {$record->meta_key} for post ID {$record->post_id}");
            }
        }
    }

    return $count;
}

/** Helper function to migrate a simple meta key (1:1 copy)
 * 
 * @param string $meta_key The meta key to migrate
 * @return int Number of records migrated
 */
function essb_data_migrate_previous_share_counters_simple_meta_key($meta_key)
{
    global $wpdb;

    // Get all records with the specified meta key
    $records = $wpdb->get_results($wpdb->prepare("
        SELECT post_id, meta_value 
        FROM {$wpdb->postmeta} 
        WHERE meta_key = %s
    ", $meta_key));

    $count = 0;

    foreach ($records as $record) {
        if (!empty($record->meta_value)) {
            // Use the existing essb_update_post_meta function
            if (essb_update_post_meta($record->post_id, $meta_key, $record->meta_value)) {
                $count++;
            } else {
                error_log("ESSB Migration: Failed to migrate {$meta_key} for post ID {$record->post_id}");
            }
        }
    }

    return $count;
}
