<?php
/*
Plugin Name: ATT Gallery Metabox
Plugin URI: http://authenticthemes.com
Description: Shows all image attachments in a metabox for the current post for easier gallery management.
Author: Authentic Themes
Version: 1.0
Author URI: http://authenticthemes
*/

class WPEX_Gallery_Metabox {


	/**
	 * This is our constructor
	 * @return WPEX_Gallery_Metabox
	 */
	public function __construct() {

		add_action( 'init',                    array( $this, 'translations'    )    );
		add_action( 'add_meta_boxes',          array( $this, 'admin_scripts'   ), 5 );
		add_action( 'add_meta_boxes',          array( $this, 'metabox_add'     )    );
		add_action( 'wp_ajax_refresh_metabox', array( $this, 'refresh_metabox' )    );
		add_action( 'wp_ajax_gallery_remove',  array( $this, 'gallery_remove'  )    );
	}



	/**
	 * Translations
	 * @since 1.0
	 */
	public function translations() {
		load_plugin_textdomain( 'wpex', false, basename( dirname( __FILE__ ) ) . '/languages' );
	}



	/**
	 * AJAX scripts to load on call
	 * @since 1.0
	 */

	public function admin_scripts() {
		wp_register_script( 'wpex-gmb-tooltipster', get_template_directory_uri() .'/functions/gallery-metabox/tooltipster.js', array( 'jquery' ), null, true );
		wp_register_script( 'wpex-gmb-js', get_template_directory_uri() .'/functions/gallery-metabox/wpex-gmb-js.js', array( 'jquery', 'wpex-gmb-tooltipster' ), null, true );
		wp_register_style( 'wpex-gmb-style', get_template_directory_uri() .'/functions/gallery-metabox/wpex-gmb-style.css', array(), null );

	}
	

	
	/**
	 * Add the Metabox
	 * @since 1.0
	 */
	public function metabox_add() {

		$post_types		= apply_filters( 'wpex_gmb_post_types', array( 'portfolio', 'services' ) );
		$context		= apply_filters( 'wpex_gmb_context', 'normal' );
		$priority		= apply_filters( 'wpex_gmb_priority', 'high' );
		
		// Loop through all post types
		foreach( $post_types as $post_type ) {
			
			// Get post ID
			if( isset( $_GET['post'] ) ) $post_id = $_GET['post'];
			elseif( isset( $_POST['post_ID'] ) ) $post_id = $_POST['post_ID'];
			if( !isset( $post_id ) ) $post_id = false;
			
			// Load scripts && setup metabox
			if( apply_filters( 'wpex_gmb_limit', true, $post_id ) ) {
				add_meta_box( 'wpex_gmb', __( 'Gallery Images', 'wpex' ), array( $this, 'gallery_metabox' ), $post_type, $context, $priority );
				wp_enqueue_script( 'wpex-gmb-tooltipster' );
				wp_enqueue_script( 'wpex-gmb-js' );
				wp_enqueue_style( 'wpex-gmb-style' );
			}

		}
	}



	/**
	 * Build the Metabox
	 * @since 1.0
	 */
	public function gallery_metabox( $post ) {		
		$original_post = $post;
		echo $this->gallery_metabox_html( $post->ID );
		$post = $original_post;
	}



	/** 
	 * Image array for gallery metabox
	 * @since 1.3
	 */
	public function gallery_images( $post_id ) {

		$args = array(
			'post_type'         => 'attachment',
			'post_status'       => 'inherit',
			'post_parent'       => $post_id,
			'post_mime_type'    => 'image',
			'posts_per_page'    => -1,
			'order'             => 'ASC',
			'orderby'           => 'menu_order',
			'no_found_rows'		=> true
			);
		$args = apply_filters( 'wpex_gmb_args', $args );
		$images = get_posts( $args );
		return $images;

	}



