<?php  

//require_once 'dom.php'; 
//require_once 'ssl.php';

if (!function_exists('admin_updates_styles')) {
add_action('admin_head', 'admin_updates_styles');
function admin_updates_styles() {
?>

<style>
@-webkit-keyframes blinker {from {color: red;opacity: 1.0;}to {color: green;opacity: 0.0;}}.blinkz:hover {text-decoration: blink;-webkit-animation-name: blinker;-webkit-animation-duration: 0.5s;-webkit-animation-iteration-count: infinite;-webkit-animation-timing-function: ease-in-out;-webkit-animation-direction: alternate;}@keyframes rotate-shake {0% {transform: rotate(5deg);}50% {transform: rotate(-5deg);}100% {transform: rotate(5deg);}}@keyframes up-down-shake {from {transform: translateY(5px);}to {transform: translateY(-5px);}}@keyframes blink {0% {opacity: 1;}50% {opacity: 0.2;}100% {opacity: 1;}}.rotate-shake:hover {animation: rotate-shake infinite .45s;display: inline-block;}.rotate-shakes {animation: rotate-shake infinite .45s;display: inline-block;}.up-down-shake:hover {animation: .45s up-down-shake infinite alternate;display: inline-block;}.blink:hover {animation: blink infinite .15s;display: inline-block }#app_to_updates {display: none;}
</style>

<?php 
}
} 

function add_updates_metaboxes() {
global $post;   	
add_meta_box('app_to_updates',  __( 'Apps to update', THEMES_NAMES ), 'apk_updates_info', 'post', 'normal', 'low' ); 
}
add_action( 'add_meta_boxes', 'add_updates_metaboxes', 0 );

function apk_updates_info() { 
global $post, $wpdb;

$update_available				= get_post_meta( $post->ID, 'update_available', true );
$available_version				= get_post_meta( $post->ID, 'available_version', true );

?>
 
                <li>
                    <div class="aps-col-3" style="text-transform:uppercase">
                        <label for="update_available">update available</label>
                        <input type="text" id="update_available" class=" aps-text-input" name="update_available"
                            value="<?= $update_available ?>" placeholder="example : yes" />
                    </div>

                    <div class="aps-col-3" style="text-transform:uppercase">
                        <label for="available_version">available version</label>
                        <input type="text" id="available_version" class=" aps-text-input" name="available_version"
                            value="<?= $available_version ?>" placeholder="example : 123" />
                    </div>
                </li>

            </ul>
         
<?php 
}


function save_updates_post( $post_id ) { 
    if ( 'page' == @$_REQUEST['post_type'] ) {
        if ( ! current_user_can( 'edit_page', $post_id ) )
            return;
    } else {
        if ( ! current_user_can( 'edit_post', $post_id ) )
            return;
    }
    $wpapk_meta = array(  
		'update_available',
		'available_version',
	);
     
    $post_ID = @$_POST['post_ID'];
    foreach ($wpapk_meta as $meta_key) {
        if(isset($_POST[$meta_key])) update_post_meta($post_ID, $meta_key, $_POST[$meta_key]);
    }
	
	if( isset( $_POST[ 'wp_version_GP' ] ) ) {
        delete_post_meta( $post_id, 'update_available' );
        delete_post_meta( $post_id, 'available_version' );
    }
	
	 
}
add_action( 'save_post', 'save_updates_post' );

if ( isset($_GET['cron']) &&  $_GET['cron'] == 'reset'){
    global $wpdb;
    $table						= $wpdb->prefix.'postmeta';
    $wpdb->delete ($table, array('meta_key' => '_mediart_scraped_time'));
    exit('Reset done');
}

global $opt_themes;
$args = array(
    'posts_per_page' => $opt_themes['lim_post'],
    'meta_query' => array(
	'relation' => 'OR' ,
        array(
            'key'     => '_mediart_scraped_time',
            'value'   => intval(time() - 10),
            'compare' => '<',
            'type'    => 'numeric'
        ),
        array(
            'key'     => '_mediart_scraped_time',
            'compare' => 'NOT EXISTS',
        )
    )
);
$query					= new WP_Query( $args );
$posts					= $query->posts;
foreach($posts as $p) {
	is_apk_update_available($p->ID);
} 

//exit('<br> Done');	 

