<?php
defined('ABSPATH') or die('No direct access permitted');
$blockClass["icon"] = "iconProBlock"; 
// $blockOrder[50][] = "icon"; 
 
use MaxButtons\maxBlocks  as maxBlocks;
use MaxButtons\maxField   as maxField;
	
class iconProBlock extends iconBlock 
{

	public function parse_css($css, $mode = 'normal') 
	{

		$data = $this->data[$this->blockname]; 

		$csspart = 'mb-icon'; 
		$csspseudo = 'normal'; 
		
		$css = parent::parse_css($css); 

		$position = $data["icon_position"]; 
		$use_fa_icon = $data["use_fa_icon"]; 
		
		if ($position == "background")
		{
			//unset($css[$csspart][$csspseudo]['background']);
			unset($css[$csspart][$csspseudo]["text-align"]); 
			$css[$csspart][$csspseudo]['position'] = 'absolute'; 
			$css[$csspart][$csspseudo]['box-sizing'] = 'border-box';
			if ($use_fa_icon == 1)
			{
			
			}
			else
			{
				
				$css[$csspart][$csspseudo]['background-image'] = 'url(' . $data["icon_url"] . ')'; 
				$css[$csspart][$csspseudo]['background-repeat'] = 'no-repeat'; 
				$css[$csspart][$csspseudo]['background-position'] = $data["icon_padding_left"] . 'px ' . $data["icon_padding_top"] . 'px' ;
  				$css[$csspart][$csspseudo]['padding'] = '0'; 
  			}
			

			$css[$csspart][$csspseudo]['width']= '100%';
			$css[$csspart][$csspseudo]['height']= '100%';			
 		}

		return $css;
	}
	
 	public function parse_button($domObj, $mode = 'normal')
 	{
 		$data = $this->data[$this->blockname]; 
		$id = $this->data["id"]; 
 
 		$icon_id = isset($data['icon_id']) ? $data['icon_id'] : 0; 

		$icon_url = $data["icon_url"]; 
		$use_fa_icon= $data["use_fa_icon"]; 
		$position = $data["icon_position"]; 
		
		$icon_post = null;
		if ( $icon_id > 0) 
		{
			$icon_post = get_post($icon_id); 
		}

		if ($icon_id == 0 && $icon_url == '' && ($use_fa_icon == 0 || $use_fa_icon == '') ) return $domObj; // no icon
 
		$anchor = $domObj->find("a",0); 
 		$anchor_text = ''; 
 		
		if ($use_fa_icon == 1) 
		{
			if ($data["fa_icon_value"] == '') return $domObj; // still no icon 
		 	$anchor_text = '<span class="mb-icon  "><i class="fa ' . $data["fa_icon_value"] . '"></i></span>';
		}
		elseif ($position == 'background') 
		{
			$anchor_text = '<span class="mb-icon"></span>'; 
		}
		elseif($icon_id > 0 && ! is_null($icon_post) ) 
		{
			$data = $icon_post;
			$icon_title = $data->post_title;
			$icon_alt = get_post_meta( $icon_id, '_wp_attachment_image_alt', true ); 
			 
			$data = wp_get_attachment_image_src($icon_id, 'full'); 
			$src = $data[0]; 
			$width = $data[1]; 
			$height = $data[2]; 
			
			$anchor_text = '<span class="mb-icon  "><img src="' . $src . '"';

			if ($icon_alt != '')
			 $anchor_text .= ' alt="' . $icon_alt . '"'; 
	
			if ($icon_title != '') 
			 $anchor_text .= ' title="' . $icon_title . '"';
	
			$anchor_text .= ' width="' . $width . '" height="' . $height . '" border="0" /></span>' ; 			
		}
		else // Required for importing button packs
		{
			$anchor_text = '<span class="mb-icon"><img src="' . $data["icon_url"] . '" alt="' . $data["icon_alt"] . '" border="0" /></span>' ; 
		}  	
		if ($position == 'bottom')
			$anchor->innertext = $anchor->innertext . $anchor_text;		 
		else
			$anchor->innertext = $anchor_text . $anchor->innertext;

		$newhtml = $domObj->save(); 
		
		$domObj =  new simple_html_dom(); 
		$domObj->load($newhtml);

 		return $domObj; 
 		
 	}
 	
 	
	public function save_fields($data, $post)
	{	
		// icon class is MBF placeholder that doesn't save info, so call the main class to enable saving. 
		return maxBlock::save_fields($data, $post); 
		
	}
 	
