<?php

namespace Nextend\SmartSlider3Pro\Generator\Joomla\Flexicontent\Sources;

use FlexicontentFields;
use FlexicontentHelperRoute;
use FlexicontentModelItem;
use JApplicationCms;
use JFactory;
use JTable;
use Nextend\Framework\Database\Database;
use Nextend\Framework\Form\Container\ContainerTable;
use Nextend\Framework\Form\Element\MixedField\GeneratorOrder;
use Nextend\Framework\Form\Element\Select\Filter;
use Nextend\Framework\Form\Element\Text;
use Nextend\Framework\Parser\Common;
use Nextend\SmartSlider3\Generator\AbstractGenerator;
use Nextend\SmartSlider3\Platform\Joomla\ImageFallback;
use Nextend\SmartSlider3Pro\Generator\Joomla\Flexicontent\Elements\FlexicontentCategories;
use Nextend\SmartSlider3Pro\Generator\Joomla\Flexicontent\Elements\FlexicontentTags;
use Nextend\SmartSlider3Pro\Generator\Joomla\Flexicontent\Elements\FlexicontentTypes;

class FlexicontentItems extends AbstractGenerator {

    protected $layout = 'article';

    public function getDescription() {
        return sprintf(n2_('Creates slides from %1$s content.'), 'FLEXIcontent');
    }

    public function renderFields($container) {
        parent::renderFields($container);

        $filterGroup = new ContainerTable($container, 'filter', n2_('Filter'));

        $source = $filterGroup->createRow('source-row');
        new FlexicontentTypes($source, 'sourcetype', n2_('Type'), 0);
        new FlexicontentCategories($source, 'sourcecategory', n2_('Categories'), 0, array(
            'isMultiple' => true
        ));
        new FlexicontentTags($source, 'sourcetag', n2_('Tags'), 0, array(
            'isMultiple' => true
        ));

        $limit = $filterGroup->createRow('limit-row');
        new Filter($limit, 'sourcefeatured', n2_('Featured'), 0);
        new Text($limit, 'sourcelanguage', n2_('Language'), '*');
        new Text($limit, 'sourceids', n2_('Only display items with these IDs'), '');

        $orderGroup = new ContainerTable($container, 'order-group', n2_('Order'));
        $order      = $orderGroup->createRow('order-row');
        new GeneratorOrder($order, 'flexiorder', 'con.created|*|desc', array(
            'options' => array(
                ''                 => n2_('None'),
                'con.title'        => n2_('Title'),
                'cat_title'        => n2_('Category title'),
                'created_by_alias' => n2_('Username'),
                'con.featured'     => n2_('Featured'),
                'con.ordering'     => n2_('Ordering'),
                'con.hits'         => n2_('Hits'),
                'con.created'      => n2_('Creation time'),
                'con.modified'     => n2_('Modification time')
            )
        ));
    }

