<?php
class Tpl
{
  protected $dir   = 'templates/';
  protected $vars  = array();
  
  function __construct( $dir = null )
  {
    if ( $dir !== null )
      $this -> dir = $dir;
  }
  
  public static function view( $file, $values = '' )
  {
    $tpl = new \Tpl;
    if ( is_array( $values ) ) foreach ( $values as $key => $val )
      $tpl -> $key = $val;
    return $tpl -> render( $file );
  }
  
  public function secureHTML( $val )
  {
    $out = stripslashes( $val );
    $out = str_replace( "'", "&#039;", $out );
    $out = str_replace( '"', "&#34;", $out );
    $out = str_replace( "<", "&lt;", $out );
    $out = str_replace( ">", "&gt;", $out );
    return $out;
  }
  
  public function render( $file )
  {    
    if ( file_exists( 'templates_a/' . $file . '.php' ) )
    {
      ob_start();
        include 'templates_a/' . $file . '.php';
        $out = ob_get_contents();
      ob_end_clean();
      
      return $out;
    }
    else if ( file_exists( 'templates_b/' . $file . '.php' ) )
    {
      ob_start();
        include 'templates_b/' . $file . '.php';
        $out = ob_get_contents();
      ob_end_clean();
      
      return $out;
    }
    else if ( file_exists( $this -> dir . $file . '.php' ) )
    {
      ob_start();
        include $this -> dir . $file . '.php';
        $out = ob_get_contents();
      ob_end_clean();
      
      return $out;
    }
    else
      return '<div class="alert alert-danger" role="alert">Nie znaleziono pliku widoku: <b>' . $this -> dir . $file . '.php</b>';
  }
  
  public function __set( $name, $value )
  {
    $this -> vars[ $name ] = $value;
  }
  
  public function __get( $name )
  {
    return $this -> vars[ $name ];
  }
}
