<?php

class h2oView extends Slim_View {
    /**
     * Renders a template using h2o.php.
     *
     * @see View::render()
     * @param string $template The template name specified in Slim::render()
     * @return string
     */
    public function render( $template ) {
		
		if (!is_array($template)) {
			if (strpos($template,"tempe/") === false) 
				$template = Slim::config('templates.path').'/'.$template;
        } else {
			$template = $template['fullpath'];
		}
		
		$page_data = array_merge($this->data,
									array(
										"session"=>$_SESSION,
										"server_time"=>getdate()),
										array("this_page"=>str_replace(Slim::config('templates.path').'/',"",$template))
									);
		
		$h2o = new h2o($template, array("cache"=>false));

		return $h2o->render($page_data);
    }
}

h2o::addFilter('strtotime');
h2o::addFilter('count');
h2o::addFilter('substract');
h2o::addFilter('get_month');
h2o::addFilter('get_day');
h2o::addFilter('format_money');

h2o::addTag('nav');
h2o::addTag('date');
h2o::addTag('combobox');

function format_money($int){
    return format::money('%n',$int);
}
function redir($data){
    parse_str($_SERVER['QUERY_STRING']);
    $id = isset($ref) ? $ref : 'index';
    header('Location:'.Nav_Tag::get_url($id, $data));
    die;
}

function get_day($day_num){
    switch ($day_num){
        case 7 : $hari="Minggu"; break;
        case 1 : $hari="Senin"; break;
        case 2 : $hari="Selasa"; break;
        case 3 : $hari="Rabu"; break;
        case 4 : $hari="Kamis"; break;
        case 5 : $hari="Jumat"; break;
        case 6 : $hari="Sabtu"; break;
    }
    return $hari;
}

function redir_by_id($id, $data = array(), $add = ''){
    header('Location:'.Nav_Tag::get_url($id, $data).$add);
    die;
}

function substract($i, $j){
    return $i-$j;
}

function get_month($i){
    $month = array(1 => 'Januari',2 => 'Februari',3 => 'Maret',4 => 'April',5 => 'Mei',6 => 'Juni',7 => 'Juli',8 => 'Agustus',9 => 'September',10 => 'Oktober',11 => 'Nopember',12 => 'Desember');
    return $month[$i * 1];
}

class Nav_Tag extends H2o_Node {
    var $id,$args;

    function __construct($argstring, $parser, $pos=0) {
        $args = explode(" ", trim($argstring),2);
        $this->id = $args[0];
        $this->args = isset($args[1]) ? $args[1]:'';
    }
    
    public static function get_url($id, $options = array()){
		/** special name **/
		$rootdir = str_replace("/bootstrap.php","",$_SERVER['SCRIPT_NAME']);
		if ($id == "public") {  return "$rootdir/views/public/"; }
		if ($id == "index") {  return "$rootdir/"; }
 
        $count = 1;
        $url = Slim::urlFor(
            $id,
            $options
        );
        while($count > 0){
            $url = preg_replace('/\(\/:(.*)\)\?/','',$url, -1, $count);
        }
        $count = 1;
        while($count > 0){
            $url = preg_replace('/\(\/(.*)\)\?/','/$1',$url, -1, $count);
        }
		
		
		//if ($url[strlen($url) -1] != "/") $url .= "/";
		
		if (isset($options['id'])) {
			$c = explode(".",$options['id']);
			if (count($c) > 1) {
				return "http://".(str_replace("//","/",str_replace(Slim::urlFor("shop",array("id"=>$options['id'])),$options['id'],$url)));
			}
		}
        return $url;
    }
    
    function render($context, $stream) {
        $cache = h2o_cache($context->options);
        $args = $this->args;
        
        $options = array();
        if($args !== ''){
			$opt_temp = explode(',',$args);
            foreach($opt_temp as $opt){
                list($key,$value) = explode(':',$opt);
                if(!class_exists('h2o_parser')){
                    require('h2o/h2o/parser.php');
                }
                
                $parser = h2o_parser::parseArguments($value);
                $parser = $parser[0];
                $value = $context->resolve($parser);
               
                $options[$key] = $value;
            }
        }
		
		
        $url = $this->get_url($this->id, $options);
        $stream->write($url);
    }
}



class Combobox_Tag extends H2o_Node {
    var $id,$args;
	
    function __construct($argstring, $parser, $pos=0) {
        $args = explode(" ", trim($argstring),2);
        $this->id = $args[0];
        $this->args = isset($args[1]) ? $args[1]:'';
    }
	
	function get_scope($name,$context) {
		//variable scoping
		$scope = explode(".",$name);
		$fd = array();
		foreach($context->scopes as $s) {
			if (count($scope) == 1 && isset($s["{$scope[0]}"])) {		
				$fd = $s["{$scope[0]}"];
				return $fd;
			}
			else if (count($scope) == 2 && isset($s["{$scope[0]}"]["{$scope[1]}"])) {		
				$fd = $s["{$scope[0]}"]["{$scope[1]}"];
				return $fd;
			}
			else if (count($scope) == 3 && isset($s["{$scope[0]}"]["{$scope[1]}"]["{$scope[2]}"])) {		
				$fd = $s["{$scope[0]}"]["{$scope[1]}"]["{$scope[2]}"];
				return $fd;
			}
			else if (count($scope) == 4 && isset($s["{$scope[0]}"]["{$scope[1]}"]["{$scope[2]}"]["{$scope[3]}"])) {		
				$fd = $s["{$scope[0]}"]["{$scope[1]}"]["{$scope[2]}"]["{$scope[3]}"];
				return $fd;
			}
		}
	}
	
