<?php if ( ! defined( 'ABSPATH' ) ) {exit;} // Exit if accessed directly.

/**
 * Codevz Admin side featured image AJAX uploader
 * 
 * @author Codevz
 * @link http://codevz.com/
 */

class Codevz_Easy_Posts_Featured_Image {

	use Codevz_Plus_Instance;

    public function __construct() {
        add_filter( 'manage_posts_columns', 		[ $this, 'add' ] );
        add_action( 'manage_posts_custom_column', 	[ $this, 'render' ], 10, 2 );
        add_action( 'wp_ajax_codevz_set_thumb', 	[ $this, 'set' ] );
        add_action( 'wp_ajax_codevz_remove_thumb', 	[ $this, 'remove' ] );
        add_action( 'admin_enqueue_scripts', 		[ $this, 'css_js' ] );

    }

	public function add( $columns ) {

	    global $typenow;

	    if ( ! in_array( $typenow, ['post', 'portfolio'], true ) ) {
	        return $columns;
	    }

	    $new = [];
	    $i = 0;

	    foreach ($columns as $key => $value) {
	        $new[$key] = $value;
	        if ($i === 0) {
	            $new['thumbnail'] = '<span style="margin: 0 18px; opacity: .9; font-size: 16px; position: relative; top: 2px;" class="dashicons dashicons-format-image" aria-hidden="true"></span>';
	        }
	        $i++;
	    }

	    return $new;
	}

    public function set() {

        $img_id = (int) esc_html( $_POST['img_id'] );

        if ( $img_id ) {
	        set_post_thumbnail( (int) esc_html( $_POST['post_id'] ), $img_id );
	        echo wp_get_attachment_image( $img_id, 'thumbnail' );
        }

        wp_die();

    }

    public function remove() {

        $img_id = (int) esc_html( $_POST['post_id'] );

        if ( $img_id ) {
       		delete_post_thumbnail( (int) $img_id );
        }

        wp_die();
    }

    public function render( $column, $post_id ) {

        if ( $column == 'thumbnail' ) {

	        $thumb_id = (int) get_post_thumbnail_id( $post_id );

	        echo '<div class="codevz-plus-thumb" data-post="' . $post_id . '" data-has="' . ( $thumb_id ? 1 : 0 ) . '">';
	        echo '<div class="codevz-plus-thumb-img">';
	        echo $thumb_id ? wp_get_attachment_image( $thumb_id, 'thumbnail' ) : "<img src=\"data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20width='360'%20height='320'%20viewBox%3D'0%200%20360%20320'%2F%3E\">";
	        echo '</div><span><span class="codevz-plus-thumb-set dashicons dashicons-images-alt2"></span><span class="codevz-plus-thumb-remove dashicons dashicons-no-alt"></span><span>';
	        echo '</div>';

        }

    }

