<?php

namespace app\controllers;
if(!defined('ACCESS_CONTROL')) {header($_SERVER['SERVER_PROTOCOL']. ' 404'); exit('404 not found');}
class ViewNotFound extends \Exception{
}

class ControllerBase {

    protected $_views;
    protected $_default_action;
    protected $_template;
    protected $params = array('get'=>array(), 'post'=>array());
    protected static $_append=array();

    protected static $_mime_types = array(
        'html'  => 'text/html',
        'js'    => 'application/javascript',
        'json'  => 'application/json',
        'text'  => 'text/plain',
    );


    public function __construct()
    {
        $this->_views = VIEWS_PATH;
        $this->_default_action = 'index';
        $this->params['post'] = $_POST;
        $this->params['get'] = $_GET;

    }

    public function appendData(array $array = array())
    {
        if($array)
        {
            foreach($array as $key=>$value)
                self::$_append[$key] = $value;
        }
    }

    public static function  render($template, array $data=array(), array $options=array())
    {
        $_options = array(
            'layout'    =>  !isset($options['type']) || $options['type']=='html',
            'type'      =>  'html',
            'mime_type'      =>  self::$_mime_types['html'],
        );

        $_options=array_merge($_options, $options);

        $_options['mime_type'] = array_key_exists($_options['type'],
            self::$_mime_types) ? self::$_mime_types[$_options['type']] : null;

        unset($options);
        $view = VIEWS_PATH.'/'.$template.'.'.$_options['type'].'.php';
        if(!file_exists($view))
            throw new ViewNotFound($template);


        if(!empty(self::$_append))
        {
            foreach(self::$_append as $key=>$value)
                $data[$key]=$value;
        }
        extract($data);

        if(!is_null($_options['type']) && $_options['type']!='html')
            header("Content-type: ".self::$_mime_types[$_options['type']]);

        if($_options['layout'])
        {
            ob_start();
            include $view;
            $yield = ob_get_clean();
            include VIEWS_PATH . '/layouts/application.html.php';
        }else
            include $view;
    }

    public static function render_status($status = 404)
    {
        $folder = ROOT_PATH. '/public';
        header($_SERVER['SERVER_PROTOCOL']. ' '.$status);
        if(file_exists($folder.'/'.$status.'.html'))
            include $folder.'/'.$status.'.html';
    }

    public static function render_partial($partial, array $data=array(), array $options=array()){
        if($data)
            extract($data);
        $options['layout']=false;
        self::render('layouts/'.$partial, $data, $options);
    }

    public function redirect($url='?')
    {
        header("Location: $url");
    }
}