<?php
/**
 * This is a core PHP file. For customization, create a file in the folder /custom/.
 * Files with the same filename in this folder will automatically be loaded instead of the current file
 */

namespace hostfact;

use Service_Controller;
use Settings_Model;

class CST_Controller extends Service_Controller
{
	public function __construct(\Template $template)
	{
		// Call service controller construct
		parent::__construct($template);

		// Make alias for cst model
		$this->CSTModel = $this->ServiceModel;

		// Set sidebar
		$this->Template->setSidebar('cst.sidebar');
	}

	public function index()
	{
        $typeId = isset($_GET['rt']) && is_numeric(basename($_GET['rt'])) ? intval(basename($_GET['rt'])) : 0;
        if ($typeId) {
            $cst_list = array_values(array_filter($this->CSTModel->listCST()[0], function($cst) use ($typeId){ return $cst['Type'] == $typeId; }));
            if (!empty($cst_list)) {
                header('Location: ' . __SITE_URL . '/' . __('cst', 'url') . '/' . __('view', 'url') . '/' . $cst_list[0]['Identifier']);
                exit;
            }
        }

        if(!empty($this->Template->cst_list))
		{
			// We want to show the latest cst
			header('Location: ' . __SITE_URL . '/' . __('cst', 'url') . '/' . __('view', 'url') . '/' . $this->Template->cst_list[0]['Identifier']);
			exit;
		}
		else
		{
			// No cst, redirect to dashboard
			header('Location: ' . __SITE_URL . '/');
			exit;
		}
	}

	public function setListCST($typeId)
	{
		$this->Template->cst_list = array_values(array_filter($this->CSTModel->listCST()[0], function($cst) use ($typeId){ return $cst['Type'] == $typeId; }));
	}

	public function view()
	{
		$this->CSTModel->id = intval(get_url_var($_GET['rt']));
		if($result = $this->CSTModel->show())
		{
			$this->formatSubscription($this->CSTModel);
			$this->Template->service = $this->CSTModel;
			$this->Template->servicetype = 'cst';
		}

		$this->setListCST($this->CSTModel->Type);

		$this->Template->parseMessage($this->CSTModel);

		if(isset($result) && $result)
		{
			$this->Template->show('cst.view');
		}
		else
		{
			$this->Template->header = __('cst service');
			$this->Template->text   = __('cst does not exist');
			$this->Template->show('page.objectnotfound');
		}
	}

}