<?php

class ThemeView
{
    protected $theme;
    protected $themeDir;
    protected $fallbackDir;

    public function __construct($theme)
    {
        $this->theme = preg_replace('/[^a-z0-9\-_]/i', '', (string)$theme);
        $this->themeDir = __DIR__ . '/../themes/' . $this->theme . '/views';
        $this->fallbackDir = __DIR__ . '/views';
    }

    public function render($view, array $data = array(), $layout = 'main')
    {
        $viewFile = $this->resolve($view);
        if(!$viewFile){
            http_response_code(500);
            echo 'View not found: ' . htmlspecialchars($view, ENT_QUOTES, 'UTF-8');
            return;
        }

        $content = $this->capture($viewFile, $data);
        if($layout === null || $layout === false){
            echo $content;
            return;
        }

        $layoutFile = $this->resolve('layouts/' . $layout);
        if(!$layoutFile){
            echo $content;
            return;
        }

        echo $this->capture($layoutFile, array_merge($data, array('content' => $content)));
    }

    public function partial($view, array $data = array())
    {
        $file = $this->resolve('partials/' . $view);
        if($file) echo $this->capture($file, $data);
    }

    protected function resolve($view)
    {
        $view = preg_replace('/[^a-z0-9\/_\-]/i', '', (string)$view);
        $candidates = array(
            $this->themeDir . '/' . $view . '.php',
            $this->fallbackDir . '/' . $view . '.php',
        );
        foreach($candidates as $file){
            if(is_file($file)) return $file;
        }
        return '';
    }

    protected function capture($file, array $data)
    {
        extract($data, EXTR_SKIP);
        ob_start();
        include $file;
        return ob_get_clean();
    }
}

