<?php
$api_url = 'https://www.wpcargo.com/repository/theme/wpcargo-pro/';
// This function has been deprecated
if(function_exists('get_theme_data') && !function_exists('wp_get_theme')){
	$theme_data = get_theme_data( TEMPLATEPATH . '/style.css');
	$theme_version = wpkeyvalue( $theme_data, 'Version' );
}
$theme_base = get_option('template');
if(function_exists('wp_get_theme')){
    $theme_data 	= wp_get_theme(get_option('template'));
    $theme_version 	= $theme_data->get('Version'); 
}    
add_filter('pre_set_site_transient_update_themes', 'wpctp_pre_set_site_transient_update_themes');
function wpctp_pre_set_site_transient_update_themes($checked_data) {
	global $wp_version, $theme_version, $theme_base, $api_url;
	$request = array(
		'slug' => $theme_base,
		'version' => $theme_version 
	);
	$send_for_check = array(
		'body' => array(
			'action' => 'theme_update', 
			'request' => serialize($request),
			'api-key' => md5(get_bloginfo('url'))
		),
		'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
	);
	$raw_response = wp_remote_post($api_url, $send_for_check);
	$response = wpkeyvalue( $raw_response, 'response' );
	$code = wpkeyvalue( $response, 'code' );
	if ( ! is_wp_error( $raw_response ) && ( $code == 200 ) && wpifisset( $raw_response, 'body' ) ){
		$response = unserialize( $raw_response['body'] );
	}
	if ( ! empty( $response ) && ( $theme_version < wpkeyvalue( $response, 'new_version' ) ) ){
		$checked_data->response[$theme_base] = $response;
	}else if( isset( $checked_data->response[$theme_base] ) ){
		unset( $checked_data->response[$theme_base] );
	}
	return $checked_data;
}
if ( is_admin() ){
	$current = get_transient('update_themes');
}
add_action( 'load-update-core.php', 'wpctp_clear_update_transient' );
add_action( 'load-themes.php', 'wpctp_clear_update_transient' );
function wpctp_clear_update_transient() {
	$site_transient_update_themes = get_option( '_site_transient_update_themes' );
	$checked = wpstdclass( $site_transient_update_themes, 'checked' );
	$response = wpstdclass( $site_transient_update_themes, 'response' );
	$wpcargopro = wpkeyvalue( $response, 'wpcargo-pro' );
	$new_version = wpkeyvalue( $wpcargopro, 'new_version' );
	if( ! $checked ){
		return;
	}
	if( ! wpifisset( $checked, 'wpcargo-pro' ) ){
		return;
	}
	if( wpifisset( $checked, 'wpcargo-pro' ) ){
		if( wpkeyvalue( $checked, 'wpcargo-pro' ) >= $new_version ){
			unset( $site_transient_update_themes->checked['wpcargo-pro'] );
			unset( $site_transient_update_themes->response['wpcargo-pro'] );
			update_option( '_site_transient_update_themes', $site_transient_update_themes );
		}		
	}
}