<?php
/**
 * @link              https://greentreemediallc.com
 * @since             1.0.0
 * @wordpress-plugin
 * Plugin Name:       Divi Icon King
 * Description:       Add almost 2000 icons to the Divi Builder UI from Font Awesome and Material Design. Features a built in filter so you can find the icon you're looking for quickly. Buckle up, buddy.
 * Plugin URI:	      http://divi-icon-plugin.com/
 * Version:           2.1.2
 * Author:            Alex Brinkman
 * Author URI:        https://greentreemediallc.com
 * Text Domain:       divi-icon-king-gtm
 * Domain Path:       /languages
 */

if ( ! defined( 'WPINC' ) ) die;

// Constants.
define( 'VERSION_DIKG', '2.1.2' );
define( 'OPTION_NAME_DIKG', 'dikg_settings' );
define( 'PLUGIN_SLUG_DIKG', 'divi-icon-king-gtm' );
define( 'SETTINGS_PAGE_DIKG', 'divi_icon_king_gtm_settings' );
define( 'MARKETPLACE_DIKG', '' );

add_filter( 'plugin_action_links', 'add_action_links_dikg', 10, 5 );
add_filter( 'dikg_filter_front_icon', 'front_icon_filter_dikg' );
add_filter( 'script_loader_tag', 'no_rocketscript_dikg', 10, 3 ); // No RocketScript

add_action( 'init', 'iconsplosion_dikg' );
add_filter( 'body_class', 'custom_public_class_dikg' );
add_filter( 'admin_body_class', 'custom_admin_class_dikg' );
add_action( 'wp_ajax_vb_fetch_icons_dikg', 'vb_fetch_icons_dikg' );

// Elegant Marketplace EDD Auto Updater.
if( MARKETPLACE_DIKG === 'emp')
	add_action( 'admin_init', 'marketplace_plugin_updater_dikg', 0 );

// Admin pages.
add_action( 'admin_init', 'setup_sections_dikg' );
add_action( 'admin_init', 'setup_fields_dikg' );
add_action( 'admin_menu', 'admin_menu_dikg' );

// Load the script on both the admin and public.
add_action( 'init', 'register_assets_dikg');
add_action( 'admin_enqueue_scripts', 'enqueue_admin_assets_dikg' );
add_action( 'admin_enqueue_scripts', 'enqueue_public_assets_dikg' );

add_action( 'wp_enqueue_scripts', 'enqueue_public_assets_dikg' );

function custom_public_class_dikg( $classes ) {
	$classes[] = 'divi-icon-king';
	return $classes;
}

function custom_admin_class_dikg( $classes ) {
	$classes .= 'divi-icon-king';
	return $classes;
}

function marketplace_plugin_updater_dikg() {
	if ( is_admin() ) :
		define( 'DIKG_PLUGIN_FILE', __FILE__ );
		define( 'PRODUCT_NAME_DIKG', 'Divi Icon King');
    define( 'PRODUCT_ID_DIKG', 402061);
    define( 'PRODUCT_AUTHOR', 'Alex Brinkman'); 
		require_once('update/emp_dikg_lic.php'); 
	endif;
}

/**
 * Filter plugin action links.
 *
 * @since    1.0.0
 */
function add_action_links_dikg( $actions, $plugin_file ) {
	static $plugin;

	if ( ! isset( $plugin ) )
		$plugin = plugin_basename(__FILE__);
	
	if ($plugin == $plugin_file) :

		$settings = array('settings' => '<a href="options-general.php?page=' . SETTINGS_PAGE_DIKG . '">' . __('Settings', 'General') . '</a>');
		$site_link = array('support' => '<a href="http://alexbrinkman.org/product-support/" target="_blank">Support</a>');
		
    $actions = array_merge($settings, $actions);
		$actions = array_merge($site_link, $actions);
			
	endif;
		
	return $actions;
}

/**
 * Register plugin assets.
 *
 * @since    2.0.0
 */
