<?php
/**
 * @package    pixelcms_articles
 *
 * @author     christophf <your@email.com>
 * @copyright  A copyright
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       http://your.url.com
 */


use Joomla\Registry\Registry;

defined('_JEXEC') or die;

require_once 'BaseModel.php';

/**
 * Pixelcms_articles model.
 *
 * @package  pixelcms_articles
 * @since    1.0
 */
class Pixelcms_articlesModelPixelcms_teams extends BaseModel
{
    protected $api_endpoint;
    protected $module;
    protected $articleId;
    protected $category_id;
    protected $cms_url;
    protected $alias;
    protected $filter;
    protected $api_version;

    public function __construct(array $config = array())
    {
        parent::__construct($config);

        /** @var extendedRegistry $params - Settings for current Menu Item */
        $params = $this->getState('params');

        $this->articleId = $params->getInt('articleId', null);
        $this->alias = $params->get('pixel_cms_alias');
        $this->cms_url = $params->get('pixel_cms_url');
        $this->api_version = $params->get('pixel_cms_version');
        $this->api_endpoint = 'departments';
        $this->module = "pixelcms_departments";
    }

    public function getTeam()
    {
        $data = $this->getCachedData();
        if ($this->articleId) {
	        foreach ($data->workers as $worker) {
		        $worker->email = str_rot13("$worker->email");
	        }
        } else {
		    foreach ($data as $team) {
	            foreach ($team->workers as $worker) {
	               $worker->email = str_rot13("$worker->email");
	            }
	        }
        }
        return $data;
    }

    public function getCachedData()
    {
        $articles = $this->cache->get($this->api_endpoint.$this->articleId, $this->module);

        if (empty($articles)) {
            $articles = $this->getData();
            $this->cache->store($articles, $this->api_endpoint.$this->articleId, $this->module);
        }

        return json_decode($articles);
    }

    private function getData()
    {
        $parameters = [];

        $url = $this->cms_url . '/api/' . $this->api_version . '/' . "$this->api_endpoint";
        if ($this->articleId) {
            $url = $this->cms_url . '/api/' . $this->api_version . '/' . "$this->api_endpoint/$this->articleId";
        }

        return $this->cURL($url, $parameters);
    }
}