	public function map_fields($map)
	{
		
		//$map["url"]["attr"] = "href"; 
		$map["icon_url"]["func"] = "updateIcon"; 
		$map["fa_icon_size"]["func"] = "updateIcon"; 
		$map["icon_position"]["func"] = "updateIcon"; 		
		$map["icon_padding_top"]["func"] = "updateIcon"; 
		$map["icon_padding_bottom"]["func"] = "updateIcon"; 
		$map["icon_padding_left"]["func"] = "updateIcon"; 
		$map["icon_padding_right"]["func"] = "updateIcon"; 						
		return $map; 
	}
	
	protected function getFAIcons() 
	{
 
 		$dir =  MB()->get_plugin_path() . "assets/libraries/font-awesome"; 
		 
		$icon_list = array(); 
		
		$font_vars = file_get_contents($dir . '/_variables.scss');
		$pos = strpos($font_vars, '$fa-var');

		// Filter the string and return only the icon class names
		$font_vars = substr($font_vars, $pos);

		// Create an array of lines
		$lines = explode("\n", $font_vars);
			$fonts_list = array();
		foreach($lines as $line) {
				// Discard any black line or anything without :
			if(strpos($line, ':') !== false) {
				// Icon names and their Unicode Private Use Area values are separated with : and hence, explode them.
				$t = explode(":", $line);

				// Remove the $fa-var with fa, to use as css class names.
				$class = str_replace('$fa-var', 'fa', $t[0]); 
				$name = $this->getFAIconName($class);
				$fonts_list[$class] = $name;
			}
		}
 
 		return $fonts_list;
	
	}

    protected function getFAIconName($class)
    {
        // Remove Prefix
        $name = substr($class, strlen('fa') + 1);

        // Convert Hyphens to Spaces
        $name = str_replace('-', ' ', $name);

        // Capitalize Words
        $name = ucwords($name);

        // Show Directional Variants in Parenthesis
        $directions = array('/up$/i', '/down$/i', '/left$/i', '/right$/i');
        $directionsFormat = array('(Up)', '(Down)', '(Left)', '(Right)');
        $name = preg_replace($directions, $directionsFormat, $name);

        // Use Word "Outlined" in Place of "O"
        $outlinedVariants = array('/\so$/i', '/\so\s/i');
        $name = preg_replace($outlinedVariants, ' Outlined ', $name);

        // Remove Trailing Characters
        $name = trim($name);

        return $name;
    }	
	