	function render($context,$stream) {
		$name = $this->id;
		$args = explode(" ",$this->args);

		$text = "";
		$value = "";
		$selected = "";
		$source = "";

		foreach ($args as $arg) {
			if (strpos($arg,"text=") !== false) {
				$text = str_replace("text=","",$arg);
			}
			if (strpos($arg,"value=") !== false) {
				$value = str_replace("value=","",$arg);
			}
			if (strpos($arg,"selected=") !== false) {
				$selected = str_replace("selected=","",$arg);
			}
			if (strpos($arg,"source=") !== false) {
				$source = str_replace("source=","",$arg);
			}
		}

		if ($text == "") { echo "ERROR: combobox text attribute is not set"; die(); }
		if ($value == "") { echo "ERROR: combobox value attribute is not set"; die(); }

		if ($source == "") { $source = $name; }

		$fd = $this->get_scope($source,$context);
		$selected = $this->get_scope($selected,$context);

		$t = '<select name="'.$name.'">';
		foreach ($fd as $f) {
			$sel = ($f[$value] == $selected ? 'selected="selected"' : "");
			if ($name == "rider") {
				$off = ($f['berhenti'] != "" ? '(OFF) ' : "" );
			} else {
				$off = "";
			}
			$t .= '<option value="'.$f[$value].'" '.$sel.'>'.$off.$f[$text].'</option>';
		}
		$t .= '<select/>';
		
        $stream->write($t);
	}
}
class Date_Tag extends H2o_Node {
    var $id,$args;
	
    function __construct($argstring, $parser, $pos=0) {
        $args = explode(" ", trim($argstring),2);
        $this->id = $args[0];
        $this->args = isset($args[1]) ? $args[1]:'';
    }
    
	function render($context,$stream) {
		$name = $this->id;
		$args = $this->args;
				
		$start_year = 1940;
		$end_year = 2020;
		
		$args = explode(" ",$args);
		$nodate = false;
		$nomonth =false;
		foreach ($args as $arg) {
			if (strpos($arg,"year[") !== false) {
				$a = explode("[",$arg);
				$a = $a[1];
				$a = explode("-",$a);
				$b = $a[0] * 1;
				$a = $a[1];
				$a = explode("]",$a);
				$a = $a[0];
				$end_year = $a;
				$start_year = $b;
			}
			
			if (strpos($arg,"nodate") !== false) {
				$nodate = true;
			}
			if (strpos($arg,"nomonth") !== false) {
				$nomonth = true;
			}	
		}
		
		//variable scoping
		$varname = explode(".",$name);
		$parent_name = 'data';
		if (count($varname) > 1) {
			$parent_name = $varname[0];
			$name = $varname[1];
		}
		
		$fd = array();
		foreach($context->scopes as $scope) {
			if (isset($scope["$parent_name"]["$name"])) {
				$fd = explode("-",$scope["$parent_name"]["$name"]);
				break;
			}
		}
		
		if (!$nodate) {
			$tgl = '<select name="'.$name.'_date">';
			for ($i = 1;$i<=31;$i++) {
				if (count($fd) == 3 && $fd[0] == $i) {
					$tgl.='<option value="'.$i.'" selected="selected">'.$i.'</option>';
				} else {
					$tgl.='<option value="'.$i.'">'.$i.'</option>';
				}
			}
			$tgl .='</select>&nbsp;';
		} else { $tgl = ""; }
		
		if (!$nomonth) {
			
			$tgl .= '<select name="'.$name.'_month">';
			for ($i = 1;$i<=12;$i++) {
				$timestamp = mktime(0, 0, 0, $i, 1, 2005);

				if (count($fd) == 3 && $fd[1] == $i) {
					$tgl.='<option value="'.$i.'"  selected="selected">'.date("M", $timestamp).'</option>';
				} else {
					$tgl.='<option value="'.$i.'">'.date("M", $timestamp).'</option>';
				}
			}
			$tgl .='</select>&nbsp;';

		} else {
			$tgl .= "";
		}
	
		$tgl .= '<select name="'.$name.'_year">';
		for ($i = $start_year;$i<=$end_year;$i++) {
			if (count($fd) == 3 && $fd[2] == $i) {
				$tgl.='<option value="'.$i.'" selected="selected">'.$i.'</option>';
			} else if ($nomonth && $nodate && isset($fd[0]) &&  $fd[0] == $i) {
				$tgl.='<option value="'.$i.'" selected="selected">'.$i.'</option>';
			}
			else {
				$tgl.='<option value="'.$i.'">'.$i.'</option>';
			}
		}
		$tgl .='</select>';
        $stream->write($tgl);
	}
}
?>
