<?php

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

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\Framework\ResourceTranslator\ResourceTranslator;
use Nextend\SmartSlider3\Generator\AbstractGenerator;
use Nextend\SmartSlider3\Platform\Joomla\ImageFallback;
use Nextend\SmartSlider3Pro\Generator\Joomla\Redshop\Elements\RedshopCategories;
use Nextend\SmartSlider3Pro\Generator\Joomla\Redshop\Elements\RedshopManufacturers;
use Nextend\SmartSlider3Pro\Generator\Joomla\Redshop\Elements\RedshopSuppliers;
use producthelper;
use Redconfiguration;

class RedshopProducts extends AbstractGenerator {

    protected $layout = 'product';

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

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

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

        $source = $filterGroup->createRow('source-row');
        new RedshopCategories($source, 'sourcecategories', n2_('Category'), 0, array(
            'isMultiple' => true
        ));
        new RedshopManufacturers($source, 'sourcemanufacturers', n2_('Manufacturer'), 0, array(
            'isMultiple' => true
        ));
        new RedshopSuppliers($source, 'sourcesuppliers', n2_('Supplier'), 0, array(
            'isMultiple' => true
        ));


        $limit = $filterGroup->createRow('limit-row');
        new Filter($limit, 'sourcefeatured', n2_('Featured'), 0);
        new Filter($limit, 'sourceonsale', n2_('On sale'), 0);
        new Filter($limit, 'sourceexpired', n2_('Expired'), 0);
        new Filter($limit, 'sourceforsell', 'For sell', 0);
        new Text($limit, 'product_parent_id', 'Parent product ID', '*');

        $orderGroup = new ContainerTable($container, 'order-group', n2_('Order'));
        $order      = $orderGroup->createRow('order-row');
        new GeneratorOrder($order, 'redshopproductsorder', 'pr.publish_date|*|desc', array(
            'options' => array(
                ''                  => n2_('None'),
                'pr.product_name'   => n2_('Product name'),
                'pr_cat.ordering'   => n2_('Ordering'),
                'pr.publish_date'   => n2_('Creation time'),
                'pr.update_date'    => n2_('Modification time'),
                'pr.visited'        => n2_('Hits'),
                'pr.product_price'  => n2_('Price'),
                'pr.discount_price' => n2_('Discount price')
            )
        ));
    }

    protected function _getData($count, $startIndex) {

        $where = array(' pr.published = 1 ');

        $categories = array_map('intval', explode('||', $this->data->get('sourcecategories', '')));
        if (!in_array(0, $categories) && count($categories) > 0) {
            $where[] = 'pr_cat.category_id IN (' . implode(',', $categories) . ') ';
        }

        $manufacturers = array_map('intval', explode('||', $this->data->get('sourcemanufacturers', '')));
        if (!in_array(0, $manufacturers) && count($manufacturers) > 0) {
            $where[] = 'pr.manufacturer_id IN (' . implode(',', $manufacturers) . ') ';
        }

        $suppliers = array_map('intval', explode('||', $this->data->get('sourcesuppliers', '')));
        if (!in_array(0, $suppliers) && count($suppliers) > 0) {
            $where[] = 'pr.supplier_id IN (' . implode(',', $suppliers) . ') ';
        }

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

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

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

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

        $parentID = $this->data->get('product_parent_id', '*');
        if (is_numeric($parentID)) {
            $where[] = ' pr.product_parent_id = ' . $parentID . ' ';
        }

        $o = '';

        $order = Common::parse($this->data->get('redshopproductsorder', 'pr.publish_date|*|desc'));
        if ($order[0]) {
            $o .= 'ORDER BY ' . $order[0] . ' ' . $order[1] . ' ';
        }

        $query = "SELECT
                        pr.product_id, 
                        pr.published, 
                        pr_cat.ordering, 
                        pr.product_name as name, 
                        pr.product_s_desc as short_description, 
                        pr.product_desc as description,
                        man.manufacturer_name as man_name,
                        pr.product_full_image as image, 
                        pr.product_thumb_image as image_thumbnail, 
                        pr.product_price,
                        pr.discount_price,
                        pr.visited,
                        pr.weight,
                        pr.product_length,
                        pr.product_height,
                        pr.product_width,
                        pr.product_diameter,
                        pr.product_preview_image,
                        pr.product_preview_back_image,
						cat.id,
                        cat.id as category_id,
                        cat.name as category_name, 
                        cat.short_description as category_short_description,
                        cat.description as category_description
                    FROM `#__redshop_product` AS pr
                    LEFT JOIN `#__redshop_product_category_xref` AS pr_cat USING (product_id)
                    LEFT JOIN `#__redshop_category` AS cat ON cat.id = pr_cat.category_id
                    LEFT JOIN `#__redshop_manufacturer` AS man USING(manufacturer_id)
                    WHERE " . implode(' AND ', $where) . " GROUP BY pr.product_id " . $o . " LIMIT " . $startIndex . ", " . $count;

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

        $product = new producthelper;
        //Redconfiguration needed for REDSHOP_FRONT_IMAGES_ABSPATH
        new Redconfiguration;
        $data = array();
        for ($i = 0; $i < count($result); $i++) {

            $r = array(
                'title'             => $result[$i]['name'],
                'url'               => 'index.php?option=com_redshop&view=product&pid=' . $result[$i]['product_id'] . '&cid=' . $result[$i]['category_id'],
                'description'       => $result[$i]['description'],
                'short_description' => $result[$i]['short_description'],
            );

            $r['image'] = ImageFallback::fallback(array(
                @$result[$i]['image'],
                @$result[$i]['product_preview_image'],
                @$result[$i]['image_thumbnail']
            ), REDSHOP_FRONT_IMAGES_ABSPATH . "product");

            if (empty($r['image'])) {
                $r['image'] = ImageFallback::fallback(array(), array(
                    $r['description'],
                    $r['short_description']
                ));
            }

            if (!empty($result[$i]['image_thumbnail'])) {
                $r['thumbnail'] = ResourceTranslator::urlToResource(REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $result[$i]['image_thumbnail']);
            } else if (!empty($result[$i]['image'])) {
                $r['thumbnail'] = ResourceTranslator::urlToResource(REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $result[$i]['image']);
            }

            $r['price'] = $product->getProductFormattedPrice($result[$i]['product_price']);

            if (!empty($result[$i]['product_preview_image'])) {
                $r['product_preview_image'] = ResourceTranslator::urlToResource(REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $result[$i]['product_preview_image']);
            }
            if (!empty($result[$i]['product_preview_back_image'])) {
                $r['product_preview_back_image'] = ResourceTranslator::urlToResource(REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $result[$i]['product_preview_back_image']);
            }

            $r += array(
                'unformatted_price'          => $result[$i]['product_price'],
                'discount_price'             => $result[$i]['discount_price'],
                'category_name'              => $result[$i]['category_name'],
                'category_url'               => 'index.php?option=com_redshop&view=category&cid=' . $result[$i]['category_id'] . '&layout=detail',
                'category_description'       => $result[$i]['category_description'],
                'category_short_description' => $result[$i]['category_short_description'],
                'manufacturer_name'          => $result[$i]['man_name'],
                'hits'                       => $result[$i]['visited'],
                'weight'                     => $result[$i]['weight'],
                'product_length'             => $result[$i]['product_length'],
                'product_height'             => $result[$i]['product_height'],
                'product_width'              => $result[$i]['product_width'],
                'product_diameter'           => $result[$i]['product_diameter'],
                'id'                         => $result[$i]['product_id']
            );

            $data[] = $r;
        }

        return $data;
    }

}
