<?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_testimonials extends BaseModel
{
    protected $api_endpoint;
    protected $module;
    protected $cms_url;
    protected $api_version;
    protected $direction = "desc";

    public function __construct(array $config = array())
    {
        $app = JFactory::getApplication();
        $this->input = $jinput = $app->input;

        parent::__construct($config);

        /** @var extendedRegistry $params - Settings for our Component */
        $params = $this->getState('params');

        $this->cms_url = $params->get('pixel_cms_url');
        $this->api_version = $params->get('pixel_cms_version');
        $this->api_endpoint = 'testimonials';
        $this->module = "pixelcms_testimonials";

        $this->direction = $params->get('direction', 'desc');
    }

    public function getTestimonials()
    {
        $testimonials = $this->cache->get($this->api_endpoint, $this->module);

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

        $testimonials = json_decode($testimonials);

        if ($this->direction === "asc") {
            $testimonials = array_reverse($testimonials);
        } else if ($this->direction === "rand") {
            $testimonials = array_rand($testimonials);
        }

        return $testimonials;
    }

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

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

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