function register_assets_dikg()
{
	// Admin.
	wp_register_style( PLUGIN_SLUG_DIKG . '-admin', plugin_dir_url( __FILE__ ) . 'assets/css/' . PLUGIN_SLUG_DIKG . '-admin.css', array(), VERSION_DIKG, 'all'  );

	wp_register_style( PLUGIN_SLUG_DIKG, plugin_dir_url( __FILE__ ) . 'assets/css/' . PLUGIN_SLUG_DIKG . '-font.css', array(), VERSION_DIKG, 'all' );
	wp_register_style( PLUGIN_SLUG_DIKG . '-fontawesome', plugin_dir_url( __FILE__ ) . 'assets/css/font-awesome.min.css', array(), VERSION_DIKG, 'all' );

	wp_register_style(  PLUGIN_SLUG_DIKG . '-icon-filter', plugin_dir_url( __FILE__ ) . 'assets/css/' . PLUGIN_SLUG_DIKG . '-icon-filter.css', array(), VERSION_DIKG, 'all'  );
	wp_register_script( PLUGIN_SLUG_DIKG . '-icon-filter', plugin_dir_url( __FILE__ ) . 'assets/js/divi-icon-king-gtm-icon-filter.js', array( 'jquery' ), VERSION_DIKG, true );
	
	wp_register_script( PLUGIN_SLUG_DIKG,  plugin_dir_url( __FILE__ ) . 'assets/js/' . PLUGIN_SLUG_DIKG . '.js', array('jquery'), VERSION_DIKG, true );
}

/**
 * Enqueue the admin assets.
 *
 * @since    1.4.0
 */
function enqueue_admin_assets_dikg( $hook ) {
	if( $hook === 'settings_page_' . SETTINGS_PAGE_DIKG ) :
		wp_enqueue_style( PLUGIN_SLUG_DIKG . '-admin' );
	endif;

	wp_enqueue_style( PLUGIN_SLUG_DIKG . '-icon-filter' );
}

/**
 * Enqueue the public assets.
 *
 * @since    2.0.0
 */
function enqueue_public_assets_dikg()
{
	wp_enqueue_style(  PLUGIN_SLUG_DIKG . '-icon-filter' );
	wp_enqueue_script( PLUGIN_SLUG_DIKG . '-icon-filter' );

	wp_enqueue_style(  PLUGIN_SLUG_DIKG );

	// If we need to load in the default FA classes.
	$settings = get_option( OPTION_NAME_DIKG );
	$enable_fa_css	= isset( $settings['enable_fa_css'] ) ? trim( $settings['enable_fa_css'] ) : false;
	if( $enable_fa_css ) wp_enqueue_style( PLUGIN_SLUG_DIKG . '-fontawesome' );

	if( is_user_logged_in() ) :

		wp_enqueue_script( PLUGIN_SLUG_DIKG );

	  $ajax_params = array(
		  'ajax_url' => admin_url( 'admin-ajax.php' ), 
		  'nonce' => wp_create_nonce( 'fetch_icons_nonce' ) 
	  );
		wp_localize_script( PLUGIN_SLUG_DIKG, 'ajax_params', $ajax_params );

	endif;
}

/**
 * Register the admin menu.
 *
 * @since    1.0.0
 */
function admin_menu_dikg()
{
	add_submenu_page(
		'options-general.php',		// parent slug
		'Divi Icon King',			// page title
		'Divi Icon King',			// menu title
		'manage_options',			//capability
		SETTINGS_PAGE_DIKG,				// slug
		'dikg_settings_page' 		// callback 
	);
}

/**
 * Generate the admin settings page.
 *
 * @since    1.0.0
 */
function dikg_settings_page()
{
	$license = trim( get_option( 'dikg_license_key' ) );
	$status = trim( get_option( 'dikg_license_status' ) );
	settings_errors( 'settings_messages' );
	?>
	    
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

		<section id="post-body" class="metabox-holder columns-2 gtm_plugin_settings__section">
		
			<form method="post" action="options.php" class="gtm_plugin_settings__form">

				<?php if( MARKETPLACE_DIKG && MARKETPLACE_DIKG === 'emp' ) : ?>
				<div class="gtm_plugin_settings">
					<table class="form-table">
						<tbody>
							<tr valign="top">
								<th scope="row" valign="top">
									<?php _e('License Key'); ?>
								</th>
								<td>
									<input id="dikg_license_key" name="dikg_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $license ); ?>" />
									<p class="description" for="dikg_license_key"><?php _e('Enter your license key'); ?></p>
								</td>
							</tr>
						<?php if( false !== $license ) { ?>
							<tr valign="top">
								<th scope="row" valign="top">
									<?php _e('Activate License'); ?>
								</th>
								<td>
									<?php if( $status && $status == 'valid' ) { ?>
										<span class="dikg_license_status dikg_license_status--active"><?php _e('License: Active'); ?></span>
										<?php wp_nonce_field( 'dikg_nonce', 'dikg_nonce' ); ?>
										<input type="submit" class="button-secondary" name="dikg_deactivate" value="<?php _e('Deactivate License'); ?>"/>
									<?php } else {
										wp_nonce_field( 'dikg_nonce', 'dikg_nonce' ); ?>
										<input type="submit" class="button-secondary" name="dikg_activate" value="<?php _e('Activate License'); ?>"/>
									<?php } ?>
								</td>
							</tr>
						<?php } ?>
						</tbody>
					</table>
				</div>
				<?php // If MARKETPLACE_DIKG END.
				endif; ?>

				<div class="gtm_plugin_settings">
					<?php
					settings_fields( SETTINGS_PAGE_DIKG );    
          do_settings_sections( SETTINGS_PAGE_DIKG );
					submit_button();
					?>
				</div>

			</form>
		</section>
		<footer class="gtm_plugin_settings__footer">
			<p>Built with <span class="dashicons dashicons-heart"></span> by Alex Brinkman over at Green Tree Media. Have a great day!</p>
			<p>If this plugin made your life just a little easier, <a href="greentreemediallc.com/twitter" target="_blank">tweet at me</a> and let me know!</p>
		</footer>
	</div><!-- /.wrap -->
	<?php
}

