<?php
// ---- Configuration ----
define('MYTHEME_UPDATE_MANIFEST', 'https://kvintti.terssi.fi/sanaprassi/manifest.json');
define('MYTHEME_SLUG', wp_get_theme()->get_stylesheet()); // theme directory name

/**
 * Fetch and cache remote manifest.
 */
function mytheme_fetch_remote_manifest() {
    $cache_key = 'mytheme_update_manifest_' . md5(MYTHEME_UPDATE_MANIFEST);
    $cached    = get_site_transient($cache_key);
    if ($cached !== false) {
        return $cached;
    }

    $args = array(
        'timeout' => 10,
        'headers' => array('Accept' => 'application/json'),
        'user-agent' => 'mytheme-update/' . wp_get_theme()->get('Version') . '; ' . home_url('/')
    );
    $resp = wp_remote_get(MYTHEME_UPDATE_MANIFEST, $args);
    if (is_wp_error($resp) || wp_remote_retrieve_response_code($resp) !== 200) {
        return false;
    }
    $body = wp_remote_retrieve_body($resp);
    $json = json_decode($body, true);
    if (!is_array($json) || empty($json['version'])) {
        return false;
    }

    // Cache for 6 hours (Core checks ~12h).
    set_site_transient($cache_key, $json, 6 * HOUR_IN_SECONDS);
    return $json;
}

/**
 * Modern path (WP 6.1+): Use Update URI hostname hook to provide update info.
 * Update URI must be set in style.css to your domain.
 */
function mytheme_register_update_uri_filter() {
    $update_uri = wp_get_theme()->get('UpdateURI');
    if (!$update_uri) {
        return;
    }
    $host = parse_url($update_uri, PHP_URL_HOST);
    if (!$host) {
        // Allow non-URL identifiers like "my-custom-hostname"
        $host = $update_uri;
    }

    add_filter("update_themes_{$host}", function($update, $theme_data, $theme_stylesheet) {
        // Only respond for this theme.
        if ($theme_stylesheet !== MYTHEME_SLUG) {
            return $update;
        }

        $remote = mytheme_fetch_remote_manifest();
        if (!$remote) {
            return $update; // No change.
        }

        $installed = wp_get_theme(MYTHEME_SLUG)->get('Version');
        // Build the update array Core expects. It will convert "version" => "new_version".
        $payload = array(
            'id'           => $theme_data['UpdateURI'],             // must stay constant
            'theme'        => MYTHEME_SLUG,
            'version'      => (string) $remote['version'],
            'new_version'  => (string) $remote['version'],          // Core will derive if missing; set for clarity
            'url'          => isset($remote['url']) ? $remote['url'] : '',
            'package'      => isset($remote['package']) ? $remote['package'] : '',
            'tested'       => isset($remote['tested']) ? $remote['tested'] : '',
            'requires_php' => isset($remote['requires_php']) ? $remote['requires_php'] : '',
            // 'requires' is used in the UI for WP compatibility.
            'requires'     => isset($remote['requires']) ? $remote['requires'] : '',
        );

        // Core will place in response/no_update based on version compare.
        return $payload;
    }, 10, 3);
}
mytheme_register_update_uri_filter();

/**
 * Back-compat (pre-6.1 or if Update URI not set): inject into the update_themes transient.
 * Also ensures "no_update" is filled so the auto-updates UI works correctly.
 */
function mytheme_inject_update_via_transient($transient) {
    if (!is_object($transient)) {
        $transient = new stdClass();
    }
    if (empty($transient->checked)) {
        return $transient;
    }

    $remote = mytheme_fetch_remote_manifest();
    $installed = wp_get_theme(MYTHEME_SLUG)->get('Version');

    $item = array(
        'theme'        => MYTHEME_SLUG,
        'new_version'  => $remote ? (string) $remote['version'] : (string) $installed,
        'url'          => $remote && !empty($remote['url']) ? $remote['url'] : '',
        'package'      => $remote && !empty($remote['package']) ? $remote['package'] : '',
        'requires'     => $remote && !empty($remote['requires']) ? $remote['requires'] : '',
        'requires_php' => $remote && !empty($remote['requires_php']) ? $remote['requires_php'] : '',
    );

    if ($remote && version_compare($installed, $remote['version'], '<')) {
        // Offer an update.
        $transient->response[ MYTHEME_SLUG ] = $item;
        unset($transient->no_update[ MYTHEME_SLUG ]);
    } else {
        // No update, but fill no_update to make auto-updates UI behave.
        if (!isset($transient->no_update)) {
            $transient->no_update = array();
        }
        $transient->no_update[ MYTHEME_SLUG ] = $item;
        unset($transient->response[ MYTHEME_SLUG ]);
    }

    return $transient;
}
add_filter('pre_set_site_transient_update_themes', 'mytheme_inject_update_via_transient');

/**
 * Optional: If your ZIP top folder is not exactly MYTHEME_SLUG,
 * rename the unpacked folder during installation to avoid folder mismatches.
 */
/* 
function mytheme_rename_package_folder($source, $remote_source, $upgrader, $hook_extra) {
    if (empty($hook_extra['theme'])) {
        return $source; // Not a theme update.
    }

    // Handle string or array for 'theme'.
    $targets = (array) $hook_extra['theme'];
    if (!in_array(MYTHEME_SLUG, $targets, true)) {
        return $source;
    }

    global $wp_filesystem;
    $desired = trailingslashit(dirname($source)) . MYTHEME_SLUG . '/';

    // If the folder name already matches, nothing to do.
    if (trailingslashit($source) === $desired) {
        return $source;
    }

    // Rename/move the extracted folder to the desired name.
    if ($wp_filesystem->move($source, $desired, true)) {
        return $desired;
    }

    // If move fails, return original to allow Core to handle/rollback.
    return $source;
}
add_filter('upgrader_source_selection', 'mytheme_rename_package_folder', 10, 4); */