<?php

namespace NicoMartin;

/**
 * Media Sideload
 * Plugin Name:       NM Media Sideload
 * Description:       Sideload an Image from a Post-Meta to your attachments
 * Version:           0.1.0
 * Author:            Nico Martin
 * Author URI:        https://nicomartin.ch
 * Text Domain:       nmsl
 * Requires PHP:      5.6
 * Requires WP:       4.9
 */

class MediaSideload
{
	private $postTypes = [ 'post' ];
	private $postMeta = 'slideload-image';
	private $postMetaId = '';
	private $siteUrl = '';

	public function __construct()
	{
		$this->postTypes  = apply_filters('NM\MediaSideload\PostTypes', $this->postTypes);
		$this->postMeta   = apply_filters('NM\MediaSideload\PostMeta', $this->postMeta);
		$this->postMetaId = $this->postMeta . '-nmsl-id';
		$this->siteUrl    = get_site_url();
	}

	public function run()
	{
		add_action('current_screen', function () {
			$screen = get_current_screen();
			if ($screen->base == 'post' && in_array($screen->post_type, $this->postTypes) && array_key_exists('post', $_GET)) {
				$imageId = $this->loadImage($_GET[ 'post' ]);
				if (is_wp_error($imageId)) {
					add_action('admin_notices', function () use ($imageId) {
						?>
						<div class="error notice">
							<p><?php echo $imageId->get_error_message(); ?></p>
						</div>
						<?php
					});
				}
			}
		});
	}

	/**
	 * @param $postId
	 * @param boolean $returnUrl
	 *
	 * @return int|string|\WP_Error
	 */
	private function loadImage($postId, $returnUrl = false)
	{
		if (! in_array(get_post_type($postId), $this->postTypes)) {
			return new \WP_Error('wrong_post_type', 'Wrong Post Type');
		}

		$meta   = get_post_meta($postId, $this->postMeta, true);
		$metaId = get_post_meta($postId, $this->postMetaId, true);

		if (! $meta) {
			return new \WP_Error('meta_not_exist', 'Post Meta "' . $this->postMeta . '" does not exist');
		}

		if ($metaId && strpos($meta, $this->siteUrl) === 0) {
			// If metaId exists and $meta does start with the site URL
			if ($returnUrl) {
				return $meta;
			}

			return $metaId;
		}

		$imageUrl     = esc_url_raw($meta);
		$sideloadedId = media_sideload_image($imageUrl, $postId, null, 'id');
		if (is_wp_error($sideloadedId)) {
			return $sideloadedId;
		}

		$sideloadedUrl = wp_get_attachment_image_url($sideloadedId, 'full');
		update_post_meta($postId, $this->postMetaId, $sideloadedId);
		update_post_meta($postId, $this->postMeta, $sideloadedUrl);

		if ($returnUrl) {
			return $sideloadedUrl;
		}

		return $sideloadedId;
	}
}

$nmMediaSideload = new MediaSideload();
$nmMediaSideload->run();