<?php namespace sc;

class Controller
{
    private $template;
    public $db;
    public $request;
    public $session;

    /**
     * Controller constructor.
     *
     * @param string $template
     */
    public function __construct($template = null)
    {
        if (null == $template) {
            $this->template = PATH . '/templates/' . rtrim(json_decode(file_get_contents(CONF . '/template.json'), true)['template'], '/') . '/';
        } else {
            $this->template = rtrim($template, '/') . '/';
        }

        $conf = include CONF . '/conf.php';

        $this->db = new DB($conf['database']);

        $this->session = new Session($conf['session']);
        $this->session->start();

        $this->request = new Request();
    }

    /**
     * 重定向页面
     *
     * @param string $url
     */
    public final function redirect($url)
    {
        header('Location: ' . $url);
    }

    /**
     * 显示页面
     *
     * @param string $view
     * @param array  $data
     */
    public final function render($view, $data = null)
    {
        $prefix = json_decode(file_get_contents(CONF . '/template.json'), true)['prefix'];

        $file = $this->template . $prefix . $view . '.php';

        if (null != $data) {
            extract($data, EXTR_REFS);
        }

        include $file;
    }

    /**
     * 返回JSON
     *
     * @param array $data
     */
    public final function json($data)
    {
        echo json_encode($data);
    }
}