<?php
namespace NeoDrawFull\NeoPluginUpdate; if (!defined("ABSPATH")) { die("neoWP direct access not allowed"); }










\NeoDrawFull\NeoGlobal\add_filter_hook("site_transient_update_plugins:max", function ($transient) {
    if (\NeoDrawFull\NeoGlobal\is_playground()) { return $transient; }

    if ($transient === false) {
        $transient = (object) [
            "response"  => [],
            "no_update" => [],
            "checked"   => [],
        ];
    }
    [, $plugin_icon_list] = \NeoDrawFull\NeoGlobal\update_and_get_plugin_list_and_icons();

    foreach (\NeoDrawFull\NeoEntrypoint\get_neo_active_plugins() as $plugin) {
        if (in_array($plugin["edition"], ["wporg", "dev"])) { continue; }

        $plugin_file = \NeoDrawFull\NeoGlobal\get_plugin_entry_path_relative($plugin["slug"]);

        if (isset($transient->response[$plugin_file]))  { unset($transient->response[$plugin_file]); }
        if (isset($transient->no_update[$plugin_file])) { unset($transient->no_update[$plugin_file]); }
        if (isset($transient->checked[$plugin_file]))   { unset($transient->checked[$plugin_file]); }

        $info_url = \NeoDrawFull\NeoGlobal\get_plugin_info_json_file_url($plugin["slug"], $plugin["edition"]);
        $plugin_info = (object) [
            "slug"        => $plugin["slug"] . "," . $plugin["edition"],
            "plugin"      => $plugin_file,
            "new_version" => \NeoDrawFull\NeoGlobal\plugin_version(),
            "tested"      => "",
            "url"         => "https://" . \NeoDrawFull\NeoGlobal\option__neo_wp_com() . "/?ref=plugin-update",
            "package"     => "",
        ];
        try {

            static $curl_cache = [];
            if (isset($curl_cache[$info_url])) {
                $new_plugin_info = $curl_cache[$info_url];
                if ($new_plugin_info === "#cachedNeoPluginUpdateError") { throw new \Exception("#cachedNeoPluginUpdateError"); }
            } else {

                $curl_cache_file = \NeoDrawFull\NeoGlobal\cache_path("neo-plugin-update") . "/" . \NeoDrawFull\NeoGlobal\get_bundle_slug($plugin["slug"], $plugin["edition"]) . ".json";
                if (\NeoDrawFull\NeoGlobal\is_cache_file_outdated($curl_cache_file, (12) * 60 * 60)) { \NeoDrawFull\NeoGlobal\fs_unlink($curl_cache_file); }
                if (\NeoDrawFull\NeoGlobal\fs_file_exists($curl_cache_file)) { $response = \NeoDrawFull\NeoGlobal\fs_file_get_contents($curl_cache_file); }
                else {

                    $response = \NeoDrawFull\NeoGlobal\curl_request($info_url, timeout: 10);
                    \NeoDrawFull\NeoGlobal\fs_file_put_contents($curl_cache_file, $response);
                }
                $new_plugin_info = json_decode($response);
                if (!is_object($new_plugin_info)) { \NeoDrawFull\NeoGlobal\global_warn_with_module_name("neo-plugin-update", "Plugin update error: Invalid JSON format for $info_url"); continue; }
                $curl_cache[$info_url] = $new_plugin_info;
            }

            $skip_update = false;
            if (str_starts_with($plugin_info->slug, "neo-media,")) {
                [$license_key, $interface_ok] = \NeoDrawFull\NeoGlobal\call_interface_func_implemented('\NeoDrawFull\NeoFreemius\interface_freemius_license_secret_key_20260211')();
                $license_key ??= \NeoDrawFull\NeoGlobal\val("neo_global__debug_license_key");
                $new_plugin_info->download_link = \NeoDrawFull\NeoGlobal\add_query_param($new_plugin_info->download_link, "license-key", $license_key);
                $new_plugin_info->download_link = \NeoDrawFull\NeoGlobal\add_query_param($new_plugin_info->download_link, "error-on-invalid-license-key", "true");
            }

            $plugin_info->new_version = $new_plugin_info->version;
            $plugin_info->package     = $new_plugin_info->download_link;
            $plugin_info->tested      = $new_plugin_info->tested_with_patch ?? "";
            $plugin_icon_url = $plugin_icon_list[$plugin["slug"]]["theme-neo"]["icon"] ?? $plugin_icon_list["neo-plugins"]["theme-neo"]["icon"] ?? null;
            if ($plugin_icon_url) {
                $plugin_info->icons = [
                    "1x" => $plugin_icon_url . "?res=1x",
                    "2x" => $plugin_icon_url . "?res=2x",
                ];
            }
            [$force_offer_update, $interface_ok] = \NeoDrawFull\NeoGlobal\call_interface_func_implemented('\NeoDrawFull\NeoDebug\interface_neo_debug_force_offer_update_enabled_20260224')(); if (!$interface_ok) { $force_offer_update = false; }
            if ((version_compare($plugin_info->new_version, \NeoDrawFull\NeoGlobal\plugin_version_without_live_timestamp($plugin["version"]), ">") && !$skip_update) || $force_offer_update) { $transient->response[$plugin_file]  = $plugin_info; }
            else                                                                                                                                                                 { $transient->no_update[$plugin_file] = $plugin_info; }
        } catch (\Throwable $e) {
            static $already_warned = false; if (!$already_warned) { $already_warned = true; \NeoDrawFull\NeoGlobal\global_warn_with_module_name("neo-plugin-update", "Plugin update error for $plugin_file (and maybe others): " . $e->getMessage()); }
            $curl_cache[$info_url] = "#cachedNeoPluginUpdateError";
            $transient->no_update[$plugin_file] = $plugin_info;
        } finally {
            $transient->checked[$plugin_file] = $plugin["version"];
        }
    }
    return $transient;
});


