<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class is for rendering HTML sub body blocks.
 *
 * It will provide a header, body and footer.
 *
 * @package    lnApp
 * @category   lnApp/Helpers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 * @uses       Style
 */
class lnApp_Block_Sub extends HTMLRender {
	protected static $_data = array();
	protected static $_spacer = '<table><tr class="spacer"><td>&nbsp;</td></tr></table>';
	protected static $_required_keys = array('body','position');

	/**
	 * Add a block to be rendered
	 *
	 * @param array Block attributes
	 */
	public static function add($block,$prepend=FALSE) {
		parent::add($block);

		// Detect any style sheets.
		if (! empty($block['style']) && is_array($block['style']))
			foreach ($block['style'] as $data=>$media)
				Style::add(array(
					'type'=>'file',
					'data'=>$data,
					'media'=>$media,
				));
	}

	/**
	 * Return an instance of this class
	 *
	 * @return Block
	 */
	public static function factory() {
		return new Block_Sub;
	}

	/**
	 * Render this block
	 *
	 * @see HTMLRender::render()
	 */
	protected function render() {
		$output = '';
		$o = array();

		$i = 0;
		$x = $y = 0;
		Sort::MAsort(static::$_data,'order,position,title,subtitle');
		foreach (static::$_data as $value) {
			$i = (! isset($value['order'])) ? $i+1 : $value['order'];

			// Work out our dimentions
			if ($value['position'] > $y)
				$y = $value['position'];
			if ($i > $x)
				$x = $i;

			// @todo Alert if a sub block has already been defined.
			$o[$i][$value['position']] = '<table class="subblock" border="0">';

			if (! empty($value['title']))
				$o[$i][$value['position']] .= sprintf('<tr class="title"><td>%s</td></tr>',$value['title']);

			if (! empty($value['subtitle']))
				$o[$i][$value['position']] .= sprintf('<tr class="subtitle"><td>%s</td></tr>',$value['subtitle']);

			$o[$i][$value['position']] .= sprintf('<tr class="body"><td>%s</td></tr>',$value['body']);

			if (! empty($value['footer']))
				$o[$i][$value['position']] .= sprintf('<tr class="footer"><td>%s</td></tr>',$value['footer']);

			$o[$i][$value['position']] .= '</table>';
		}

		// Render our output.
		$output .= '<table class="subblockhead">';
		foreach ($o as $k => $v)
			$output .= sprintf('<tr><td style="width: %s%%;">%s</td></tr>',$x=round(100/$y,0),implode(sprintf('</td><td style="width: %s%%;">',$x),$v));
		$output .= '</table>';

		return $output;
	}
}
?>