function setup_sections_dikg()
{
	add_settings_section( 'divi_icon_king_settings', '', 'dikg_section_callback', SETTINGS_PAGE_DIKG );
	add_settings_section( 'divi_icon_king_css', '', 'dikg_section_callback', SETTINGS_PAGE_DIKG );
}

function dikg_section_callback( $arguments )
{
	switch( $arguments['id'] ) :
		case 'divi_icon_king_settings':
			echo '<p>Choose the icon fonts you\'d like to use. <strong>You can access the icons directly in the Divi Builder</strong>.</p>';
		break;
		case '<p>Additional CSS</p>';
		break;
	endswitch;
}
    
function setup_fields_dikg()
{
  // Our main setting we'll be saving our settings under.
	register_setting( SETTINGS_PAGE_DIKG, OPTION_NAME_DIKG );
	register_setting( SETTINGS_PAGE_DIKG, 'dikg_license_key' );
        
	$settings = get_option( OPTION_NAME_DIKG );
	
	$enable_fontawesome = isset( $settings['enable_fontawesome'] ) ? trim( $settings['enable_fontawesome'] ) : false;
	$enable_material	= isset( $settings['enable_material'] ) ? trim( $settings['enable_material'] ) : false;
	$enable_fa_css	= isset( $settings['enable_fa_css'] ) ? trim( $settings['enable_fa_css'] ) : false;
                    
    $fields = array(
		array(
	    	'uid' 				=> 'enable_fontawesome',
		    'label' 			=> 'Enable Font Awesome',
		    'section' 			=> 'divi_icon_king_settings',
			'type' 				=> 'checkbox',
			'is_toggle'			=> true,
		    'options' 			=> false,
		    'placeholder' 		=> '',
		    'helper' 			=> '',
		    'supplemental' 		=> '',
		    'default' 			=> $enable_fontawesome
	    ),
	    array(
	    	'uid' 				=> 'enable_material',
		    'label' 			=> 'Enable Material Icons',
		    'section'	 		=> 'divi_icon_king_settings',
			'type' 				=> 'checkbox',
			'is_toggle'			=> true,
		    'options' 			=> false,
		    'placeholder' 		=> '',
		    'helper' 			=> '',
		    'supplemental' 		=> '',
		    'default' 			=> $enable_material
			),
			array(
	    	'uid' 				=> 'enable_fa_css',
		    'label' 			=> 'Load FontAwesome CSS classes?',
		    'section'	 		=> 'divi_icon_king_settings',
			'type' 				=> 'checkbox',
			'is_toggle'			=> true,
		    'options' 			=> false,
		    'placeholder' 		=> '',
		    'helper' 			=> '',
		    'supplemental' 		=> 'This loads in the original Font Awesome classes so you can use them in custom HTML. For example, enabling this will allow you to use original Font Awesome classes like \'<strong>fa fa-home</strong>\' to show the house icon.',
		    'default' 			=> $enable_fa_css
		  ),
    );
	   
	foreach( $fields as $field ) :
	        
	    add_settings_field(
	        $field['uid'],
	        $field['label'],          
	        'dikg_field_callback',
	        SETTINGS_PAGE_DIKG,
	        $field['section'],
	        $field
	    );
	        
	endforeach;
}

