<?php
require_once 'Sabai/Response/Web.php';
require_once 'Plugg/Template.php';

class Plugg_Response extends Sabai_Response_Web
{
    private $_tabs = array();
    private $_currentTab;
    private $_tabPageInfo = array();
    private $_tabPageTitle;

    public function __construct()
    {
        parent::__construct(new Plugg_Template());
    }

    public function addTab($tabName, $tabTitle, $tabUrl = null)
    {
        if (empty($tabUrl)) $tabUrl = array();
        $this->_tabs[$tabName] = array('title' => $tabTitle, 'url' => $tabUrl);
        return $this;
    }

    public function addTabs($tabs)
    {
        foreach ($tabs as $tab_name => $tab_data) {
            $this->addTab($tab_name, $tab_data['title'], @$tab_data['url']);
        }
        return $this;
    }

    public function setCurrentTab($tabName)
    {
        $this->_currentTab = $tabName;
        return $this;
    }

    public function setPageInfo($pageTitle, $pageUrl = array())
    {
        if (empty($this->_tabs) || !isset($this->_currentTab)) {
            return parent::setPageInfo($pageTitle, $pageUrl);
        }

        $this->_tabPageInfo[] = array('title' => $pageTitle, 'url' => $pageUrl);

        return $this;
    }

    public function setPageTitle($pageTitle)
    {
        if (empty($this->_tabs) || !isset($this->_currentTab)) {
            return setPageTitle($pageTitle);
        }

        $this->_tabPageTitle = $pageTitle;

        return $this;
    }

    public function clearTabPageInfo()
    {
        $this->_tabPageInfo = array();
        $this->_tabPageTitle = null;

        return $this;
    }

    protected function _sendContent(Sabai_Application $application, $contentNames, $vars)
    {
        $vars['TABS'] = $this->_tabs;
        $vars['TAB_CURRENT'] = $this->_currentTab;
        $vars['TAB_PAGE_TITLE'] = $this->_tabPageTitle;
        $vars['TAB_PAGE_BREADCRUMBS'] = '';
        if (isset($this->_currentTab) && count($this->_tabPageInfo) > 0) {
            $page_info_last = array_pop($this->_tabPageInfo);
            if (!isset($vars['TAB_PAGE_TITLE'])) $vars['TAB_PAGE_TITLE'] = $page_info_last['title'];
            if (!empty($this->_tabPageInfo)) {
                $breadcrumbs = array();
                foreach ($this->_tabPageInfo as $page_info) {
                    $breadcrumbs[] = sprintf(
                        '<a href="%s">%s</a>',
                        $application->url->create($page_info['url']),
                        h($page_info['title'])
                    );
                }
                $breadcrumbs[] = h($page_info_last['title']);
                $vars['TAB_PAGE_BREADCRUMBS'] = implode(' &gt; ', $breadcrumbs);
            }
        }
        parent::_sendContent($application, $contentNames, $vars);
    }
}