<?php

add_filter('site_transient_update_themes', 'wrockmetro_update_themes');

function wrockmetro_update_themes($transient) {

    // let's get the theme directory name
    // it will be "wrockmetro-theme"
    $stylesheet = get_template();

    // now let's get the theme version
    // but maybe it is better to hardcode it in a constant
    $theme = wp_get_theme();
    $version = $theme->get('Version');

    if (false == $remote = get_transient('wrockmetro-theme-update' . $version)) {
        // connect to a remote server where the update information is stored
        $remote = wp_remote_get(
            'https://cdn.insertcart.com/wrockmetro/info.json',
            array(
                'timeout' => 10,
                'headers' => array(
                    'Accept' => 'application/json'
                )
            )
        );

        // do nothing if errors
        if (
            is_wp_error($remote)
            || 200 !== wp_remote_retrieve_response_code($remote)
            || empty(wp_remote_retrieve_body($remote))
        ) {
            return $transient;
        }

        // encode the response body
        $remote = json_decode(wp_remote_retrieve_body($remote));

        if (!$remote) {
            return $transient; // who knows, maybe JSON is not valid
        }
    }

    // Check if the properties exist before accessing them
    $requires = property_exists($remote, 'requires') ? $remote->requires : '';
    $requires_php = property_exists($remote, 'requires_php') ? $remote->requires_php : '';

    $data = array(
        'theme' => $stylesheet,
        'url' => property_exists($remote, 'details_url') ? $remote->details_url : '',
        'requires' => $requires,
        'requires_php' => $requires_php,
        'new_version' => property_exists($remote, 'version') ? $remote->version : '',
        'package' => property_exists($remote, 'download_url') ? $remote->download_url : '',
    );
	$transient = (object) $transient; // Initialize $transient as an object
    // check all the versions now
		if (
		$remote
		&& version_compare($version, $data['new_version'], '<')
		&& version_compare($requires, get_bloginfo('version'), '<')
		&& version_compare($requires_php, PHP_VERSION, '<')
	) {
		$transient->response[$stylesheet] = $data;
	} else {
		$transient->no_update[$stylesheet] = $data;
	}

    return $transient;
}
