<?php
defined('ABSPATH') || exit;

// ═══════════════════════════════════════════
// Update Checker
// ═══════════════════════════════════════════
add_filter('pre_set_site_transient_update_plugins', 'iv1_wp_tools_check_for_update');
function iv1_wp_tools_check_for_update($transient) {
    if (empty($transient->checked)) {
        return $transient;
    }

    $plugin_file = defined('IV1WPT_PLUGIN_FILE')
        ? plugin_basename(IV1WPT_PLUGIN_FILE)
        : 'iv1-wp-tools/iv1-wp-tools.php';

    $response = wp_remote_get(IV1_WP_TOOLS_UPDATE_JSON, [
        'timeout' => 10,
    ]);

    if (is_wp_error($response)) {
        return $transient;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);

    if (empty($data->version) || empty($data->download_url)) {
        return $transient;
    }

    $current_version = defined('IV1WPT_VERSION') ? IV1WPT_VERSION : '1.0.0';

    if (version_compare($current_version, $data->version, '<')) {
        $transient->response[$plugin_file] = (object) [
            'id'           => $plugin_file,
            'slug'         => $data->slug ?? 'iv1-wp-tools',
            'plugin'       => $plugin_file,
            'new_version'  => $data->version,
            'package'      => $data->download_url,
            'url'          => $data->homepage ?? 'https://www.intellivision1.de',
            'tested'       => $data->tested ?? '6.9.4',
            'requires'     => $data->requires ?? '5.6',
            'requires_php' => $data->requires_php ?? '7.4',
        ];
    } else {
        unset($transient->response[$plugin_file]);
    }

    return $transient;
}

add_action('upgrader_process_complete', 'iv1_wp_tools_clear_update_cache_after_update', 10, 2);
function iv1_wp_tools_clear_update_cache_after_update($upgrader, $hook_extra) {
    if (empty($hook_extra['type']) || $hook_extra['type'] !== 'plugin') {
        return;
    }

    if (empty($hook_extra['action']) || $hook_extra['action'] !== 'update') {
        return;
    }

    $plugin_file = defined('IV1WPT_PLUGIN_FILE')
        ? plugin_basename(IV1WPT_PLUGIN_FILE)
        : 'iv1-wp-tools/iv1-wp-tools.php';

    if (!empty($hook_extra['plugins']) && in_array($plugin_file, $hook_extra['plugins'], true)) {
        delete_site_transient('update_plugins');
    }
}