function dikg_field_callback( $arguments )
{
	$option_name = OPTION_NAME_DIKG;
  $value = isset( $arguments['default'] ) ? $arguments['default'] : '';

	// Check which type of field we want
    switch( $arguments['type'] ) :
    	
    	case 'checkbox': // If it is a checkbox field
				if( isset( $arguments['is_toggle'] ) && $arguments['is_toggle'] ) :
					printf( '<input name="%4$s[%1$s]" id="%1$s" type="%2$s" class="tgl tgl-flat" %3$s /><label class="tgl-btn" for="%1$s"></label>', $arguments['uid'], $arguments['type'], ( ( $value == 'on' ) ? 'checked' : ''), $option_name  );
				else :
					printf( '<input name="%4$s[%1$s]" id="%1$s" type="%2$s" %3$s />', $arguments['uid'], $arguments['type'], ( ( $value == 'on' ) ? 'checked' : ''), $option_name );
				endif;
			break;
	        
	    case 'text': // If it is a text field
		    printf( '<input name="%5$s[%1$s]" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" />', $arguments['uid'], $arguments['type'], $arguments['placeholder'], $value, $option_name );
		break;
		    
		case 'number': // If it is a number field
		    printf( '<input name="%5$s[%1$s]" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" />', $arguments['uid'], $arguments['type'], $arguments['placeholder'], $value, $option_name );
		break;
	        
	    case 'textarea': // If it is a textarea
		    printf( '<textarea name="%4$s[%1$s]" id="%1$s" placeholder="%2$s" rows="5" cols="50">%3$s</textarea>', $arguments['uid'], $arguments['placeholder'], $value, $option_name );
		break;
	        
	    case 'select': // If it is a select dropdown
		        
		    if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ) :
			        
			    $options_markup = '';
			        
			    foreach( $arguments['options'] as $key => $label ) :
				    $options_markup .= sprintf( '<option value="%s" %s>%s</option>', $key, selected( $value, $key, false ), $label );
			    endforeach;
			        
			    printf( '<select name="%3$s[%1$s]" id="%1$s">%2$s</select>', $arguments['uid'], $options_markup, $option_name );
		       
		    endif;
		        
		break;
		    
    endswitch;

	// If there is help text
    if( $helper = $arguments['helper'] ) :
        printf( '<span class="helper"> %s</span>', $helper );
	endif;
	
	// If there is a tooltip
	if( $tooltip = isset( $arguments['tooltip'] ) ? $arguments['tooltip'] : false ) :
		printf( '<a href="#" class="gtm-tooltip" data-tooltip="%s"><span class="dashicons dashicons-editor-help"></span></a>', $tooltip );
	endif;

	// If there is supplemental text
  if( $supplimental = $arguments['supplemental'] ) :
    printf( '<p class="description">%s</p>', $supplimental );
  endif;
}

function iconsplosion_dikg()
{
	$settings = get_option( OPTION_NAME_DIKG );
	
	$enable_fontawesome = isset( $settings['enable_fontawesome'] ) ? trim( $settings['enable_fontawesome'] ) : false;
	$enable_material	= isset( $settings['enable_material'] ) ? trim( $settings['enable_material'] ) : false;

	//Add new structured ET icons to the divi builder so we can filter them.
	add_filter('et_pb_font_icon_symbols', 'et_icons_dikg', 20 );
	
	if( $enable_fontawesome ) :
	  add_filter('et_pb_font_icon_symbols', 'fontawesome_icons_dikg', 25 );
	endif;
	
	if( $enable_material ) :
		add_filter('et_pb_font_icon_symbols', 'material_icons_dikg', 30);
	endif;
}

/**
 * Add structured ET icons to Divi.
 *
 * @since    1.0.0
 */
function et_icons_dikg( $icons )
{			
	// Ditch the original icons. Deuces.
	$icons = [];
	
	include( plugin_dir_path( __FILE__ ) . 'assets/elegantthemes.php' );
	
	foreach( $elegantthemes_icons as $icon ) :
		$icons[] = $icon['unicode'];
	endforeach;

	return $icons;
}
		
/**
 * Add Font Awesome icons to Divi.
 *
 * @since    1.0.0
 */
function fontawesome_icons_dikg( $icons )
{	
	include( plugin_dir_path( __FILE__ ) . 'assets/fontawesome.php' );
	
	foreach( $fontawesome_icons as $icon ) :
		$icons[] = $icon['unicode'];
	endforeach;
			
  return $icons;
}

/**
 * Add Material icons to Divi.
 *
 * @since    1.0.0
 */
function material_icons_dikg( $icons )
{	
	include( plugin_dir_path( __FILE__ ) . 'assets/material.php');
	
	foreach( $material_icons as $icon ) :
		$icons[] = $icon['unicode'];
	endforeach;
	
  return $icons;
}

/**
 * Overwrites the same function in Divi's functions.php file. 
 * Identify the new icons in the divi builder so we can handle 
 * them accordingly.
 * 
 * This function only runs on the classic back end builder/ WP Customizer.
 *
 * @since 1.0.0
 */
