<?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_news extends BaseModel
{
    protected $api_endpoint;
    protected $articleId;
    protected $module;
    protected $cms_url;
    protected $alias;
    protected $limit;
    protected $api_version;
    protected $page;
    protected $perPage;
    protected $category_id;
    protected $excluded;
    protected $intro_length;

    protected $defaults = [
        'cut_images' => 1,
        'disable_title_image' => 0,
        'show_date' => 'before',
        'intro_length' => 200,
    ];


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

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

        $this->limit = $params->getInt('limit', null);
        $this->intro_length = $params->getInt('intro_length', null);
        $this->articleId = $params->getInt('articleId', null);
        $this->category_id = $params->get('pixelcms_category_id', null);
        $this->cms_url = $params->get('pixel_cms_url');
        $this->api_version = $params->get('pixel_cms_version');
        $this->excluded = $params->get('e_ids', null);
        $this->api_endpoint = 'news';
        $this->module = "pixelcms_news";

        if (!$params->get('is_module', false)) {
            $this->page = $params->getInt('page', 1);
            $this->perPage = $this->limit;
        }
    }

    public function getNews()
    {
        $data = $this->getCachedData();

        if ($this->articleId && !$data) {
            throw new \Exception("Termin nicht gefunden", 404);
        }

        return $data;
    }

    public function getCachedData()
    {
        $categoryKey = (is_array($this->category_id)) ? implode('.', $this->category_id) : $this->category_id;
        $cacheKey = "$this->api_endpoint:" . (($this->articleId) ? "id:$this->articleId" : "l:$this->limit;p:$this->page;c:$categoryKey");
        $articles = $this->cache->get($cacheKey, $this->module);
        if (empty($articles)) {
            $articles = $this->getPreparedData();
            $this->cache->store($articles, $cacheKey, $this->module);
        }
        return json_decode($articles);
    }

    private function getPreparedData()
    {
        $json = $this->getData();
        $data = json_decode($json);
        $articles = $data->data ?? $data;

        if (is_array($articles)) {
            foreach ($articles as $index => &$article) {
                foreach ($article->images as &$image) {
                    $image = str_replace('http', 'https', $image);
                }
            }
        } else {
            foreach ($articles->images as &$image) {
                $image = str_replace('http', 'https', $image);
            }
        }

        return json_encode($data);
    }

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

        if ($this->limit > 0) {
            $parameters['limit'] = $this->limit;
        }

        if ($this->page) {
            if ($this->perPage > 0) {
                $parameters['page'] = $this->page;
                $parameters['perPage'] = $this->perPage;
            }
            unset($parameters['limit']);
        }

        if ($this->category_id) {
            $parameters['category'] = $this->category_id;
        }

        if ($this->intro_length) {
            $parameters['intro'] = $this->intro_length;
        }

        if ($this->excluded) {
            $parameters['excluded_manufacturers'] = $this->excluded;
        }

        $url = $this->cms_url . '/api/' . $this->api_version . '/' . "$this->api_endpoint";

        if ($this->articleId) {
            $url .= "/$this->articleId";
        }

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