<?php
/**
 * Button X
 *
 * This file is used to register export/import 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( 'BtnsxPortation' ) ) {
	class BtnsxPortation {
		private static $instance;

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

		/**
		 * Constructor
		 * @since 0.1
		 */
		public function __construct() {
			add_action( 'admin_head', array( $this, 'import_page_styles' ) );
			add_filter( 'post_row_actions', array( $this, 'row_actions' ), 10, 2 );
    		add_action( 'admin_init', array( $this, 'download' ) );
    		add_action( 'wp_ajax_one_click_import', array( $this, 'one_click_import' ) );
    		add_action( 'wp_ajax_upload', array( $this, 'upload' ) );
			add_action( 'admin_footer', array( $this, 'import_jquery' ) );
		}

		/**
		 * Function to output CSS on import page.
		 * @since  0.1
		 * @return string
		 */
		public function import_page_styles() {
			$current_color = get_user_option( 'admin_color' );
			global $_wp_admin_css_colors;
			?>
			<style type="text/css">
		      	.col-pad-settings {
					padding: 20px 10px 20px !important;
		      	}
		      	.btn-save {
					background-color: <?php echo $_wp_admin_css_colors[$current_color]->colors[3]; ?> !important;
					background-image: none !important;
		      	}
		      	.btn-import {
					background-color: <?php echo $_wp_admin_css_colors[$current_color]->colors[2]; ?> !important;
					background-image: none !important;
		      	}
		      	.btn-settings {
		      		/*width: 100% !important;*/
					border: 0 !important;
					color: #fff !important;
		      	}
		      	.btn-settings:disabled {
		      		opacity: 0.4;
		      	}
	      	</style>
	      	<?php
		}

		/**
		 * Function to add export link to row actions on buttons X post type
		 * @since  0.1
		 * @param  string    $actions default actions
		 * @param  WP_Post   $post post object
		 * @return string
		 */
		public function row_actions( $actions, WP_Post $post ) {
	        if ( !in_array( $post->post_type, array( 'buttons-x', 'buttons-x-social', 'buttons-x-dual', 'buttons-x-cs' ) ) ) {
	            return $actions;
	        }
	        if( $post->post_type == 'buttons-x' ){
	        	$actions[ 'export' ] = '<a href="edit.php?post_type=buttons-x&btnsx_export=' . $post->ID . '">' . __( 'Export', 'btnsx' ) . '</a>';
	        }
	        if( $post->post_type == 'buttons-x-social' ){
	        	$actions[ 'export' ] = '<a href="edit.php?post_type=buttons-x-social&btnsx_export=' . $post->ID . '">' . __( 'Export', 'btnsx' ) . '</a>';
	        }
	        if( $post->post_type == 'buttons-x-dual' ){
	        	$actions[ 'export' ] = '<a href="edit.php?post_type=buttons-x-dual&btnsx_export=' . $post->ID . '">' . __( 'Export', 'btnsx' ) . '</a>';
	        }
	        if( $post->post_type == 'buttons-x-cs' ){
	        	$actions[ 'export' ] = '<a href="edit.php?post_type=buttons-x-cs&btnsx_export=' . $post->ID . '">' . __( 'Export', 'btnsx' ) . '</a>';
	        }
	        return $actions;
	    }

	    /**
	     * Function to execute when export link is clicked
	     * @since  0.1
	     * @return 
	     */
	    public function download() {
	        /* Listen for form submission */
	        if( empty( $_GET[ 'btnsx_export' ] ) ){
	            return;
	        }
	        /* Check permissions and nonces */
	        if( !current_user_can( 'manage_options' ) )
	            wp_die('');
	     
	        // check_admin_referer( '','');
	     
	        // Trigger download
	        $this->export();
	    }

	    /**
	     * Function to export button as json file
	     * @since  0.1
	     * @param  array     $args
	     * @return string
	     */
	    public function export( $args = array() ) {
	    	// get the current post id
		    $id = $_GET['btnsx_export'];
		    // fetch json data
		    $output = $this->fetch_json( $id );
		    // print json data
		    $this->print_json( array( $output ) );
		}

		/**
		 * Function fetch and encode data as json
		 * @since  0.1
		 * @param  int    $id
		 * @return string
		 */
		public function fetch_json( $id ) {
			// Look for the specified post type and slug that are published
		    $args = array(
		        'post_type' => array( 'buttons-x', 'buttons-x-social', 'buttons-x-dual', 'buttons-x-cs' ),
		        'p' => $id,
		        'post_status' => array( 'publish', 'trash' )
		    );
		    $post_type_query = new WP_Query( $args );

		    // A post with that information already exists
		    if ( $post_type_query->have_posts() ) {
		    	// Start loop
		        while ( $post_type_query->have_posts() ) {
		            $post_type_query->the_post();

		            // fetch all custom fields
		            $meta_data = get_post_custom( get_the_ID() );

		            // check for post type
		            $post_type = get_post_type( get_the_ID() );

		            // unserialize required custom fields data
		            if( $post_type == 'buttons-x' ){
		            	$meta_data = maybe_unserialize( $meta_data['btnsx'][0] );
		            	// look for assigned tags
			            $tags = get_the_terms( get_the_ID(), 'btnsx_tag' );
			            if ( $tags && ! is_wp_error( $tags ) ) {
			                foreach ( $tags as $tag ) {
			                    $tags[] = $tag->name;
			                }
			            }
			            // look for assigned packs
			            $packs = get_the_terms( get_the_ID(), 'btnsx_pack' );
			            if ( $packs && ! is_wp_error( $packs ) ) {
			                foreach ( $packs as $pack ) {
			                    $packs[] = $pack->name;
			                }
			            }
		            }
		            if( $post_type == 'buttons-x-social' ){
		            	$meta_data = maybe_unserialize( $meta_data['btnsx-social'][0] );
		            	// look for assigned tags
			            $tags = get_the_terms( get_the_ID(), 'btnsx_social_tag' );
			            if ( $tags && ! is_wp_error( $tags ) ) {
			                foreach ( $tags as $tag ) {
			                    $tags[] = $tag->name;
			                }
			            }
			            // look for assigned packs
			            $packs = get_the_terms( get_the_ID(), 'btnsx_social_pack' );
			            if ( $packs && ! is_wp_error( $packs ) ) {
			                foreach ( $packs as $pack ) {
			                    $packs[] = $pack->name;
			                }
			            }
		            }
		            if( $post_type == 'buttons-x-dual' ){
		            	$meta_data = maybe_unserialize( $meta_data['btnsx-dual'][0] );
		            	// look for assigned tags
			            $tags = get_the_terms( get_the_ID(), 'btnsx_dual_tag' );
			            if ( $tags && ! is_wp_error( $tags ) ) {
			                foreach ( $tags as $tag ) {
			                    $tags[] = $tag->name;
			                }
			            }
			            // look for assigned packs
			            $packs = get_the_terms( get_the_ID(), 'btnsx_dual_pack' );
			            if ( $packs && ! is_wp_error( $packs ) ) {
			                foreach ( $packs as $pack ) {
			                    $packs[] = $pack->name;
			                }
			            }
		            }
		            if( $post_type == 'buttons-x-cs' ){
		            	$meta_data = maybe_unserialize( $meta_data['btnsx-cs'][0] );
		            	// look for assigned tags
			            $tags = get_the_terms( get_the_ID(), 'btnsx_cs_tag' );
			            if ( $tags && ! is_wp_error( $tags ) ) {
			                foreach ( $tags as $tag ) {
			                    $tags[] = $tag->name;
			                }
			            }
			            // look for assigned packs
			            $packs = get_the_terms( get_the_ID(), 'btnsx_cs_pack' );
			            if ( $packs && ! is_wp_error( $packs ) ) {
			                foreach ( $packs as $pack ) {
			                    $packs[] = $pack->name;
			                }
			            }
		            }
		            
		            // get post title
		            $title = get_the_title();

		            // create a new data variable
		            $fields = array();
		            // loop through the data and unserialize serialized data
		            foreach ( $meta_data as $k => $v ) {
		            	$v = maybe_unserialize( $v );
		            	// store unserialized value as array
		            	$fields[ $k ] = $v;
		            }

		            // Create a new array with fields to output
		            $data = array(
		                get_the_ID() => array(
		                	'type'	=> $post_type,
		                    'title' => $title,
		                    'tags' 	=> $tags,
		                    'packs' => $packs,
		                    'data' 	=> $fields
		                )
		            );

		            
		            // $output = json_encode( $data ); 

		        }
		    }
		    wp_reset_postdata();

		    return $data;
		}

		/**
		 * Function to print json file
		 * @since  0.1
		 * @return string
		 */
		public function print_json( $output ) {
			// Create a file name
		    $sitename = sanitize_key( get_bloginfo( 'name' ) );
		    if ( ! empty( $sitename ) ) $sitename .= '.';
		    $filename = $sitename . 'Buttons-X.' . date( 'Y-m-d' ) . '.json';
		 
		    // Print header
		    header( 'Content-Description: File Transfer' );
		    header( 'Content-Type: application/txt;' );
		    header( 'Content-Disposition: attachment; filename=' . $filename );
		    header( 'Content-Transfer-Encoding: binary' );
		    header( 'Expires: 0' );
		    header( 'Cache-Control: must-revalidate' );
		    header( 'Pragma: public' );

		    // print encoded data
		    print json_encode( $output ); // Use json_encode( $output, JSON_PRETTY_PRINT ) for pretty print.

		    exit;
		 
		    /* Print comments */
		    //echo "<!-- This is an export file containing buttons for Buttons X button builder plugin for WordPress -->\n";
		 
		    /* Print the logs */
		}

		/**
		 * Function to import pre-made buttons
		 * @since  0.1
		 * @return string
		 */
		public function one_click_import( $file ) {
			// check for nonce
			check_ajax_referer( 'btnsx-import', 'security' );

			$local_file = BTNSX__PLUGIN_DIR . 'assets/buttons.json';

			$predefined = array();

			if( $file === '' ) {
				$file = $local_file;
				$predefined = isset($_POST['buttons']) ? $_POST['buttons'] : array();
			}
			
			$buttons = self::parse( $file );

			$newButtons = array();
			if( is_array( $buttons ) ) {
				$newButtons = $buttons;
				$buttons = array();
				foreach ( $newButtons as $key => $value ) {
					if( !empty($predefined) ){
						foreach ( $value as $k => $v ) {
							if( in_array($k, array_filter($predefined)) ){
								$buttons[$k] = $v;
							}
						}
					} 
					if( $file != $local_file ) {
						foreach ( $value as $k => $v ) {
							$buttons[$k] = $v;
						}
  					}
				}
			}

			if( !empty($buttons) ){
				$data = array(); $title = array(); $taxonomies = array();
				// store the json data in proper format
				foreach ( $buttons as $key => $value ) {
					$val = (array) $value->{ 'data' };
					$id = $val['btnsx_id'];
					$title[ $id ] = $value->{ 'title' };
					$tags = (array) $value->{ 'tags' };
					$packs = (array) $value->{ 'packs' };
					$post_type = $value->{ 'type' };
					// store tags as an array
					foreach ( $tags as $t => $g ) {
						if( is_object( $g ) ){ //  && $g->object_id == $id
							$taxonomies[ $id ][ 'btnsx_tag' ][] = $g->name;
						}
					}
					// store packs as an array
					foreach ( $packs as $p => $k ) {
						if( is_object( $k ) ){
							$taxonomies[ $id ][ 'btnsx_pack' ][] = $k->name;
						}
					}
					$d = array();
					// convert deep object values to array
					foreach ( $val as $k => $v ) {
						if( is_object( $v ) ){
							$v = (array) $v;
						}
						$d[ $k ] = $v;
					}
					$data[ $post_type ][ $val['btnsx_id'] ] = $d;
				}
				$buttons_args = array(
					'post_type' => 'buttons-x',
					'posts_per_page' => -1
				);
				// The Query to get all currently stored button titles
				$title_query = new WP_Query( $buttons_args );
				$title_array = array();
				// The Loop
				if ( $title_query->have_posts() ) {
					while ( $title_query->have_posts() ) {
						$title_query->the_post();
						$title_array[] = get_the_title();
					}
				} else {
					// no posts found
				}
				/* Restore original Post Data */
				wp_reset_postdata();
				$buttons_social_args = array(
					'post_type' => 'buttons-x-social',
					'posts_per_page' => -1
				);
				// The Query to get all currently stored button titles
				$title_query_social = new WP_Query( $buttons_social_args );
				$title_array_social = array();
				// The Loop
				if ( $title_query_social->have_posts() ) {
					while ( $title_query_social->have_posts() ) {
						$title_query_social->the_post();
						$title_array_social[] = get_the_title();
					}
				} else {
					// no posts found
				}
				/* Restore original Post Data */
				wp_reset_postdata();
				$buttons_dual_args = array(
					'post_type' => 'buttons-x-dual',
					'posts_per_page' => -1
				);
				// The Query to get all currently stored button titles
				$title_query_dual = new WP_Query( $buttons_dual_args );
				$title_array_dual = array();
				// The Loop
				if ( $title_query_dual->have_posts() ) {
					while ( $title_query_dual->have_posts() ) {
						$title_query_dual->the_post();
						$title_array_dual[] = get_the_title();
					}
				} else {
					// no posts found
				}
				/* Restore original Post Data */
				wp_reset_postdata();
				$buttons_cs_args = array(
					'post_type' => 'buttons-x-cs',
					'posts_per_page' => -1
				);
				// The Query to get all currently stored button titles
				$title_query_cs = new WP_Query( $buttons_cs_args );
				$title_array_cs = array();
				// The Loop
				if ( $title_query_cs->have_posts() ) {
					while ( $title_query_cs->have_posts() ) {
						$title_query_cs->the_post();
						$title_array_cs[] = get_the_title();
					}
				} else {
					// no posts found
				}
				/* Restore original Post Data */
				wp_reset_postdata();
				global $btnsx_settings;
				foreach ( $data as $type => $value ) {
					foreach( $value as $id => $val ) {
						$title[ $id ] = isset( $title[ $id ] ) ? $title[ $id ] : __( 'No Title', 'btnsx' );
						if( !in_array( $title[ $id ], ( $type === 'buttons-x' ? $title_array : $type === 'buttons-x-social' ? $title_array_social : $title_array_dual ) ) ) {
							$args = array(
								'post_title'	=> $title[ $id ], // The title of post.
								'post_status'	=> 'publish',
								'post_type'		=> $type, // Our custom post type.
							);
							if( $type == 'buttons-x-social' ) {
								$pack = 'btnsx_social_pack';
								$tag = 'btnsx_social_tag';
							} elseif( $type == 'buttons-x-dual' ) {
								$pack = 'btnsx_dual_pack';
								$tag = 'btnsx_dual_tag';
							} elseif( $type == 'buttons-x-cs' ) {
								$pack = 'btnsx_cs_pack';
								$tag = 'btnsx_cs_tag';
							} else {
								$pack = 'btnsx_pack';
								$tag = 'btnsx_tag';
							}
							$post_id 		= wp_insert_post( $args );
							if( isset( $taxonomies[ $id ][ 'btnsx_pack' ] ) ) {
								$packs 		= wp_set_object_terms( $post_id, $taxonomies[ $id ][ 'btnsx_pack' ], $pack );
							}
							if( isset( $taxonomies[ $id ][ 'btnsx_tag' ] ) ) {
								$tags 		= wp_set_object_terms( $post_id, $taxonomies[ $id ][ 'btnsx_tag' ], $tag );
							}
							if ( is_wp_error( $packs ) ) {
								echo sprintf( __( 'Error assigning packs for button %d.', 'btnsx' ), $post_id );
							}
							if ( is_wp_error( $tags ) ) {
								echo sprintf( __( 'Error assigning tags for button %d.', 'btnsx' ), $post_id );
							}
							if( $type == 'buttons-x' ){
								$imgs = array(
									'btnsx_preview_background_image' => isset( $val['btnsx_preview_background_image']['image'] ) ? $val['btnsx_preview_background_image']['image'] : '',
									'btnsx_icon_image' => isset( $val['btnsx_icon_image'] ) ? $val['btnsx_icon_image'] : '',
									'btnsx_icon_image_hover' => isset( $val['btnsx_icon_image_hover'] ) ? $val['btnsx_icon_image_hover'] : '',
									'btnsx_background_image_normal' => isset( $val['btnsx_background_image_normal'] ) ? $val['btnsx_background_image_normal'] : '',
									'btnsx_background_image_hover' => isset( $val['btnsx_background_image_hover'] ) ? $val['btnsx_background_image_hover'] : ''
								);
								$imgs = array_filter( $imgs );
								$src = '';
								foreach ($imgs as $key => $img) {
									if( $key == 'btnsx_preview_background_image' ) {
										$val[$key]['image'] = $this->btnsx_media_handle_upload($img);
									}else{
										$val[$key] = $this->btnsx_media_handle_upload($img);
									}
								}
								update_post_meta( $post_id, 'btnsx', $val );
								if( $btnsx_settings['css'] === 'external' ) {
									$css = new Btnsx();
									$css->print_css( $post_id );
									// echo "CSS printed";
								}
							}
							if( $type == 'buttons-x-social' ){
								update_post_meta( $post_id, 'btnsx-social', $val );
							}
							if( $type == 'buttons-x-dual' ){
								update_post_meta( $post_id, 'btnsx-dual', $val );
								if( $btnsx_settings['css'] === 'external' ) {
									$css = new BtnsxDual();
									$css->print_css( $post_id );
								}
							}
							if( $type == 'buttons-x-cs' ){
								update_post_meta( $post_id, 'btnsx-cs', $val );
							}
							echo sprintf( __( 'Button "%s" imported successfully.', 'btnsx' ), $title[ $id ] ) . '|';
						} else {
							echo sprintf( __( 'Button with same name "%s" already exists.', 'btnsx' ), $title[ $id ] ) . '|';
						}
					}
				}
			} else {
				echo __( 'No button selected.', 'buttons-x' );
			}

			wp_die();
		}

		public function btnsx_media_handle_upload( $url ){
			// Need to require these files
			if ( !function_exists('media_handle_upload') ) {
				require_once(ABSPATH . "wp-admin" . '/includes/image.php');
				require_once(ABSPATH . "wp-admin" . '/includes/file.php');
				require_once(ABSPATH . "wp-admin" . '/includes/media.php');
			}

			$tmp = download_url( $url );
			if( is_wp_error( $tmp ) ){
				// download failed, handle error
			}
			$post_id = 0;
			$file_array = array();

			// Set variables for storage
			// fix file filename for query strings
			preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
			$file_array['name'] = basename($matches[0]);
			$file_array['tmp_name'] = $tmp;

			// If error storing temporarily, unlink
			if ( is_wp_error( $tmp ) ) {
				@unlink($file_array['tmp_name']);
				$file_array['tmp_name'] = '';
			}

			// do the validation and storage stuff
			$id = media_handle_sideload( $file_array, $post_id );

			// If error storing permanently, unlink
			if ( is_wp_error($id) ) {
				@unlink($file_array['tmp_name']);
				return;
			}

			$src = wp_get_attachment_url( $id );
			return $src;
		}

		/**
		 * Function to manually upload buttons
		 * @since  0.1
		 * @return
		 */
		public function upload() {
			 
			check_ajax_referer( 'btnsx-import', 'security' );

			// remove all backslashes from string
			$post = stripslashes( $_POST['data'] );

			// Important to decode first before encoding
			$post = json_decode( $post );
			// encode the parsed data
			$data = json_encode( $post );

	        /* Listen for form submission */
	        if ( empty( $data ) ) {
	        	wp_die( __( 'File empty or not found', 'btnsx' ) );
	        }
	        
	        /* Check permissions and nonces */
	        if ( ! current_user_can( 'manage_options' ) ) {
	            wp_die( __( 'You do not have sufficient permissions.', 'btnsx' ) );
	        }
	      
	        // If we've made it this far then we can import the data
	        $this->one_click_import( $data );

	        wp_die();
	    }

		/**
		 * Function to output script on settings page
		 * @since  0.1
		 * @return string
		 */
		public function import_jquery() {
			// create nonce
			$import_nonce = wp_create_nonce( 'btnsx-import' );
			$screen = get_current_screen();
		    if ( $screen->id == 'buttons-x_page_buttons-x-import' ) {
				?>
			    <script type="text/javascript">
					jQuery( document ).ready( function( $ ) {
						var json = '';
						$( '#btnsx-click-import' ).on( 'click', function( e ) {
							e.preventDefault();
							var buttons = [];
							$('input[name="btnsx_opt_predefined_style[]"]').each(function(){
								if($(this).is(':checked')){
									buttons.push($(this).val());
								}
							});
							btnText = '<?php _e( "Import", 'btnsx' ); ?>';
							// disble the button to avoid multiple clicks
						  	$( this ).attr( 'disabled', 'disabled' ).html( '<i class="fa fa-refresh fa-spin"></i>' );
						  	var data = {
								'action'	: 'one_click_import',							// wp ajax action
								'security'	: '<?php echo $import_nonce; ?>',			// nonce value created earlier
								'buttons'	: buttons
							};
							// fire ajax
						  	$.post( ajaxurl, data, function( response ) {
						  		console.log( response );
						  		var split = response.split( '|' );
						  		// if nonce fails then not authorized else settings saved
						  		if( response === '-1' ){
							  		toast( '<?php _e( "Not Authorized!", 'btnsx' ); ?>', '#btnsx-click-import', btnText );
						  		} else {
						  			$.each( split, function( i, v ){
						  				if( v != '' ){
						  					setTimeout(function(){ 
						  						toast( v, '#btnsx-click-import', btnText );
						  					}, 800*i );
							  			}
						  			});
						  		}
						  	});
						});
						$('#btnsx_import_upload').on( 'change', function(){
							json = ''; // reset value when file is changed
							fileReader(); // read file
						});
						var btnText = '<?php _e( "Import", 'btnsx' ); ?>';
						function optimizedImport( json, start, finish ) {
							var data = {
								'action'	: 'upload',									// wp ajax action
								'security'	: '<?php echo $import_nonce; ?>',			// nonce value created earlier
								'data'		: json
							};
							if( start == 0 ){
				  				console.log('Import started!');
				  			}
							// fire ajax
						  	$.post( ajaxurl, data, function( response ) {
						  		// var_dump(response);
						  		// if nonce fails then not authorized else settings saved
						  		if( response === '-1' ){
							  		toast( '<?php _e( "Not Authorized!", "btnsx" ); ?>', '#btnsx-submit-import', btnText );
						  		} else {
						  			var timeOut = + start * 800;
						  			response = response.replace( '|', '' );
						  			console.log( response );
						  			setTimeout(function(){ 
				  						Materialize.toast( response, 2000 );
				  						if( start == finish ){
				  							$( '#btnsx-submit-import' ).removeAttr( 'disabled' ).html( btnText );
							  				console.log('Import finished!');
							  			}
				  					}, timeOut );
						  		}
						  	});
						}
						$( '#btnsx-submit-import' ).on( 'click', function( e ) {
							e.preventDefault();
							// disble the button to avoid multiple clicks
						  	if( $('#btnsx_import_upload').get(0).files.length !== 0 ) {
							  	if( json != '' ){
							  		var jsonD = $.parseJSON( json );
							  		try{
								  		var finish = + jsonD.length - 1;
								  		console.log( jsonD.length );
								  		if( jsonD.length == 1 ){
								  			$( this ).attr( 'disabled', 'disabled' ).html( '<i class="fa fa-refresh fa-spin" style="font-size:13px;"></i> Importing a button...' );
								  		} else if( jsonD.length > 1 ) {
											$( this ).attr( 'disabled', 'disabled' ).html( '<i class="fa fa-refresh fa-spin" style="font-size:13px;"></i> Importing ' + jsonD.length + ' buttons...' );
								  		}
								  		$.each( jsonD, function( i, v ){
							  				if( v != '' ){
							  					optimizedImport( JSON.stringify( jsonD[i] ), i, finish );
								  			}
							  			});
								  	}catch(e){
								  		toast( '<?php _e( "Invalid file content.", "btnsx" ); ?>', '#btnsx-submit-import', btnText );
								  	}
								} else {
									toast( '<?php _e( "File not supported.", "btnsx" ); ?>', '#btnsx-submit-import', btnText );
								}
							} else {
								toast( '<?php _e( "File not found.", "btnsx" ); ?>', '#btnsx-submit-import', btnText );
							}
						});
						function fileReader(){
							var btnText = '<?php _e( "Import", 'btnsx' ); ?>';
							//check whether client browser supports File API
							if ( window.FileReader )
							{
						   		var file = $('#btnsx_import_upload')[0].files[0];
							    var fsize = $('#btnsx_import_upload')[0].files[0].size; //get file size
							    var ftype = $('#btnsx_import_upload')[0].files[0].type; // get file type
							    //allow file types
							    switch( ftype )
							    {
							        case 'application/json':
							        break;
							        case 'application/txt':
							        break;
							        case '':
							        break;
							        default:
							        	toast( '<b>' + ftype + '</b> : <?php _e( "Unsupported file type!", 'btnsx' ); ?>', '#btnsx-submit-import', btnText );
							         	return false;
							    }
						       	//Allowed file size is less than 1 MB (1048576 = 1 mb)
						       	if( fsize > 1048576 ) 
						       	{
						       		toast( '<b>' + fsize + '</b> : <?php _e( "File is too big, it should be less than 1 MB.", 'btnsx' ); ?>', '#btnsx-submit-import', btnText );
						         	return false;
						       	} else {
						       		var reader = new FileReader();
							      	// Closure to capture the file information.
							      	reader.onload = function(e) {
							      		// set json variable value
										json = reader.result;
										// console.log(json);
									}
							      	reader.readAsText(file);
							      	return false;
						       	}
							} else {
						       //Error for older unsupported browsers that doesn't support HTML5 File API
						       toast( '<?php _e( "Please upgrade your browser, because your current browser lacks HTML5 File API.", 'btnsx' ); ?>', '#btnsx-submit-import', btnText );
						       return false;
						    }
						}

						/**
					  	 * Dialog box
					  	 * @since  0.1
					  	 * @param  {string}  dialogText text to be displayed inside dialog
					  	 * @param  {string}  buttonText text to be displayed inside button
					  	 * @return {string}
					  	 */
					  	function toast( dlgText, btnId, btnText ){
					  		Materialize.toast( dlgText, 2000, '', function(){
					  			$( btnId ).removeAttr( 'disabled' ).html( btnText );
					  		});
					  	}

					});
				</script>
				<?php
			}
		}

		/**
		 * Check and make sure data is json format
		 * @since  0.1
		 * @param  string    $string
		 * @return boolean
		 */
		public static function isJson( $string ) {
	        json_decode( $string );
	        return ( json_last_error() == JSON_ERROR_NONE );
	    }

	    /**
	     * Check and return decoded json data
	     * @since  0.1
	     * @param  string    $file
	     * @return mixed
	     */
	    public static function parse( $file ) {
	        // Load the json file
	        if( is_file( $file ) ){
	        	$json = file_get_contents( $file );
	        } else {
	        	$json = $file;
	        }
	        $decoded = json_decode( $json );

	        $format = self::isJson( $json );
	        // Is it of json format?
	        if ( $format == false ){
	            wp_die( __( 'There was an error importing the buttons. File content should be in valid "JSON" format.', 'btnsx' ) );
	        } else {
	            return $decoded;
	        }
	    }
	} // Portation Class
}

/**
 *  Kicking this off
 */

$btn_options = new BtnsxPortation();
$btn_options->init();