    protected function _getData($count, $startIndex) {

        $query = 'SELECT ';
        $query .= 'con.id, con.images, con.introtext, con.fulltext ';

        $query .= 'FROM #__content AS con ';

        $query .= 'LEFT JOIN #__flexicontent_cats_item_relations AS fcat ON fcat.itemid = con.id ';
        $query .= 'LEFT JOIN #__categories AS cat ON fcat.catid = cat.id ';

        $jNow  = JFactory::getDate();
        $now   = $jNow->toSql();
        $where = array(
            "(con.publish_up = '0000-00-00 00:00:00' OR con.publish_up IS NULL OR con.publish_up < '" . $now . "') AND (con.publish_down = '0000-00-00 00:00:00' OR con.publish_down IS NULL OR con.publish_down > '" . $now . "') ",
            'con.state = 1 '
        );

        $category = array_map('intval', explode('||', $this->data->get('sourcecategory', '')));
        if (!in_array('0', $category)) {
            $where[] = 'fcat.catid IN (' . implode(',', $category) . ') ';
        }

        $tag = array_map('intval', explode('||', $this->data->get('sourcetag', '0')));
        if (!in_array('0', $tag)) {
            $where[] = ' con.id IN (SELECT itemid FROM #__flexicontent_tags_item_relations WHERE tid IN(' . implode(',', $tag) . '))';
        }

        $type = array_map('intval', explode('||', $this->data->get('sourcetype', '0')));
        if (!in_array('0', $type)) {
            $where[] = ' con.id IN (SELECT item_id FROM #__flexicontent_items_ext WHERE type_id IN(' . implode(',', $type) . '))';
        }

        $ids = $this->data->get('sourceids', '');
        if (!empty($ids)) {
            $where[] = ' con.id IN (' . $ids . ')';
        }

        switch ($this->data->get('sourcefeatured', 0)) {
            case 1:
                $where[] = 'con.featured = 1 ';
                break;
            case -1:
                $where[] = 'con.featured = 0 ';
                break;
        }

        $language = $this->data->get('sourcelanguage', '*');
        if ($language) {
            $db      = JFactory::getDbo();
            $where[] = 'con.language = ' . $db->quote($language) . ' ';
        }

        if (count($where)) {
            $query .= ' WHERE ' . implode(' AND ', $where);
        }

        $query .= 'GROUP BY con.id ';

        $order = Common::parse($this->data->get('flexiorder', 'con.created|*|desc'));
        if ($order[0]) {
            $query .= 'ORDER BY ' . $order[0] . ' ' . $order[1] . ' ';
        }

        $query .= 'LIMIT ' . $startIndex . ', ' . $count;

        $result = Database::queryAll($query);

        $lng      = JFactory::getLanguage();
        $adminApp = JFactory::$application;
        $siteApp  = JApplicationCms::getInstance('site');
        $siteApp->loadLanguage($lng);


        require_once(JPATH_ADMINISTRATOR . DS . 'components/com_flexicontent/defineconstants.php');
        JTable::addIncludePath(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_flexicontent' . DS . 'tables');
        require_once(JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'permission.php');
        require_once(JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'helpers' . DS . 'route.php');
        require_once(JPATH_SITE . DS . "components/com_flexicontent/classes/flexicontent.fields.php");
        require_once(JPATH_SITE . DS . "components/com_flexicontent/classes/flexicontent.helper.php");
        require_once(JPATH_SITE . '/components/com_flexicontent/models/item.php');

        $app  = JFactory::getApplication();
        $user = JFactory::getUser();
        $aid  = $user->getAuthorisedViewLevels();

        $itemModel = new FlexicontentModelItem();

        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            JFactory::$application = $siteApp;
            $item                  = $itemModel->getItem($result[$i]['id'], $check_view_access = false);
            list($item) = FlexicontentFields::getFields($item, '', $item->parameters, $aid);
            JFactory::$application = $adminApp;

            $helper = array();
            foreach ($item->fields AS $k => $field) {
                if ($k == 'favourites' || $k == 'voting' || $k == 'state') {
                    continue;
                }
                $helper[$k] = @FlexicontentFields::getFieldDisplay($item, $k, $values = null, $method = 'display');
            }

            $r = array(
                'title'       => $helper['title'],
                'description' => $helper['text'],
                'introtext'   => $result[$i]['introtext'],
                'fulltext'    => $result[$i]['fulltext'],
            );

            if (!empty($result[$i]['images'])) {
                $img        = json_decode($result[$i]['images']);
                $r['image'] = $r['thumbnail'] = ImageFallback::fallback(array(
                    @$img->image_intro,
                    @$img->image_fulltext
                ), array(
                    $helper['text']
                ));
            }

            $r += array(
                'url'               => FlexicontentHelperRoute::getItemRoute($item->id, $item->catid),
                'url_label'         => n2_('View'),
                'creation_date'     => $helper['created'],
                'created_by'        => $helper['created_by'],
                'modification_date' => $helper['modified'],
                'modified_by'       => $helper['modified_by'],
                'hits'              => $helper['hits'],
                'document_type'     => $helper['document_type'],
                'version'           => $helper['version'],
                'categories'        => $helper['categories'],
                'tags'              => $helper['tags'],
                'id'                => $result[$i]['id']
            );

            $data[] = $r;
        }
        JFactory::$application = $adminApp;

        return $data;
    }
}