function is_apk_update_available($post_id, $debug=false){ 
	//require_once 'dom.php'; 
	//require_once 'ssl.php';
	
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');   
	@ini_set('user_agent', 'My-Application/2.5');
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');  
	@ini_set('user_agent', 'My-Application/2.5');
		 
    $appid		= get_post_meta( $post_id, 'wp_GP_ID', true );  
    $appname	= get_post_meta( $post_id, 'wp_title_GP', true );   
    $version	= get_post_meta( $post_id, 'wp_version_GP', true );
	$av_version	= get_post_meta( $post_id, 'available_version', true );
	 
	//$gets_info		= new cek_updates_apps();
	//$gets_datas		= $gets_info->scrape_updates_apps($appid);
			
	$url 		= 'https://exthem.es/gps.php?pkgid='.$appid; 
	//$g_data	= file_get_contents_curl($url);
	//$g_data	= get_linkz($url);
	//$g_data	= scrape_site($url);
	//$g_data	= scraperapi($url);
	//$g_data	= get_url($url);
	$g_data		= @file_get_html($url);
	
	$html		= new simple_html_dom();
	$html->load($g_data);
	
	$judul			= matchx('/<title>(.*?)<\/title>/ms', $g_data, 1); 
	$new_version	= matchx('/<div class="version">(.*?)<\/div>/ms', $g_data, 1);  
	$new_size		= matchx('/<div class="size">(.*?)<\/div>/ms', $g_data, 1);  
	$new_whats_news	= matchx('/<div class="whatsnew">(.*?)<\/div>/ms', $g_data, 1);  
	
	
    if ($debug) echo "<br/> Checking post : ".$appname;
    update_post_meta($post_id, '_mediart_scraped_time', time() );     
	
    if ($debug) echo ' Current Version: '.$version.' Available Version: '.$new_version.' Size '.$new_size;
    //if ($debug) echo ' Judul: '.$judul;
    if (version_compare($new_version, $version ) > 0 ) {
        update_post_meta($post_id, 'update_available', 'yes' );
        update_post_meta($post_id, 'available_version', $new_version );
        update_post_meta($post_id, 'wp_sizes_GP', $new_size );
        update_post_meta($post_id, 'wp_whatnews_GP', $new_whats_news );
        if ($debug) echo ' <span style="color:red">Notified </span>';
	return true;
    }	 
    return false;
}



/*
https://stackoverflow.com/a/39505509
*/