if ( ! function_exists( 'et_pb_get_font_icon_list_items' ) ) :
	
	function et_pb_get_font_icon_list_items()
	{
		$settings = get_option( OPTION_NAME_DIKG );
	
	  $enable_fontawesome = isset( $settings['enable_fontawesome'] ) ? trim( $settings['enable_fontawesome'] ) : false;
	  $enable_material	= isset( $settings['enable_material'] ) ? trim( $settings['enable_material'] ) : false;

		$output = '';
		
		// Only the WP customizer needs this function.
		if( is_customize_preview() ) :
			$symbols = et_pb_get_font_icon_symbols();
		endif;
		
		$filter_triggers = [];
		$the_icons = [];

		include( plugin_dir_path( __FILE__ ) . 'assets/elegantthemes.php' );
		foreach( $elegantthemes_icons as $icon ) :
			$the_icons[] = $icon;
		endforeach;
		unset( $icon );

		if( $enable_fontawesome ) :
			include( plugin_dir_path( __FILE__ ) . 'assets/fontawesome.php' );
			foreach( $fontawesome_icons as $icon ) :
				$the_icons[] = $icon;
			endforeach;
			unset( $icon );
		endif;

		if( $enable_material ) :
			include( plugin_dir_path( __FILE__ ) . 'assets/material.php' );
			foreach( $material_icons as $icon ) :
				$the_icons[] = $icon;
			endforeach;
			unset( $icon );
		endif;
													
		foreach ( $the_icons as $icon ) :
				
			if(! in_array(esc_attr($icon['family']), $filter_triggers) ) :
				$filter_triggers[] = $icon['family'];
			endif;

			$output .= sprintf(
				'<li data-name=\'%1$s\' title=\'%1$s (%3$s)\' data-icon=\'%2$s\' data-family=\'%3$s\' data-terms=\'%4$s\' class="divi-icon-king-gtm divi-icon-king-gtm--%3$s"></li>',
				$icon['name'],
				$icon['unicode'],
				$icon['family'],
				$icon['terms']
			);			

		endforeach;
		unset( $icon );

		$output .= '</ul>
		<div class="dikg_icon_filter dikg_icon_filter--closed">
		<span class="dikg_icon_filter__btn dikg_icon_filter--visible">Search Icons</span>
		<div class="dikg_icon_filter__controls dikg_icon_filter--hidden">';
				
			if( $filter_triggers ) :
				foreach( $filter_triggers as $trigger ) :
					$output .= sprintf(
						'<span class="dikg_icon_filter__control_option dikg_icon_filter__control_family" data-value="%1$s">%1$s</span>',
						$trigger
					);
				endforeach;
				unset( $trigger );
			endif;

			$output .=
			'<span class="dikg_icon_filter__control_option dikg_icon_filter__control_action dikg_icon_filter__all">All</span> 
			<span class="dikg_icon_filter__control_option dikg_icon_filter__control_action dikg_icon_filter__close">Close</span>
		</div>
		</div>';

		return $output;
	}
endif;

function vb_fetch_icons_dikg()
{
	if ( ! check_ajax_referer( 'fetch_icons_nonce', 'nonce' ) ) :
		return false;
	endif;

	$settings = get_option( OPTION_NAME_DIKG );
	$enable_fontawesome = isset( $settings['enable_fontawesome'] ) ? trim( $settings['enable_fontawesome'] ) : false;
	$enable_material	  = isset( $settings['enable_material'] ) ? trim( $settings['enable_material'] ) : false;

	$icons = [];

	include( plugin_dir_path( __FILE__ ) . 'assets/elegantthemes.php' );
	$icons = $elegantthemes_icons;

	if( $enable_fontawesome ) :
		include( plugin_dir_path( __FILE__ ) . 'assets/fontawesome.php');
		$icons = array_merge( $icons, $fontawesome_icons );
	endif;

	if( $enable_material ) :
		include( plugin_dir_path( __FILE__ ) . 'assets/material.php');
		$icons = array_merge( $icons, $material_icons );
	endif;

	header('Content-Type: application/json; charset=UTF-8');
  exit( json_encode($icons) );	
}

/**
 * Tell CloudFlare to ignore RocketScripting my script.
 *
 * @since    1.1.0
 */
function no_rocketscript_dikg( $tag, $handle, $src )
{
  if ( PLUGIN_SLUG_DIKG . '-script' === $handle )  :
    $tag = '<script data-cfasync="false" src="' . esc_url( $src ) . '" ></script>';
  endif;
    
  return $tag;
}