<?php
/**
 * Button X
 *
 * This file is used to register WooCommerce related functionality of the plugin.
 *
 * @package Buttons X
 * @since 0.1
 */

// Make sure we don't expose any info if called directly
if ( !defined( 'ABSPATH' ) )
	exit;

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

		private static $instance;

		/**
		 * Initiator
		 * @since 0.1
		 */
		public static function init() {
			return self::$instance;
		}

		/**
		 * Constructor
		 * @since 0.1
		 */
		public function __construct() {
			// ajax
			add_action( 'wp_ajax_buttons_list', array( $this, 'buttons_list_ajax' ) );
			add_action( 'wp_ajax_buttons_counter_list', array( $this, 'buttons_counter_list_ajax' ) );
			add_action( 'wp_ajax_buttons_social_list', array( $this, 'buttons_social_list_ajax' ) );
			add_action( 'wp_ajax_buttons_dual_list', array( $this, 'buttons_dual_list_ajax' ) );
			//conent
			add_action( 'admin_footer', array( $this, 'modal_content' ) );
			// media button
			add_action( 'media_buttons', array( $this, 'add_media_button' ), 13 );
			add_action( 'admin_head', array( $this, 'modal_style' ) );
		}

		/**
		 * Inject modal styles in document head
		 * @since 1.9.57
		 * @return html string
		 */
		function modal_style() {
			ob_start();

			?>
			<style type="text/css">
				.wp-media-buttons-icon.dashicons-btnsx-logo {
					display: inline-block;
				    width: 18px;
				    height: 18px;
				    vertical-align: text-top;
				    margin: 0 2px;
				}
				.btnsx-modal .media-modal {
					max-width: 585px;
				    margin: 0 auto;
				    max-height: 600px;
				    top: 13%;
				}
				.btnsx-modal .media-frame-router, .btnsx-modal .media-frame-title, .btnsx-modal .media-frame-content, .btnsx-modal .media-frame-toolbar {
					left: 0;
				}
				.btnsx-modal .media-modal .media-menu-item {
					-webkit-box-shadow: none;
					box-shadow: none;
				}
				#btnsx-modal-content ul {
					padding: 15px;
					padding-right: 0;
					margin: 0;
				}
				#btnsx-modal-content ul li {
					display: inline-block;
				}
				#btnsx-modal-content ul li a {
					display: inline-block;
				    max-width: 100px;
				    background: #efefef;
				    padding: 15px;
				    margin-right: 15px;
				    width: 97.5px;
				    min-height: 60px;
				    line-height: 1.4;
				    text-align: center;
				    overflow: hidden;
				    transition: 0.2s all ease;
				}
				/*#btnsx-modal-content ul li:nth-child(4n) a {
					margin-right: 0;
				}*/
				#btnsx-modal-content ul li a:hover {
					box-shadow: 2px 2px 12px 0px rgba(103, 103, 103, 0.26);
					-webkit-box-shadow: 2px 2px 12px 0px rgba(103, 103, 103, 0.26);
					-moz-box-shadow: box-shadow: 2px 2px 12px 0px rgba(103, 103, 103, 0.26);
				}
				#btnsx-modal-content ul li a.selected {
					background-color: #005086;
					color: #fff;
				}
			</style>
			<?php

			$output = ob_get_contents();

			ob_end_clean();

			echo $output;
		}

		/**
		 * Function to add media button
		 * @since 1.9.57
		 * @return html string
		 */
		function add_media_button() {
			ob_start();
			?>
				<button type="button" id="insert-btnsx-shortcode" class="button">
					<i class="wp-media-buttons-icon dashicons-btnsx-logo"></i>
					Buttons
				</button>
			<?php

			$output = ob_get_contents();

			ob_end_clean();

			echo $output;
		}

		/**
		 * Function to fetch buttons
		 * @since  1.7
		 * @return string
		 */
		public function buttons( $post_type ) {

			global $wpdb;
		   	$btnsx_post = $post_type;
			$btnsx_post_status = 'publish';
	        $btnsx = $wpdb->get_results( $wpdb->prepare(
	            "SELECT ID, post_title
	                FROM $wpdb->posts 
	                WHERE $wpdb->posts.post_type = %s
	                AND $wpdb->posts.post_status = %s
	                ORDER BY ID DESC",
	            $btnsx_post,
	            $btnsx_post_status
	        ) );

	        $list = array();

	        foreach ( $btnsx as $btn ) {
				$selected = '';
				$btn_id = $btn->ID;
				$btn_name = $btn->post_title;
				$list[] = array(
					'text' =>	$btn_name,
					'value'	=>	$btn_id
				);
			}

			wp_send_json( $list );
		}

		/**
		 * Function to fetch counter buttons
		 * @since  1.8.0
		 * @return string
		 */
		public function buttons_counter_list_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-buttons-list', 'security' );
			$btns = $this->buttons( 'buttons-x-cs' );
			return $btns;
		}

		/**
		 * Function to fetch dual buttons
		 * @since  1.7
		 * @return string
		 */
		public function buttons_dual_list_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-buttons-list', 'security' );
			$btns = $this->buttons( 'buttons-x-dual' );
			return $btns;
		}

		/**
		 * Function to fetch buttons
		 * @since  1.6
		 * @return string
		 */
		public function buttons_list_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-buttons-list', 'security' );
			$btns = $this->buttons( 'buttons-x' );
			return $btns;
		}

		/**
		 * Function to fetch social buttons
		 * @since  1.6
		 * @return string
		 */
		public function buttons_social_list_ajax() {
			// check for nonce
			check_ajax_referer( 'btnsx-buttons-list', 'security' );
			$btns = $this->buttons( 'buttons-x-social' );
			return $btns;
		}

		/**
		 * Function to output tab content markup
		 * @since  1.9.58
		 */
		private function tab_content($id, $display) {
			?>
			<div id="<?php echo esc_attr($id); ?>-list-wrapper" style="display:<?php echo esc_attr( $display ? 'block' : 'none' ); ?>">
		   		<div>
		   			<div class="media-toolbar-primary search-form" style="margin-right:15px;">
		   				<label for="media-search-input" class="screen-reader-text"><?php esc_html_e('Search Media','btnsx'); ?></label>
		   				<input type="search" placeholder="Search buttons..." id="<?php echo esc_attr($id); ?>-search" class="search">
		   			</div>
		   			<div class="clear"></div>
		   		</div>
		   		<ul id="<?php echo esc_attr($id); ?>-list"></ul>
		   	</div>
			<?php
		}
 		
		/**
		 * Function to output button list ajax script
		 * @since  1.9.57
		 * @return string
		 */
		public function modal_content() {
			$screen = get_current_screen();
			if ( in_array( $screen->id, array( 'post', 'page' ) ) ) {
				$buttons_list_nonce = wp_create_nonce( 'btnsx-buttons-list' );
				?>
				<script type="text/template" id="tmpl-btnsx-modal-content">
					<div class="media-frame mode-select wp-core-ui" id="__wp-uploader-id-0">
					   	<div class="media-frame-title">
					    	<h1><strong>Buttons X</strong> <span style="font-size:13px;line-height:1.5;font-style:italic;font-weight:400;color:#aeaeae;"> ( <?php esc_html_e('Select buttons below and click "Insert Shortcode" button.', 'btnsx' ); ?> ) </span></h1>
					   	</div>
					   	<div class="media-frame-router">
					    	<div class="media-router">
					      		<a id="btnsx-buttons-tab" href="#" class="media-menu-item active"><?php esc_html_e('Buttons','btnsx'); ?></a>
					      		<a id="btnsx-dual-buttons-tab" href="#" class="media-menu-item"><?php esc_html_e('Dual Buttons','btnsx'); ?></a>
					      		<a id="btnsx-social-buttons-tab" href="#" class="media-menu-item"><?php esc_html_e('Social Buttons','btnsx'); ?></a>
					      		<a id="btnsx-social-counters-tab" href="#" class="media-menu-item"><?php esc_html_e('Social Counters','btnsx'); ?></a>
					    	</div>
					   	</div>
					   	<div id="btnsx-modal-content" class="media-frame-content btnsx-modal-content">
					   		<?php $this->tab_content('btnsx-buttons',true); ?>
					   		<?php $this->tab_content('btnsx-dual-buttons',false); ?>
					   		<?php $this->tab_content('btnsx-social-buttons',false); ?>
					   		<?php $this->tab_content('btnsx-social-counters',false); ?>
					   	</div>
					   	<div class="media-frame-toolbar">
					      	<div class="media-toolbar">
					        	<div class="media-toolbar-primary search-form">
					        		<button type="button" id="btnsx-insert-shortcode" class="button media-button button-primary button-large media-button-insert"><?php esc_html_e('Insert Shortcode', 'btnsx' ); ?></button>
					        	</div>
					      </div>
					   </div>
					</div>
				</script>
			    <script type="text/javascript">
			    	(function($) {
						$(document).ready( function() {
							var content = 'btnsx-modal-content';
						    var FooView = wp.Backbone.View.extend({
					            events: {
					                'click .media-menu-item': 'activeView',
					                'click .btnsx-button-sc': 'toggleActiveClass',
					                'click #btnsx-insert-shortcode': 'insertShortcode',
					                'click #btnsx-buttons-tab': 'buttonsView',
					                'click #btnsx-dual-buttons-tab': 'dualButtonsView',
					                'click #btnsx-social-buttons-tab': 'socialButtonsView',
					                'click #btnsx-social-counters-tab': 'socialCountersView',
					                'input #btnsx-buttons-search': 'searchButtons',
					                'input #btnsx-dual-buttons-search': 'searchDualButtons',
					                'input #btnsx-social-buttons-search': 'searchSocialButtons',
					                'input #btnsx-social-counters-search': 'searchSocialCounters'
					            },
					            template: wp.template( content ),
					            initialize: function(){
					            	this.selectedButtons = [];
					            	this.initialRender();
					            },
					            initialRender: function() {
									this.btnsxButtonsList();
					            },
					            prepare: function() {
					                return this.model.toJSON();
					            },
					            ajaxContent: function(id, action, security) {
					            	// console.log("Works");
					            	$('#btnsx-buttons-list-wrapper,#btnsx-social-buttons-list-wrapper,#btnsx-social-counters-list-wrapper,#btnsx-dual-buttons-list-wrapper').hide();
									$(id+'-wrapper').fadeIn();
					            	var data = {
										'action'	: action, // wp ajax action
										'security'	: security // nonce value created earlier
									};
					            	jQuery.post( ajaxurl, data, function( response ) {
								  		// if nonce fails then not authorized else settings saved
								  		if( response === '-1' ){
									  		// do nothing
									  		console.log('error: not authorized');
								  		} else {
								  			if (typeof(tinyMCE) != 'undefined') {
												// clear the previous buttons
												if ($(id).is(':empty')){
													if( response.length < 1 ){
														$(id).append("<li>Please create a button first.</li>");
													} else {
														$.each(response, function( index, value ) {
															var txt = value.text ? value.text : '(no title)';
															// limit name to 40 characters
															if(txt.length > 40) txt = txt.substring(0,40)+'...';
														  	$(id).append("<li><a href='javascript:void(0)' class='btnsx-button-sc' data-id='"+value.value+"' data-type='"+action+"'>"+txt+"</a></li>");
														});
													}
												}
											}
								  		}
								  	});
					            },
					            activeView: function(ev) {
					            	$('.media-router').children().attr('class','media-menu-item');
					            	$(ev.target).attr('class','media-menu-item active');
					            },
					            btnsxButtonsList: function() {
					            	this.ajaxContent('#btnsx-buttons-list','buttons_list','<?php echo $buttons_list_nonce; ?>');
								},
								toggleActiveClass: function(ev) {
									$(ev.target).toggleClass('selected');
									this.selectedButtons.push({
										id: $(ev.target).data('id'),
										type: $(ev.target).data('type')
									});
								},
								insertShortcode: function(ev) {
									$.each(this.selectedButtons, function( index, value ) {
										switch(value.type) {
										    case 'buttons_dual_list':
										        wp.media.editor.insert('[btnsx_dual id="' + value.id + '"]');
										        break;
										    case 'buttons_social_list':
										        wp.media.editor.insert('[btnsx_social id="' + value.id + '"]');
										        break;
										    case 'buttons_counter_list':
										        wp.media.editor.insert('[btnsx_social_counter id="' + value.id + '"]');
										        break;
										    default:
										        wp.media.editor.insert('[btnsx id="' + value.id + '"]');
										}
									});
									modal.close();
								},
								buttonsView: function(ev) {
									this.ajaxContent('#btnsx-buttons-list','buttons_list','<?php echo $buttons_list_nonce; ?>');
								},
								dualButtonsView: function(ev) {
									this.ajaxContent('#btnsx-dual-buttons-list','buttons_dual_list','<?php echo $buttons_list_nonce; ?>');
								},
								socialButtonsView: function(ev) {
									this.ajaxContent('#btnsx-social-buttons-list','buttons_social_list','<?php echo $buttons_list_nonce; ?>');
								},
								socialCountersView: function(ev) {
									this.ajaxContent('#btnsx-social-counters-list','buttons_counter_list','<?php echo $buttons_list_nonce; ?>');
								},
								search: function(inputId, ulId, value) {
								    // Declare variables
								    var input, filter, ul, li, a, i;
								    // input = document.getElementById(inputId);
								    filter = value.toUpperCase();
								    ul = $(ulId);
								    li = ul.children();

								    // Loop through all list items, and hide those who don't match the search query
								    for (i = 0; i < li.length; i++) {
								        a = li[i].getElementsByTagName("a")[0];
								        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
								            li[i].style.display = "";
								        } else {
								            li[i].style.display = "none";
								        }
								    }
								},
								searchButtons: function(ev) {
									this.search('#btnsx-buttons-search','#btnsx-buttons-list',ev.target.value);
								},
								searchDualButtons: function(ev) {
									this.search('#btnsx-dual-buttons-search','#btnsx-dual-buttons-list',ev.target.value);
								},
								searchSocialButtons: function(ev) {
									this.search('#btnsx-social-buttons-search','#btnsx-social-buttons-list',ev.target.value);
								},
								searchSocialCounters: function(ev) {
									this.search('#btnsx-social-counters-search','#btnsx-social-counters-list',ev.target.value);
								}
						    });

						    // create our modal instance
						    var modal = new wp.media.view.Modal({
						    	title: 'Buttons X',
								className: 'btnsx-modal',
					            controller: { 
					                trigger: function(id) {
					                    // events can be caught here
					                }
					            }
						    });

						    var FooModel = Backbone.Model.extend();
						    var m = new FooModel();
						    $('#insert-btnsx-shortcode').click( function( event ) {
								event.preventDefault();
							    modal.content( new FooView({ model: m }) );
							    modal.open();
							});
						});
					})(jQuery);
				</script>
				<?php
			}
		}

		
	} // Mce Class
}

/**
 *  Kicking this off
 */

$btn_mce = new BtnsxMce();
$btn_mce->init();