\NeoDrawFull\NeoGlobal\add_filter_hook("plugins_api", function ($result, $action, $args) {
    if ($action !== "plugin_information" || empty($args->slug)) { return $result; }
    if (!str_starts_with($args->slug, "neo-")) { return $result; }
    if (!str_contains($args->slug, ",")) { return $result; }

    try {
        $response = \NeoDrawFull\NeoGlobal\curl_request(\NeoDrawFull\NeoGlobal\get_plugin_info_json_file_url(explode(",", $args->slug)[0], explode(",", $args->slug)[1]), timeout: 10);
        $plugin_info = \NeoDrawFull\NeoGlobal\json_decode_better($response);
        return (object)[
            "name"           => $plugin_info["name"],
            "slug"           => $args->slug,
            "version"        => $plugin_info["version"]        ?? "",
            "author"         => $plugin_info["author"]         ?? "",
            "author_profile" => $plugin_info["author_profile"] ?? "",
            "requires"       => $plugin_info["requires"]       ?? "",
            "requires_php"   => $plugin_info["requires_php"]   ?? "",
            "tested"         => $plugin_info["tested"]         ?? "",
            "last_updated"   => $plugin_info["last_updated"]   ?? "",
            "sections"       => array_intersect_key(array_change_key_case((array)($plugin_info["sections"] ?? []), CASE_LOWER), array_flip(["description", "installation", "faq", "changelog", "screenshots"])),
            "banners"        => (array)($plugin_info["banner"] ?? []),
            "download_link"  => $plugin_info["download_link"]  ?? "",
        ];
    } catch (\Throwable $e) {
        \NeoDrawFull\NeoGlobal\global_warn_with_module_name("neo-plugin-update", "Plugin info error: " . $e->getMessage());
        return $result;
    }
});



\NeoDrawFull\NeoGlobal\add_action_hook("current_screen", function () {
    if (get_current_screen()->id !== "plugins") { return; }

    $coupon_code = "RES_N20_UPD"; $coupon_url = "https://" . \NeoDrawFull\NeoGlobal\option__neo_wp_com() . "/pricing/?x=RES_N20_UPD&ref=wp-backend-update#pricing-table";
    \NeoDrawFull\NeoGlobal\enqueue_js_variable_backend("neoPluginUpdateExitCouponCode", $coupon_code);
    \NeoDrawFull\NeoGlobal\enqueue_js_variable_backend("neoPluginUpdateExitCouponUrl",  $coupon_url);
    \NeoDrawFull\NeoGlobal\enqueue_js("neo-plugin-update--payment-required-popup.js");
});



\NeoDrawFull\NeoGlobal\add_action_hook("neo_init", function () {
    $force_check_updates = function () { \NeoDrawFull\NeoGlobal\delete_all(\NeoDrawFull\NeoGlobal\cache_path("neo-plugin-update")); delete_site_transient("update_plugins"); };
    \NeoDrawFull\NeoGlobal\call_interface_func_implemented('\NeoDrawFull\NeoReset\interface_register_neo_reset_action_20260410')(
        id: "neo-plugin-update--force-update-check", button_text: \NeoDrawFull\NeoGlobal\neo__("Check for updates now", "Jetzt auf Updates prüfen"), confirm_title: \NeoDrawFull\NeoGlobal\neo__("Check for updates?", "Auf Updates prüfen?"), confirm_text: \NeoDrawFull\NeoGlobal\neo__("This will manually check for new neoPlugin updates. If new updates are available, they will be shown on the plugin page.", "Es wird manuell geprüft, ob neue neoPlugin-Updates verfügbar sind. Bei neuen Updates werden diese auf der Plugin-Seite angezeigt."),
        action_callback: $force_check_updates
    );
});
