<?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 Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use \NicepageHelpersNicepage;

class Template extends BaseItem
{
    protected static $_instance;

    /**
     * Page constructor.
     *
     * @param null $templateTable Page table
     */
    public function __construct($templateTable) {
        parent::__construct($templateTable);
    }

    /**
     * @param array $data Template data
     *
     * @return void
     */
    public function setTemplateData($data) {
        $this->_templateData = array_merge($data, array('type' => $this->_props['templateKey']));
    }

    /**
     * @param string $productName Product name
     *
     * @return null
     */
    public function setProductName($productName)
    {
        $this->_productName = $productName;
    }

    /**
     * Set plugin styles
     */
    public function setStyles()
    {
        parent::setStyles();
        $themeCss = '/templates/' . Factory::getApplication()->getTemplate() . '/css/default.css';
        if ($this->_templateData && file_exists(JPATH_BASE . $themeCss)) {
            $this->_styles .= '<link href="' . Uri::root(true) . $themeCss . '" rel="stylesheet">';
        }
    }

    /**
     * Get properties
     *
     * @return array|mixed|null
     */
    public function getProps() {
        return $this->_props;
    }

    /**
     * @return string
     */
    public function getHtml() {
        $type = $this->_pageView === 'landing' ? 'landing' : 'content';
        $content = "<!--np_" . $type . "-->" . $this->getSectionsHtml() . "<!--/np_" . $type . "-->";
        $content .= "<!--np_template_id-->" . $this->getPageId() . "<!--/np_template_id-->";
        return $content;
    }

    /**
     * Get edit link html
     *
     * @return string
     */
    public function getEditLinkHtml() {
        return '';
    }

    /**
     * Get page instance
     *
     * @param null $templateKey Template key
     *
     * @return Template
     */
    public static function getInstance($templateKey)
    {
        $templateTable = NicepageHelpersNicepage::getTemplatesTable();
        if (!$templateTable->load(array('template_key' => $templateKey))) {
            return null;
        }

        if (!is_object(self::$_instance)) {
            self::$_instance = new self($templateTable);
        }

        return self::$_instance;
    }
}

