<?php

namespace modules\cms;

class main extends \moduleMain {

	use \modules\config\traits {
			\modules\config\traits::__construct as __ConstructConfig;
		}
	use \modules\input\traits {
			\modules\input\traits::__construct as __ConstructInput;
		}
	use \modules\database\traits {
			\modules\database\traits::__construct as __ConstructDatabase;
		}
	use \modules\output\traits {
			\modules\output\traits::__construct as __ConstructOutput;
		}

	private $model_cms = NULL;
	private $editPage = FALSE;
	private $pagestatus = 0;

	public function __construct() {
		parent::__construct(__DIR__);
		$this->__ConstructConfig();
		$this->__ConstructInput();
		$this->__ConstructDatabase();
		$this->__ConstructOutput($this->__INPUT, $this->__CONFIG);
	}

	public function Activate() {
		hook_add('output.errordetail', [$this, '__create']);
		hook_add('uri', [$this, '__checkcms']);
		hook_add('email.transform', [$this, '__applyHandlebars']);		// is the email using a templating system?
		hook_add('menu.menu2', [$this, '__edit'], 2);					// can we edit this page?
		hook_add('menu.admin', [$this, '__admin_menu'], 20);	 		// admin menu
//		$this->autoloadRegister('LightnCandy', __DIR__ . '/lightncandy');
		$this->Register_FormatHandler('__cms', [$this, '__cms_page'], 'a CMS page');
		$this->Register_FormatHandler('__cms_edit', [$this, '__cms_edit'], 'CMS page editor');
		$this->Register_FormatHandler('__cms_json', [$this, '__cms_json'], 'update CMS page status');
	}
	
	public function __admin_menu(&$menu) {
		$menu[] = [
				'caption' => 'CMS Content', 
				'href' => '/admin/cms-pages', 
				'hint' => 'View/Edit CMS Content',
				'icon' => '<i class="fas fa-file-alt"></i>',
				's' => 0
			];
		$menu[] = [
				'caption' => 'Email Templates', 
				'href' => '/admin/email', 
				'hint' => 'Edit Email Templates',
				'icon' => '<i class="far fa-envelope"></i>',
				's' => 0
			];
	}

	private function _init() {
		if (empty($this->model_cms)) {
			$this->model_cms = $this->LoadModel('cms_model');
			$this->model_cms->SetPages($this->loadModel('pages'));
		}
	}

	public function __create(&$data, $http_status) {
		if ($http_status->status() == 404) {		// only for not-found pages
			$this->_init();
			$uri = $this->uri();					// without any query_string
			if ($uri != '/') $uri = rtrim($uri, '/');
			$this->editPage = $this->model_cms->ErrorPage($data, $uri);
		}
	}
	
	// only for email templates
	public function __applyHandlebars(&$mailobject) {
        $template = $mailobject->template();
		if (empty($result) && !empty($template)) {
			$this->_init();
			$this->model_cms->ApplyEmailTemplate($mailobject);
		}
	}
	
	// is the URL one from the cms system?
	//to do: intercept email links 
	public function __checkcms($uri) {
		$this->_init();
		$preview = $this->param('previewid', '');
		if ($preview) {
			$this->model_cms->SetPagesHistory($this->loadModel('pages_history'));
			$this->model_cms->RedirectToPreview($preview, $this->hostname(TRUE));
			return;
		}
		$edithash = $this->param('editpage', '');
//		$this->model_cms->SetPages($this->loadModel('pages'));
		if ($uri != '/') $uri = rtrim($uri, '/');
		$this->pagestatus = $this->model_cms->IsCmsPage($uri, $edithash);
		switch($this->pagestatus) {
			case 1:			// view cms text
				$this->OutputFormat('__cms');
				return;
			case 2:			// edit text
				$this->model_cms->SetPagesHistory($this->loadModel('pages_history'));
				return $this->_acceptcms('__cms_edit');
		// CASE 3: redirect to preview page
		}
	}
	
	// a cms page has been requested.
	// if we are doing a preview, at the same time the page is saved here, the homepage
	//  is loaded from another tab.  We pause a second to allow this update to saved
	//  then the other tab redirects to the preview page
	private function _acceptcms($param) {
		// set cms text
		
		if ($this->method() == 'POST') {
			$this->model_cms->SetPagesHistory($this->loadModel('pages_history'));
			// {"error":false,"message":null,"body":null,"result":null}

			$param = [
				's' 		=> strtolower(trim($this->post('s', ''))), 
				'body' 		=> $this->post('body', ''), 
				'title' 	=> $this->post('title', ''),
				'previewid' => $this->post('previewid', ''),
//				'uri' 		=> $this->post('uri', ''),			// this is used earlier
				'perms' 	=> $this->post('perms', ''),
			];
			$result = $this->model_cms->PageSave($param);
			$this->OutputSet('result', $result['result']);
			$this->OutputSet('message', $result['message']);
			$this->OutputFormat('__cms_json');
			//to do: update data json to display page-saved noty.
		} else {
			$this->OutputFormat($param);
		}
	}
	
	public function __edit(&$menu) {
		if ($this->editPage) {		// page not found - allow it to be created or edited
// does the page exist?
			$hint = $this->pagestatus ? 'Edit Content' : 'Create Content';
			$menu[] = [
				'caption' => $hint, 
				'href' => $this->editPage, 
				'hint' => $hint,
				'icon' => '<i class="fax-green largeicon fas fa-pen-square"></i>',
				's' => 0
			];
		}
	}
	
	public function __cms_page($data) {
		unset($data['result'], $data['message']);
		$this->model_cms->ViewPage();
		$this->__OUTPUT->ExportHandler($data, 'html');
	}

	public function __cms_edit($data) {
		unset($data['result'], $data['message'], $data['template']);
//		$base = $this->StaticUriModule(__DIR__);
//		$this->IncludeFile($base . '/style.css');
		$this->model_cms->EditPage();
		$this->__OUTPUT->ExportHandler($data, 'html');
	}
	
	public function __cms_json($data) {
		$data['result'] = $this->OutputGet('result');
		$data['message'] = $this->OutputGet('message');
		$this->__OUTPUT->ExportHandler($data, 'json');
	}
	
}