<?php  
/**
 * Initialize wprthumb or image_background_other on the post edit screen.
 * https://stackoverflow.com/q/22577566
*/

if (!function_exists('init_image_background_other')) {
	function init_image_background_other() {
		new image_background_other();
	}
}

if ( is_admin() ) {
    add_action( 'load-post.php', 'init_image_background_other' );
    add_action( 'load-post-new.php', 'init_image_background_other' );
}

if ( !class_exists( 'image_background_other' ) ) {
class image_background_other { 

    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
        add_action( 'save_post', array( $this, 'save' ) );
    }
 
    public function add_meta_box( $post_type ) {
		if ( post_type_supports( $post_type, 'thumbnail' )) {
		  add_meta_box(
			'featured_image_and_background_remote'
			,'Remote Post Thumbnail and Background Image'
			,array( $this, 'render_meta_box_content' )
			,$post_type
			,'side'
			,'default'
		  );
		}
    }

    /**
     * Save the meta when the post is saved.
     */
    public function save( $post_id ) {
 
        // Check if our nonce is set.
        if ( ! isset( $_POST['image_background_other_nonce'] ) )
            return $post_id;

        $nonce = $_POST['image_background_other_nonce'];

        // Verify that the nonce is valid.
        if ( ! wp_verify_nonce( $nonce, 'image_background_other' ) )
            return $post_id;

        // If this is an autosave, our form has not been submitted,
		// so we don't want to do anything.
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
            return $post_id;

        // Check the user's permissions.
        if ( 'page' == $_POST['post_type'] ) {

            if ( ! current_user_can( 'edit_page', $post_id ) )
                return $post_id;

        } else {

            if ( ! current_user_can( 'edit_post', $post_id ) )
                return $post_id;
        }

		/* All good, its safe for us to save the data now. */
		
		/* featured image */
		$image_url		= get_post_meta( get_the_ID(), 'poster', true );
		$image			= $image_url;
		//$title_image	= sanitize_title($gets_data['title_GP']);
		$title_image	= sanitize_title_with_dashes(ex_themes_clean(get_post_meta( get_the_ID(), 'wp_GP_ID', true )));
		$title			= $title_image.'-'.$post_id;
		$uploaddir		= wp_upload_dir();
		$filename		= "{$title}.png"; 
		$uploadfile		= $uploaddir['path'].'/'.$filename;
		$contents		= file_get_contents($image);
		$savefile		= fopen($uploadfile, 'w');
		fwrite($savefile, $contents);
		fclose($savefile);
		$wp_filetype	= wp_check_filetype(basename($filename), null );
		$attachment		= array(
			'post_mime_type'	=> $wp_filetype['type'],
			'post_title'		=> $filename,
			'post_content'		=> '',
			'post_status'		=> 'inherit'
		);
		$attach_id		= wp_insert_attachment( $attachment, $uploadfile );
		require_once(ABSPATH . 'wp-admin/includes/image.php');
		$attach_data	= wp_generate_attachment_metadata( $attach_id, $uploadfile );
		wp_update_attachment_metadata( $attach_id, $attach_data );
		set_post_thumbnail( $post_id, $attach_id );
			
		/* background image */
		$image_bg		= get_post_meta( get_the_ID(), 'background', true );
		$title_image	= sanitize_title_with_dashes(ex_themes_clean(get_post_meta( get_the_ID(), 'wp_GP_ID', true )));
		$title			= $title_image.'-'.$post_id; 
		$uploaddir		= wp_upload_dir();
		$filename_bg	= "{$title}-bg.png";
		$uploadfile_bg	= $uploaddir['path'].'/'.$filename_bg;
		$contents_bg	= file_get_contents($image_bg);
		$savefile_bg	= fopen($uploadfile_bg, 'w');
		fwrite($savefile_bg, $contents_bg);
		fclose($savefile_bg);
		$wp_filetype_bg	= wp_check_filetype(basename($filename_bg), null );
		$attachment_bg	= array(
			'post_mime_type'	=> $wp_filetype_bg['type'],
			'post_title'		=> $filename_bg,
			'post_content'		=> '',
			'post_status'		=> 'inherit'
		);
		$attach_id_bg	= wp_insert_attachment( $attachment_bg, $uploadfile_bg );
		require_once(ABSPATH . 'wp-admin/includes/image.php');
		$attach_data_bg	= wp_generate_attachment_metadata( $attach_id_bg, $uploadfile_bg );
		wp_update_attachment_metadata( $attach_id_bg, $attach_data_bg ); 
		update_post_meta( $post_id, '_background_image_id', $attach_id_bg );
		update_post_meta( $post_id, 'background_images', $attach_id_bg );

		$GP_ID			= get_post_meta( get_the_ID(), 'wp_GP_ID', true );

		$url 			= (empty($_SERVER['HTTPS']) ? 'http' : 'https') . '://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$GP_ID; 
		$url2 			= 'https://exthem.es/gps.php?pkgid='.$GP_ID;  
		 
		//$get_infos		= @get_linkz1($gp);  
		//$g_data			= @file_get_contents($url2);
		
		if (!function_exists('file_get_html')) {
			require_once get_template_directory().'/libs/addons/inc/dom.php';
		}
		
		$context = stream_context_create([
			'ssl' => [
				'verify_peer' => false,
				'verify_peer_name' => false,
			]
		]); 

		//$html	= str_get_html(file_get_contents($url));	
		//$html 		= @get_linkz1($url2); // Load the HTML from a URL
		//$html 		= file_get_contents($url2); // Load the HTML from a URL
		
		$html			= file_get_html($url, false, $context); // Load the HTML from a URL wirhout ssl verfied

		if (!empty($html)) {
		$g_data 		= $html->outertext;
		$n_version		= matchx('/<div class="version">(.*?)<\/div>/ms', $g_data, 1);  
		$images_GP		= match_all('/<img.*?src="(.*?)".*?>/ms', matchx('/<div id="gallery">(.*?)<\/div>/ms', $g_data, 1), 1); 

		$html->clear();
		unset($html);		
		
		if ( !empty($images_GP) ) { 
			$gallery_image	= array(); 
			for ($i = 0; $i < count( $images_GP ); $i++ ) {
				if ( '' != $images_GP[$i] ) {
					$gallery_image['image_url'][] = $images_GP[$i];
				}
			}
			update_post_meta( $post_id, 'gallery_data', $gallery_image ); 
		}
		
		}

	 
		/* download link */
		$download_info_link = array();
		
		$title_dwz	= get_post_meta( get_the_ID(), 'wp_title_GP', true );
		$size_dwz	= get_post_meta( get_the_ID(), 'wp_sizes', true );
		$linkapkz	= ouo_io_exhemes('https://exthem.es/apk.php?pkg='.$GP_ID);
			 
		$download_info_link_data_gps = [
			'name'		=> $title_dwz,
			'url'		=> $linkapkz,
			'sizes1' 	=> $size_dwz,
			'sizes' 	=> $size_dwz,
			'title' 	=> $title_dwz,
			'links' 	=> $linkapkz,
			'size' 		=> $size_dwz,
			'tipes' 	=> '',
			'notes' 	=> '',
		]; 
			 
		array_push($download_info_link, $download_info_link_data_gps);
		add_post_meta($post_id, "repeatable_fields", $download_info_link);
		add_post_meta($post_id, "group_downloads_links", $download_info_link);			
		 
		$categorys	= get_post_meta( get_the_ID(), 'wp_category', true );
		$developers	= get_post_meta( get_the_ID(), 'wp_developers_GP', true );
		wp_set_object_terms( $post_id, get_post_meta( get_the_ID(), 'wp_category', true ), 'category', false );
		wp_set_object_terms( $post_id, get_post_meta( get_the_ID(), 'wp_developers_GP', true ), 'developer', true ); 

	}
 
    public function render_meta_box_content( $post ) { 
        wp_nonce_field( 'image_background_other', 'image_background_other_nonce' ); 
        //echo '<label for="remote_thumb">';
        //_e( 'Enter remote image url', 'wprthumb' );
        //echo '</label> ';
        //echo '<input type="text" id="remote_thumb" name="remote_thumb" size="25" />';
    }
}
}