	public function admin_fields() 
	{
		//parent::admin_fields();
 
		$data = $this->data[$this->blockname]; 

 
/*		foreach($this->fields as $field => $options)
		{		
 	 	    $default = (isset($options["default"])) ? $options["default"] : ''; 
			${$field} = (isset($data[$field])) ? $data[$field] : $default;
			${$field  . "_default"} = $default; 
		}
*/		
//		global $mbpro_icon_positions; 	


?>	

     <div class='maxmodal-data' id='view-icons' data-width='800px'>
        	<span class='title'> <?php _e("Icons and Images","maxbuttons-pro"); ?></span>
        	<span class='content'>
            	<div class="font-awesome">
            		<?php  $icon_list = $this->getFAIcons(); ?> 
               		<h4>
               		 <?php printf(__("Choose from %d icons, ordered alphabetically","maxbuttons-pro"), count($icon_list)); ?>	                					</h4>            
               			    <ul class="icon-list">
                            <?php
                             foreach($icon_list as $icon => $name) {
                                echo '<li><i  title=' . $name . ' data-mbicon="'.$icon.'" class="fa '.$icon.'"></i>
                                	</li>';
                            } 
                            unset($icon_list);
                            ?>
                        </ul>
                    </div>
             </span>
			<div class='controls'><p><button type='button' class='button-primary modal_close'><?php _e("Close","maxbuttons-pro"); ?></button>
			</p></div>			
      </div>
      	
		<div class="option-container">
				<div class="title"><?php _e('Icons and images', 'maxbuttons-pro') ?></div>
				<div class="inside">
<?php
		$use_fa = new maxField('switch'); 
		$use_fa->name = 'use_fa_icon'; 
		$use_fa->id = $use_fa->name; 
		$use_fa->value = '1'; 
		$use_fa->checked = checked(maxBlocks::getValue('use_fa_icon'), 1, false); 
		$use_fa->inputclass = 'fa_switch'; 
		$use_fa->label = __('Use Image', 'maxbuttons-pro');
		
		$use_fa->output('start',''); 
		
		$ispacer = new maxfield('spacer'); 
		$ispacer->label = __('Use Font Awesome Icon','maxbuttons-pro'); 
		$ispacer->output('','end'); 

		$condition = array('target' => 'use_fa_icon', 'values' => 'checked'); 
		$faicon_active = htmlentities(json_encode($condition)); 
				
		$condition = array('target' => 'use_fa_icon', 'values' => 'unchecked'); 
		$image_active = htmlentities(json_encode($condition)); 		
		
		$fa_button = new maxField('button'); 
		$fa_button->label = '&nbsp;';
		$fa_button->button_label = __("Select Icon","maxbuttons-pro");
		$fa_button->name =  'select_icon'; 
		$fa_button->id = $fa_button->name; 
		$fa_button->modal = 'view-icons'; 
		$fa_button->inputclass = 'maxmodal'; 
		$fa_button->start_conditional = $faicon_active;
		$fa_button->output('start','end'); 

		$fa_icon_value = maxBlocks::getValue('fa_icon_value'); 
		
		$fa_icon_preview = new maxField('generic');
		$fa_icon_preview->id = 'icon_preview'; 
		$fa_icon_preview->label = '&nbsp;'; 
		$fa_icon_preview->name = 'fa_preview'; 
		$fa_icon_preview->content = "                  
                            <div class='fa-only font-awesome-preview'> 
                            <i class='fa $fa_icon_value '></i>
                            <div class='remove_fa_icon'>" . __('remove','maxbuttons-pro') . "</div>
                            </div>"; 
        $fa_icon_preview->start_conditional = $faicon_active; 
        $fa_icon_preview->output('start',''); 
                   
		$fa_icon = new maxField('hidden'); 
		$fa_icon->id = 'fa_icon_value'; 
		$fa_icon->name = $fa_icon->id; 
		$fa_icon->value = $fa_icon_value; 
		$fa_icon->output('','end'); 

		$icon_size = new maxField('number');
		$icon_size->id = 'fa_icon_size'; 
		$icon_size->name = $icon_size->id; 
		$icon_size->value = maxUtils::strip_px(maxBlocks::getValue('fa_icon_size')); 
		$icon_size->label = __('Icon Size', 'maxbuttons-pro'); 
		$icon_size->min = 5; 
		$icon_size->inputclass = 'tiny'; 
		$icon_size->start_conditional = $faicon_active;
		$icon_size->output('start','end'); 
	
		// Icon Color
		$color = new maxField('color'); 
		$color->id = 'icon_color'; 
		$color->name = $color->id; 
		$color->value = maxBlocks::getColorValue('icon_color'); 
		$color->label = __('Icon Color','maxbuttons'); 
		$color->copycolor = true; 
		$color->bindto ='icon_color_hover'; 
		$color->copypos = 'right'; 
		$color->start_conditional = $faicon_active; 
		$color->output('start'); 

		// Icon Color Hover
		$hcolor = new maxField('color'); 
		$hcolor->id = 'icon_color_hover'; 
		$hcolor->name = $hcolor->id; 
		$hcolor->value = maxBlocks::getColorValue('icon_color_hover'); 
		$hcolor->label = __('Hover','maxbuttons'); 
		$hcolor->copycolor = true; 
		$hcolor->bindto ='icon_color'; 
		$hcolor->copypos = 'left'; 
		$hcolor->output('', 'end');             	
	
//**Icon section. 		
		$icon_id =	maxBlocks::getValue('icon_id'); 
		$icon_url = maxBlocks::getValue('icon_url'); 
		$icon_alt = maxBlocks::getValue('icon_alt'); 	
		
?>
					<div class="option-design use-image non-fa" data-show="<?php echo $image_active ?>">
						<div class="label"><?php _e('Image', 'maxbuttons-pro') ?></div>
						<div class="input">
							<input type="hidden" name="icon_id" id='icon_id' value="<?php echo $icon_id ?>" /> 
							<input type="hidden" id="icon_url" name="icon_url" value="<?php echo $icon_url ?>" />
							<span class='icon_preview' id='icon_url_preview'>
							<?php 
							if (isset($icon_url) && $icon_url != '') 
								echo "<img src='$icon_url'>"; 
							elseif ($icon_id > 0) 
							{	
								$icon = wp_get_attachment_metadata( $attachment_id );

							}
							?>
							<span class='remove_icon dashicons dashicons-dismiss'></span>
							</span>
							<?php 
								$icon_title = ''; 
								$icon_alt = ''; 
								$filename = ''; 
							if ($icon_id > 0)
							{
									$data = get_post($icon_id);
									$icon_title = $data->post_title;
									$icon_alt = get_post_meta( $icon_id, '_wp_attachment_image_alt', true ); 
									$data = wp_get_attachment_image_src($icon_id, 'full'); 
									$filename = basename($data[0]); 
									$width = $data[1]; 
									$height = $data[2]; 
							}
							?>
							<span class='icon_data'>
								<label><?php _e("File Name","maxbuttons-pro"); ?></label>
								<span class='filename'><?php echo $filename ?></span>
								<label><?php _e("Alt","maxbuttons-pro"); ?></label>
								<span class='alt'><?php echo $icon_alt ?></span>
								<label><?php _e("Title","maxbuttons-pro"); ?></label>
								<span class='atttitle'><?php echo $icon_title ?></span>

							</span>
							
							<input type="button" class="button" id="icon_url_button" name="icon_url_button" value="<?php _e('Select...', 'maxbuttons-pro') ?>" />
						
						</div>
						<div class="clear"></div>
					</div>

					<?php

				$icon_positions = array(
					'' => '',
					'left' => __('Left of text','maxbuttons-pro'), 
					'right' => __('Right of text', 'maxbuttons-pro'), 
					'top' => __('Top of text','maxbuttons-pro'), 
					'bottom' => __('Bottom of text','maxbuttons-pro'), 
					'background' => __('As background','maxbuttons-pro'), 
			); 
						
				$position = new maxField('generic');
				$position->label = __('Position','maxbuttons-pro'); 
				$position->id = 'icon_position'; 
				$position->name = $position->id; 
				$position->value = maxBlocks::getValue('icon_position'); 
				$position->content = maxUtils::selectify($position->name, $icon_positions, $position->value);
				$position->output('start','end');


				$condition = array('target' => 'icon_position', 'values' => array('left','right', 'top') ); 
						$padding_conditional = htmlentities(json_encode($condition));	 
					
										
				$icon_url = MB()->get_plugin_url() . 'images/icons/' ; 	
						
				$ptop = new maxField('number'); 
				$ptop->id = 'icon_padding_top';
				$ptop->name = $ptop->id;
				$ptop->min = 0; 
			 	$ptop->inputclass = 'tiny';
				$ptop->value = maxUtils::strip_px(maxBlocks::getValue('icon_padding_top') ); 
				$ptop->label = __("Padding","maxbuttons-pro");
	 			$ptop->before_input = '<img src="' . $icon_url . 'p_top.png" title="' . __("Padding Top","maxbuttons") . '" >';			
				$ptop->output('start'); 

		 		$pright = new maxField('number'); 
		 		$pright->id = 'icon_padding_right';
		 		$pright->name = $pright->id; 
				$pright->min = 0;
		 		$pright->inputclass = 'tiny'; 
		 		$pright->before_input = '<img src="' . $icon_url . 'p_right.png" class="icon padding" title="' . __("Padding Right","maxbuttons") . '" >'; 
		 		$pright->value = maxUtils::strip_px(maxBlocks::getValue('icon_padding_right')); 
		 		$pright->output();	 			 				 			 					 					 		

		 		$pbottom = new maxField('number'); 
		 		$pbottom->id = 'icon_padding_bottom';
		 		$pbottom->name = $pbottom->id; 
				$pbottom->min = 0; 
		 		$pbottom->inputclass = 'tiny'; 
		 		$pbottom->before_input = '<img src="' . $icon_url . 'p_bottom.png" class="icon padding" title="' . __("Padding Bottom","maxbuttons") . '" >'; 			 
		 		$pbottom->value = maxUtils::strip_px(maxBlocks::getValue('icon_padding_bottom')); 
		 		
		 		$pbottom->output();

			 	$pleft = new maxField('number'); 
		 		$pleft->id = 'icon_padding_left';
		 		$pleft->name = $pleft->id; 
				$pleft->min = 0; 
		 		$pleft->inputclass = 'tiny'; 
		 		$pleft->before_input = '<img src="' . $icon_url . 'p_left.png" class="icon padding" title="' . __("Padding Left","maxbuttons") . '" >'; 
		 		$pleft->value = maxUtils::strip_px(maxBlocks::getValue('icon_padding_left')); 
		 		
		 		$pleft->output('','end');	
			 	
				?>

					<?php /* work in progress.. <div class="option-design ">
						<div class="label"><?php _e('Background Image', 'maxbuttons-pro') ?></div>
						<div class="input">
							<input type="text" id="background_url" name="background_url" value="<?php echo esc_attr($background_url) ?>" />
							<input type="button" class="button" id="background_url_button" name="background_url_button" value="<?php _e('Select...', 'maxbuttons-pro') ?>" />
						</div>
						<div class="clear"></div>
					</div>		 */
				?>	
					
				</div> <!-- inside -->
			</div>

<?php
	} // admin_fields
} // class

?>