	public function css_js( $hook ) {

		if ( $hook !== 'edit.php' ) {
			return;
		}

		wp_enqueue_media();

		wp_register_script('codevz-thumb', false, [], false, true);
		wp_enqueue_script('codevz-thumb');

		wp_add_inline_script('codevz-thumb', $this->js());

		wp_register_style('codevz-thumb', false);
		wp_enqueue_style('codevz-thumb');

		wp_add_inline_style('codevz-thumb', '
			th#thumbnail {width:64px}
			.codevz-plus-thumb {width:58px;position:relative;display:flex;align-items:center}
			.codevz-plus-thumb-loading {pointer-events: none;opacity: .6}
			.codevz-plus-thumb-img{width:inherit}
			.codevz-plus-thumb-img img{width:inherit;max-width: 100%; height: auto; display: block; border-radius: 5px;background-size: 28px; background-color: #fbfbfb;background-image: url(data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDU4IDU4IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1OCA1ODsiIHhtbDpzcGFjZT0icHJlc2VydmUiIHdpZHRoPSI2NHB4IiBoZWlnaHQ9IjY0cHgiPgo8Zz4KCTxwYXRoIGQ9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MtMC45NzItMC4zOTItMS4zNjgtMC4wNDRMNi4zMzksNDQuMjQ5Yy0wLjQxNSwwLjM2NS0wLjQ1NSwwLjk5Ny0wLjA5LDEuNDEyQzYuNDQ3LDQ1Ljg4Niw2LjcyMyw0Niw3LDQ2eiIgZmlsbD0iI2RlZGVkZSIvPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=) !important; background-repeat: no-repeat !important; background-position: center !important;}
			.codevz-plus-thumb > span {transition:all .2s ease-in-out;position:absolute;left:50%;transform:translateX(-50%);display:flex;opacity:0}
			tr:hover .codevz-plus-thumb > span {opacity:1}
			.codevz-plus-thumb .dashicons { transition:all .2s ease-in-out;box-shadow: 0px 2px 10px #33333345;margin: 0 2px;border-radius: 4px; background: #fff; color: #555; padding: 3px; font-size: 17px; line-height: 1; width: 1em; height: 1em; text-align: center; cursor: pointer; }
			.codevz-plus-thumb .codevz-plus-thumb-remove { background: #d63638; color: #fff; }
			.codevz-plus-thumb[data-has="0"] .codevz-plus-thumb-remove {display: none}
			.codevz-plus-thumb .dashicons:hover {transform:scale(1.1)}
			.codevz-plus-thumb-loading:after {
				position: absolute;
				content: "";
				left: 50%;
				top: 50%;
				width: 25px;
				height: 25px;
				border: 3px solid rgb(255 255 255 / 54%);
				font-size: 0 !important;
				border-right-color: #2271b1 !important;
				border-radius: 100%;
				transform: translate(-50%, -50%);
				animation: cz_anim .6s linear infinite
			}
			@keyframes cz_anim {0% {transform: translate(-50%, -50%) rotate(0deg)}100% {transform: translate(-50%, -50%) rotate(359deg)}}
		');
	}

    public function js() {

        return "document.addEventListener('click', function(e) {

    if (e.target.classList.contains('codevz-plus-thumb-set')) {
        codevzOpenMedia(e.target);
    }

    if (e.target.classList.contains('codevz-plus-thumb-remove')) {
        codevzRemoveThumb(e.target);
    }

});

function codevzOpenMedia( btn ) {
    var thumb = btn.closest( '.codevz-plus-thumb' ),
    	image = thumb.querySelector( '.codevz-plus-thumb-img' );

    var frame = wp.media({
        multiple: false
    });

    frame.on( 'select', function () {
        var img = frame.state().get( 'selection' ).first().toJSON();

        thumb.classList.add('codevz-plus-thumb-loading');

        fetch( ajaxurl, {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'action=codevz_set_thumb&post_id=' + thumb.dataset.post + '&img_id=' + img.id
        }).then( function(r) { return r.text(); }).then( function( html ){
        	image.innerHTML = html;
    		thumb.dataset.has = 1;
        	thumb.classList.remove('codevz-plus-thumb-loading');
        });
    });

    frame.open();
}

function codevzRemoveThumb( btn ) {
    var thumb = btn.closest( '.codevz-plus-thumb' ),
    	image = thumb.querySelector( '.codevz-plus-thumb-img' );

    btn.disabled = true;
    thumb.classList.add('codevz-plus-thumb-loading');

    fetch(ajaxurl, {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=codevz_remove_thumb&post_id=' + thumb.dataset.post
    }).then(function(){
    	thumb.dataset.has = 0;
		image.innerHTML = '<img src=\"data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20width=%27360%27%20height=%27320%27%20viewBox%3D%270%200%20360%20320%27%2F%3E\">';
    	btn.disabled = false;
    	thumb.classList.remove('codevz-plus-thumb-loading');
    });
}";

    }

}
Codevz_Easy_Posts_Featured_Image::instance();