<?php
/**
 * @package   Nicepage Website Builder
 * @author    Nicepage https://www.nicepage.com
 * @copyright Copyright (c) 2016 - 2019 Nicepage
 * @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
 */

namespace NP\Items;

defined('_JEXEC') or die;

use \NicepageHelpersNicepage;

/**
 * Class TemplateFromSettings
 */
class TemplateFromSettings extends Template
{
    private $_templateObject;
    private $_templateKey;

    /**
     * @param string $templateJson Template object from config
     * @param string $templateKey  Template name
     */
    public function __construct($templateJson, $templateKey) {
        $this->_templateObject = $templateJson;
        $this->_templateKey = $templateKey;
        parent::__construct($this);
    }

    /**
     * Get template props
     *
     * @return mixed|null
     */
    public function getProps() {
        if ($this->_props) {
            return $this->_props;
        }
        if ($this->_templateKey === 'password') {
            $props = $this->_backwardPasswordTemplate($this->_templateObject);
        } else {
            $props = unserialize(call_user_func('base' . '64_decode', $this->_templateObject));
        }
        $props['pageId'] = $this->_templateKey;
        $props['isPreview'] = false;

        return $props;
    }

    /**
     * Backward for old password template
     *
     * @param string $data Template data
     *
     * @return array
     */
    private function _backwardPasswordTemplate($data) {
        $data = json_decode($data, true);
        return array(
            'publishHtml' => $data['php'],
            'head' => preg_replace('/<\/?style>/', '', $data['styles']),
            'hideHeader' => $data['hideHeader'],
            'hideFooter' => $data['hideFooter'],
        );
    }

    /**
     * Get page instance
     *
     * @param null $templateKey Template key
     *
     * @return TemplateFromSettings
     */
    public static function getInstance($templateKey)
    {
        $config = NicepageHelpersNicepage::getParamsTable()->getParameters();
        $template = isset($config[$templateKey]) ? $config[$templateKey] : '';

        if (!$template) {
            return null;
        }

        if (!is_object(self::$_instance)) {
            self::$_instance = new self($template, $templateKey);
        }

        return self::$_instance;
    }
}