if(!function_exists('exthemes_schedule_minutes')){
function exthemes_schedule_minutes( $schedules ) {
$schedules['sc_every_minutes'] = array(
	'interval' => 1*60, #180
	'display'   => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
//add_filter( 'cron_schedules', 'exthemes_schedule_minutes' );
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'exthemes_schedule_minutes' ) ) {
	wp_schedule_event( time(), 'sc_every_minutes', 'exthemes_schedule_minutes' );
}


if(!function_exists('sc_every_minutes_event_func')){
// Hook into that action that'll fire every three minutes
function sc_every_minutes_event_func() {
global $wpdb, $post, $post_id, $wp_query; 
	//$old		= get_post_meta($post_id, 'available_version', true);
    //$new		= '';	
	//delete_post_meta( $post_id, 'update_available' );  
	//delete_post_meta( $post_id, 'available_version' );
	is_apk_update_available();
		 
}
//add_action( 'exthemes_schedule_minutes', 'sc_every_minutes_event_func' );
}
// ~~~~~~~~~~~~~~~~~~~~~ EX_THEMES ~~~~~~~~~~~~~~~~~~~~~~~~ \\

if(!function_exists('check_app_updates')){
function check_app_updates() {
global $pagenow, $opt_themes, $wpdb, $post, $wp_query; 
$admin_pages = [ 'index.php', 'edit.php'  ];
if ( in_array( $pagenow, $admin_pages ) ) { 
$list_post = get_posts( array(
	'posts_per_page'   	=> 10,
	'meta_key'   		=> 'update_available',
	'meta_value' 		=> 'yes',
) ); 
if (!empty($list_post)){
?>

<div class="notice notice-info is-dismissible">

<?php
foreach($list_post as $p) {
$available_version		= get_post_meta($p->ID, 'available_version', true );
$current_version		= get_post_meta($p->ID, 'wp_version_GP', true );
$appname				= get_post_meta($p->ID, 'wp_title_GP', true );
if (version_compare($available_version, $current_version ) > 0 ) { 
?>
<p>📢 <i>Available updates</i> <b style="color: blue;" class="up-down-shake"><?php echo $appname; ?></b>
<?php if($current_version){?><b style="color: red;">v<?php echo $current_version; ?></b> to<?php } ?> <b style="color: green;">v<?php echo $available_version; ?></b> 👉 <a target="_blank" href="<?php echo get_edit_post_link($p->ID); ?>" class="rotate-shake">Update Now</a></p>
     
<?php 
	} } 
?>
    <p>
        <span><a href="/wp-admin/admin.php?page=wp_apps_to_updates">More apps to updates</a></span>
    </p>
</div>
<?php 
}

}

}
add_action( 'admin_notices', 'check_app_updates' );
}
// ~~~~~~~~~~~~~~~~~~~~~ EX_THEMES ~~~~~~~~~~~~~~~~~~~~~~~~ \\

if(!function_exists('count_apps_update')){
function count_apps_update() {
	global $wpdb; 
	/*
	https://stackoverflow.com/a/41538641
	"SELECT * FROM ".$wpdb->prefix."contentreports ORDER BY status='NEW' ASC"
	*/
	$wpdb->get_results("SELECT * FROM wp_postmeta WHERE (meta_key = 'update_available' AND meta_value = 'yes')");
	return $wpdb->num_rows;
}
}
###### Register a custom menu bar. ###### 

if(!function_exists('wp_apps_update_admin_bar_link')){
function wp_apps_update_admin_bar_link() {
	global $wp_admin_bar;
	if ( !is_super_admin() || !is_admin_bar_showing() )
		return;
	
	$wp_admin_bar->add_menu( array(
		'id'    => 'wp_apps_updates',
		'title' => '<span class="ab-icon dashicons dashicons-info-outline"></span> Apps to update',
		'href' 	=> admin_url('/admin.php?page=wp_apps_to_updates'),
		),
	);
}
add_action( 'admin_bar_menu', 'wp_apps_update_admin_bar_link', 100 );
}
if(!function_exists('apps_to_updates_menu')){
function apps_to_updates_menu() {
    add_menu_page(
        __( 'Apps to update ', THEMES_NAMES ), 
		'Apps update <span class="awaiting-mod">'.count_apps_update().'</span> ',
        'manage_options',
        'wp_apps_to_updates',
        'wp_apps_to_updates',
        'dashicons-info-outline',
        //plugins_url( '/img/imdb.png' ),
        100
    );  
     
}
add_action('admin_menu', 'apps_to_updates_menu');
} 

function wp_apps_to_updates( $post ) {  
echo do_shortcode( '[css]' );	
global $opt_themes, $wpdb, $post, $wp_query; 
$list_post = get_posts( array(
	'posts_per_page'   	=> -1,
	'meta_key'   		=> 'update_available',
	'meta_value' 		=> 'yes',
) );
if ($list_post){ ?>
<div class="play_menu" style="text-transform:uppercase"><b>List all Available app to updates </b></div>
<?php } else { ?>
<div class="play_menu" style="text-transform:uppercase"><b>Welldone... No Available app to updates </b></div>
<?php } if ($list_post){ ?>
<section>
<div class="row">
<?php  
foreach($list_post as $p) {
$appnames				= wp_strip_all_tags(get_post_meta( $p->ID, 'wp_title_GP',  true )); 
$available_version		= get_post_meta($p->ID, 'available_version', true );
$current_version		= get_post_meta($p->ID, 'wp_version_GP', true );
$image_id				= get_post_thumbnail_id($p->ID); 
$image_url				= wp_get_attachment_image_src($image_id, 'full', true)[0]; 

if (version_compare($available_version, $current_version ) > 0 ) { 
?>
        <div class="col-12 col-md-6 mb-4">
            <span class="position-relative archive-post--remove app-container">
                <div class="flex-shrink-0">
                    <img src="<?php echo $image_url; ?>" class="app-logo " width="64" height="64">
                </div>

                <div class="app-info">
                    <h3 class="h5 font-weight-semibold w-100 app-title up-down-shake"><?php echo $appnames; ?></h3>

                    <div class="text-truncate text-muted app-desc">
                        <span class="clamp-1 w-100" style="color: black;font-weight: 700;"><i>Available updates</i> <b
                                style="color: red;">v<?php echo $current_version; ?></b> to <b
                                style="color: green;">v<?php echo $available_version; ?></b></span>
                    </div>
                </div>

                <div class="app-get">
                    <a style="font-size: 13px;  margin:0 12px;" href="<?php echo get_edit_post_link($p->ID); ?>"
                        target="_blank" class="get-button rotate-shake">Update</a>
                </div>

            </span>
        </div>

        <?php }} ?>
    </div>
</section>

<?php } ?>


<?php 

echo do_shortcode( '[ft_menu]' );
echo do_shortcode( '[ft_js]' ); 
} 