<?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
 */


defined('_JEXEC') or die;

require_once 'BaseModel.php';

/**
 * Pixelcms_articles model.
 *
 * @package  pixelcms_articles
 * @since    1.0
 */
class Pixelcms_articlesModelLandwirt_content extends BaseModel
{
    protected $articleId;
    protected $module;
    protected $customer;
    protected $menuId;
    protected $nummer;
    protected $allParams;

    protected $hidden = [
    ];

    static $landwirt_ext_url = 'https://extern.landwirt.com';
    static $landwirt_url = 'https://www.landwirt.com';

    public function __construct(array $config = array())
    {
        $app = JFactory::getApplication();
        $this->input = $jinput = $app->input;
        $this->articleId = $jinput->get('articleId', null);
        $this->nummer = $jinput->get('nummer', null);
        $this->customer = $jinput->getInt('landwirt_customer', null);
        $this->module = $jinput->get('landwirt_module', null);
        $this->menuId = $jinput->getInt('Itemid');

        parent::__construct($config);
    }

    public function getArticles()
    {
        return $this->getCachedData('artikel');
    }

    public function getVideos()
    {
        return $this->getCachedData('videos');
    }

    public function getDiashow()
    {
        return $this->getCachedData('artikeldiashow');
    }

    public function getCachedData($type)
    {
        $details = $this->articleId !== null;
        $cacheKey = self::getCacheKey([
            'customer' => $this->params->get('landwirt_customer'),
            'type' => $type,
            'nummer' => $this->nummer,
            'artId' => $this->articleId,
        ]);

        $data = $this->cache->get($cacheKey, 'landwirt_content');

        if (empty($data)) {
            $data = $this->getData($type, $details);
            $data = $this->preparePlayer($data);
            $this->cache->store($data, $cacheKey, 'landwirt_content');
        }
        $data = $this->prepareLinks($data);
        return $data;
    }

    private static function getCacheKey($cacheVars)
    {
        return implode('|', array_map(function($el, $key) {
            return "$key:$el";
        }, $cacheVars, array_keys($cacheVars)));
    }

    private function prepareLinks($content)
    {
        $menuId =  $this->menuId;
        return preg_replace_callback('/href=["\'].*?(?:(?:artikel|video)(?:[iI][Dd])=(\d*)|dianame=([^&]*)&nummer=(\d*)|dianame=([^&"\']*)).*?["\']/', function($match) use ($menuId) {
            if (isset($match[4])) {
                $articleId = $match[4];
            } else if (isset($match[2])) {
                $articleId = $match[2];
            } else {
                $articleId = $match[1];
            }
            $params = [
                'articleId' => $articleId,
                'Itemid' => $menuId,
            ];
            if (isset($match[3])) {
                $params['nummer'] = $match[3];
            }
            $query = http_build_query($params);
            return 'href="'.JRoute::_("index.php?$query").'"';
        }, $content);
    }

    private function preparePlayer($content)
    {
        return preg_replace_callback('/<iframe.*?src="([^"\']*).*><\/iframe>/', function ($matches) {
            if (preg_match('/videoId:\s+\'([^\']*)\'/', $this->cURL($matches[1]), $video)) {
                return "<div class='video_wrapper'><iframe src=\"https://www.youtube-nocookie.com/embed/$video[1]?rel=0\" frameborder=\"0\" allowfullscreen></iframe></div>";
            }
            return '';
        }, $content);
    }

    private function getData($type, $details = false)
    {
        $parameters = [];

        $url = self::$landwirt_ext_url . "/$type.php";

        if ($this->articleId) {
            if ($type === 'videos') {
                $parameters['videoid'] = $this->articleId;
            } else if ($type === 'artikeldiashow') {
                $parameters['dianame'] = $this->articleId;
            } else if ($type === 'artikel') {
                $url = self::$landwirt_url . "/ez/index.php/article/extern/$this->articleId";
            }
        }

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

        if ($details) {
            $parameters['detail'] = 1;
            if ($type === 'artikel') {
                return $this->cURL($url, $parameters);
            }
        }

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


    protected function cURL($url, $parameters = [])
    {
        $parameters = array_merge([
            'kunde' => ($this->customer) ?: $this->params['landwirt_customer'],
        ], $parameters);

        $query = http_build_query($parameters);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "$url?$query",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => self::$timeout,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
	        CURLOPT_FOLLOWLOCATION => true,
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $errNo = curl_errno($curl);

        curl_close($curl);

        if ($err) {
            throw new Exception($err, $errNo);
        }
        return $response;
    }
}
