<?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_events extends BaseModel
{
    protected $api_endpoint;
    protected $module;
    protected $articleId;
    protected $category_id;
    protected $cms_url;
    protected $alias;
    protected $filter;
    protected $limit;
    protected $api_version;
	protected $state;
	protected $query;
	protected $defaults = [
        'disable_title_image' => 0,
    ];

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

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

        $this->limit = $params->getInt('limit', null);
        $this->articleId = $params->getInt('articleId', null);
        $this->category_id = $params->get('pixelcms_category_id', null);
        $this->filter = $params->get('pixelcms_filter', 'all');
        $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 = 'events';
        $this->module = "pixelcms_events";
    }

    public function getArticle()
    {
        $data = $this->getCachedEvents();
        if ($this->articleId) {
            return array_reduce($data, function ($carry, $article) {
                if ($article->id === (int) $this->articleId) {
                    $carry = $article;
                }
                return $carry;
            });
        }
        return $data;
    }

    public function getCategory()
    {
        $data = $this->getCachedData('categories');
        if ($this->category_id) {
            return array_reduce($data, function ($carry, $category) {
                if ($category->id === $this->category_id) {
                    $carry = $category;
                }
                return $carry;
            });
        }
        return $data;
    }

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

        if ($this->params->has('limit')) {
            $parameters['limit'] = $this->params->get('limit');
        }
        if ($this->params->has('filter')) {
            $filter = $this->params->get('filter');
            if ($filter === 'current_month') {
                $parameters['start'] = (new DateTime('first day of this month'))->format('Y-m-d');
                $parameters['end'] = (new DateTime('first day of this month'))->format('Y-m-t');
            } else if ($filter === 'next_month') {
                $parameters['start'] = (new DateTime())->format('Y-m-d');
                $parameters['end'] = (new DateTime('next month'))->format('Y-m-d');
            } else {
                $parameters['start'] = '';
            }
        }
        if ($this->params->has('order')) {
            $parameters['order'] = $this->params->get('order', 'desc');
        }
        if ($this->params->has('include_started')) {
            $parameters['include_started'] = $this->params->getInt('include_started');
        }

        $cacheKey = implode(',', array_map(function($value, $key) {
            return "$key:$value";
        }, $parameters, array_keys($parameters)));

        $events = $this->cache->get($cacheKey, $this->module);

        if ($this->articleId && (empty($events) || !in_array($this->articleId, array_column(json_decode($events), 'id')))) {
            $cacheKey = "$this->api_endpoint:id:$this->articleId";
            $events = $this->cache->get($cacheKey, $this->module);
        }

        if (empty($events)) {
            $events = $this->getEvents($parameters);
            $this->cache->store($events, $cacheKey, $this->module);
        }

        return json_decode($events);
    }

    private function getEvents($parameters)
    {
        $url = $this->cms_url . '/api/' . $this->api_version . '/' . "$this->api_endpoint/active";

        if ($this->params->getInt('include_disabled', 0) === 1) {
            $url = $this->cms_url . '/api/' . $this->api_version . '/' . "$this->api_endpoint";
        }

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

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

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

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