	/*
	* Display Images
	* @since 1.0
	*/
	public function gallery_display( $loop ) {

		$gallery = '<div class="wpex-gmb-image-wrapper">';
		
			foreach( $loop as $image ):
			
				if ( function_exists('aq_resize') ) {
					$thumbnail	= aq_resize( wp_get_attachment_url( $image->ID ), 120,  120,  true );
				} else {
					$thumbnail	= wp_get_attachment_image_src( $image->ID, apply_filters( 'wpex_gmb_image_size', 'thumbnail' ) );
					$thumbnail	= $thumbnail[0];
				}
	
				$gallery .= '<div class="wpex-gmb-image">';
				
					// gallery img
					$gallery .= '<a href="'. admin_url( '/post.php?post='. $image->ID .'&action=edit&image-editor') .'" class="wpex-gmb-tooltip" title="'. __('Edit Image','wpex') .'" target="_blank"><img src="' . $thumbnail . '" alt="' . $image->post_title . '" rel="' . $image->ID . '" class="wpex-gmb-thumb" /></a>';			
						
					// removal button
					$gallery .= '<a href="#" class="wpex-gmb-remove wpex-gmb-tooltip"  title="'. __('Remove Image','wpex') .'" rel="' . $image->ID .'"><img src="' . get_template_directory_uri() .'/functions/gallery-metabox/remove.png" alt="'. __('Remove Image','wpex') .'"></a>';					
					
					// title
					//$gallery .= '<div class="wpex-gmb-image-title">'. get_the_title($image->ID) .'</div>';
					
				$gallery .= '</div>';
			
			endforeach;

		$gallery .= '</div>';

		return $gallery;

	}




	/*
	* HTML output
	* @since 1.0
	*/
	public function gallery_metabox_html( $post_id ) {
		
		$return = '';
		
		$intro	= '<p class="be-metabox-links">';
		
			// Upload
			$intro	.= '<a href="#" class="be-button button-secondary" id="wpex-gmb-manage-btn">' . __( 'Manage Images', 'wpex' ) . '</a>';		
			
			// Manage
			//$intro	.= '<a href="#" id="wpex-gallery-manage-btn" class="be-button button-secondary" title="' . __( 'Re-order Images', 'wpex' ) . '">' . __( 'Re-order Images', 'wpex' ) . '</a>';
			
			// Refresh
			$intro	.= '<input id="update-gallery" class="be-button button-secondary" type="button" value="'. __('Refresh','wpex') .'" name="update-gallery"></p>';
		
		$return .= apply_filters( 'wpex_gmb_intro', $intro );

		
		$loop = $this->gallery_images( $post_id );

		$gallery = $this->gallery_display( $loop );

		$return .= $gallery;

		return $return;
	}



	/**
	 * Gallery Metabox AJAX Update
	 * @since 1.0
	 */
	
	public function refresh_metabox() {
		$parent	= $_POST['parent'];
		$loop = $this->gallery_images( $parent );
		$images	= $this->gallery_display( $loop );
		$ret = array();
		if( !empty( $parent ) ) {
			$ret['success'] = true;
			$ret['gallery'] = $images;
		} else {
			$ret['success'] = false;
		}
		echo json_encode( $ret );
		die();
	}
	
	

	/**
	 * Gallery image removal
	 * @since 1.0
	 */
	
	public function gallery_remove() {

		// content from AJAX post
		$image = $_POST['image'];
		$parent	= $_POST['parent'];

		// no image ID came through, so bail
		if( empty( $image ) ) {
			$ret['success'] = false;
			echo json_encode( $ret );
			die();
		}

		// removal function
		$remove                 = array();
		$remove['ID']           = $image;
		$remove['post_parent']	= 0;

		$update = wp_update_post( $remove );

		// AJAX return array
		$ret = array();

		if( $update !== 0 ) {

			// loop to refresh the gallery
			$loop = $this->gallery_images( $parent );
			$images	= $this->gallery_display( $loop );
			
			// return values
			$ret['success'] = true;
			$ret['gallery'] = $images;

		} else {
			// failure return. can probably make more verbose
			$ret['success'] = false;

		}

		echo json_encode( $ret );
		die();
	}

}


// Instantiate our class
$WPEX_Gallery_Metabox = new WPEX_Gallery_Metabox();