<?php

add_filter('pre_set_site_transient_update_plugins', 'connect_check_for_update');
add_filter('plugins_api', 'connect_plugin_info', 10, 3);

/**
 * Check for plugin updates by querying the custom update server.
 */
function connect_check_for_update($transient)
{
    if (empty($transient->checked)) {
        return $transient;
    }

    $remote = wp_remote_get(SC_UPDATE_API_BASE);

    if (is_wp_error($remote) || wp_remote_retrieve_response_code($remote) !== 200) {
        return $transient;
    }

    $plugin_data = json_decode(wp_remote_retrieve_body($remote));
    $plugin_file = SC_PLUGIN_FILE;

    if (version_compare($plugin_data->version, SC_PLUGIN_VERSION, '>')) {
        $transient->response[$plugin_file] = (object) [
          'slug'        => $plugin_data->slug,
          'plugin'      => $plugin_file,
          'new_version' => $plugin_data->version,
          'url'         => $plugin_data->homepage,
          'package'     => $plugin_data->download_url,
        ];
    }

    return $transient;
}

/**
 * Provide plugin information (e.g., for "View Details" in the updater).
 */
function connect_plugin_info($result, $action, $args)
{
    if ($action !== 'plugin_information' || $args->slug !== '121-connect') {
        return $result;
    }

    $remote = wp_remote_get(SC_UPDATE_API_BASE);
    if (is_wp_error($remote) || wp_remote_retrieve_response_code($remote) !== 200) {
        return $result;
    }

    $plugin_data = json_decode(wp_remote_retrieve_body($remote));

    return (object) [
      'name'          => $plugin_data->name,
      'slug'          => $plugin_data->slug,
      'version'       => $plugin_data->version,
      'author'        => $plugin_data->author,
      'homepage'      => $plugin_data->homepage,
      'download_link' => $plugin_data->download_url,
      'sections'      => (array) $plugin_data->sections,
    ];
}
