<?php
/**
 * Marketplace - Component Marketplace 
 * ******************************************************************
 *
 * PHP version 7.0
 *
 * @category   Component
 * @package    Joomla
 * @author     WebKul software private limited <support@webkul.com>
 * @copyright  2010 WebKul software private limited
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @version    GIT:5.2
 * @filesource http://store.webkul.com
 * @link       Technical Support:  webkul.uvdesk.com
 * ******************************************************************
 */
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');

if (!class_exists('VmConfig')) {
    include JPATH_ADMINISTRATOR .
    '/components/com_virtuemart/helpers/config.php';
}
if (!class_exists('MarketplaceModelProducts')) {
    /**
     * MarketplaceModelProducts class
     * 
     * @category Component
     * @package  Joomla
     * @author   WebKul software private limited <support@webkul.com>
     * @license  http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
     * @link     Technical Support:  webkul.uvdesk.com
     */
    class MarketplaceModelProducts extends JModelList
    {
        var $_data = null;
        var $_total = null;
        var $_pagination = null;
        var $_id = null;
        /**
         * Undocumented function
         *
         * @param array $config var
         */
        public function __construct($config = array())
        {
            if (empty($config['filter_fields'])) {
                $config['filter_fields'] = array(
                    'v.virtuemart_product_id',
                    'b.virtuemart_product_id',
                    'product_description','z.product_description',
                    'productname','z.product_name',
                    'v.product_sku', 'v.product_sku',
                    'price','v.price',
                    'v.product_in_stock','v.product_in_stock',
                    'state','v.published',
                    'username','u.username'
                );
            }
            parent::__construct($config);
        }
        /**
         * GetListQuery function
         *
         * @return void
         */
        protected function getListQuery()
        {
            $db  = $this->getDbo();
            $vmconf = VmConfig::loadConfig();
            $query = $db->getQuery(true);
            $query->select(
                $this->getState('list.select', 'a.block')
            )
                ->select('v.*', 'z.*');
            $query->from($db->quoteName('#__virtuemart_products').' AS v');
            $search = $this->getState('filter.search');
            if (!empty($search)) {
                if (stripos($search, 'productname:') === 0) {
                    $query->where('z.product_name = '.(int) substr($search, 3));
                } else {
                    $search = $db->Quote('%'.$db->escape($search, true).'%');
                    $query->where('(z.product_name LIKE '.$search.')');
                }
            }
            
            // Join over the categories.
            $query->select(
                'v.published,v.product_in_stock,v.product_o'.
                'rdered,v.product_sku,z.product_name'
            );
            $query->join(
                'LEFT',
                '#__marketplace_product AS a ON a.virtuemart_p'.
                'roduct_id = v.virtuemart_product_id'
            );
            $query->join(
                'LEFT',
                '#__virtuemart_products_'.$vmconf->get("vmlang").
                ' AS z ON z.virtuemart_product_id = v.virtuemart_product_id'
            );

            $query->select('u.username');
            $query->join('LEFT', '#__users AS u ON u.id = v.created_by');
            $query->join(
                'LEFT',
                '#__virtuemart_product_categories as c ON v.vir'.
                'tuemart_product_id=c.virtuemart_product_id'
            );
            
            $productId = $this->getState('filter.virtuemart_product_id');
            if (is_numeric($productId)) {
                $query->where('v.virtuemart_product_id = '.(int) $productId);
            }
    
            $sellerId = $this->getState('filter.seller_id');
            
            if (is_numeric($sellerId)) {
                $query->where('v.created_by = '.(int) $sellerId);
            } else {
                
                $sub_query = $db->getQuery(true);
                $sub_query->select($db->quoteName('seller_id'))
                    ->from($db->quoteName('#__marketplace_sellerprofile'));
                $query->where('v.created_by IN('.$sub_query.')');
            }
            $published = $this->getState('list.published');
            if (is_numeric($published)) {
                $query->where('v.published = '.(int) $published);
            } elseif ($published === '') {
                $query->where('(v.published IN (0, 1))');
            }
            $categoryId=$this->getState('filter.vmcategory');
            if (is_numeric($categoryId)) {
                $query->where('c.virtuemart_category_id= '.(int) $categoryId);
            }
            $orderCol       = $this->state->get('list.ordering', 'z.product_name');
            $orderDirn      = $this->state->get('list.direction', 'asc');
            if ($orderCol == 'v.ordering' || $orderCol == 'username') {
                $orderCol = 'z.product_name '.$orderDirn.', z.product_name';
            }
            
            $query->order($db->escape($orderCol.' '.$orderDirn));
            $query->group('v.virtuemart_product_id');
            return $query;
        }
        /**
         * GetTable function
         *
         * @param string $type   var
         * @param string $prefix var
         * @param array  $config var
         * 
         * @return void
         */
        public function getTable(
            $type = 'Product', $prefix = 'MarketplaceTable', $config = array()
        ) {
            return JTable::getInstance($type, $prefix, $config);
        }
        /**
         * GetUserName function
         *
         * @param integer $user var
         * 
         * @return void
         */
        public function getUserName($user=0)
        {
            $query=$this->_db->getQuery(true);
            $query->select($this->_db->quoteName('username'))
                ->from($this->_db->quoteName('#__users')) 
                ->where($this->_db->quoteName('id')."=".$user);
            $this->_db->setQuery($query);
            try{
                return $this->_db->loadResult();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
        }
        /**
         * Published function
         *
         * @param array   $cid     var
         * @param integer $publish var
         * 
         * @return void
         */
        function published($cid = array(), $publish = 1)
        {
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);

            if (count($cid)) {
                $cids = implode(',', $cid);
                $fields = array($db->quoteName('published')."=".(int)$publish);
                $query->update($db->quoteName('#__virtuemart_products'))
                    ->set($fields)
                    ->where($db->quoteName('virtuemart_product_id')."IN(".$cids.")");
                $db->setQuery($query);
                try{
                    if (!$db->execute()) {
                        $this->setError($db->getErrorMsg());
                        return false;
                    }
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                }
                $query=$db->getQuery(true);
                $query->update($db->quoteName('#__marketplace_product'))
                    ->set($db->quoteName('block')."=0")
                    ->where($db->quoteName('virtuemart_product_id')."IN(".$cids.")");
                $db->setQuery($query);
                try{
                    if (!$db->execute()) {
                        $this->setError($db->getErrorMsg());
                        return false;
                    }
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                }
            } 
            return true;
        }
        /**
         * Unpublished function
         *
         * @param array   $cid       var
         * @param integer $unpublish var
         * 
         * @return void
         */
        function unpublished($cid = array(), $unpublish = 0)
        {
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $fields = array($db->quoteName('published')."=".(int)$unpublish);
            if (count($cid)) {
                $cids = implode(',', $cid);
                $query->update($db->quoteName('#__virtuemart_products'))
                    ->set($fields)
                    ->where($db->quoteName('virtuemart_product_id')."IN(".$cids.")");
                $db->setQuery($query);
                try{
                    if (!$db->execute()) {
                        $this->setError($db->getErrorMsg());
                        return false;
                    }
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                } 
                $query=$db->getQuery(true);
                $query->update($db->quoteName('#__marketplace_product'))
                    ->set($db->quoteName('block')."=".(int)1)
                    ->where($db->quoteName('virtuemart_product_id')."IN(".$cids.")");
                $db->setQuery($query);
                try{
                    if (!$db->execute()) {
                        $this->setError($db->getErrorMsg());
                        return false;
                    }
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                }
            }
            return true;
        }
        /**
         * PopulateState function
         *
         * @param [type] $ordering  var
         * @param [type] $direction var
         * 
         * @return void
         */
        protected function populateState($ordering = null, $direction = null)
        {
            $app = JFactory::getApplication('administrator');
            $search = $this->getUserStateFromRequest(
                $this->context.'.filter.search', 'filter_search'
            );
            $this->setState('filter.search', $search);
            $state = $this->getUserStateFromRequest(
                $this->context.'.filter.state', 'filter_state', '', 'string'
            );
            $this->setState('filter.state', $state);
            $categoryId = $this->getUserStateFromRequest(
                $this->context.'.filter.vmcategory', 'filter_vmcategory'
            );
            $this->setState('filter.vmcategory', $categoryId);
            $seller = $this->getUserStateFromRequest(
                $this->context . '.filter.seller_id', 'filter_seller_id'
            );
            $this->setState('filter.seller_id', $seller);
            $params = JComponentHelper::getParams('com_marketplace');
            $this->setState('params', $params);
            parent::populateState('z.product_name', 'asc');
        }
        /**
         * Deleteproducts function
         *
         * @param array $ids var
         * 
         * @return void
         */
        public function deleteproducts($ids=array())
        {
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $query->delete($db->quoteName('#__marketplace_product'))
                ->where(
                    $db->quoteName('virtuemart_product_id').
                    "IN (".implode(',', $ids).")"
                );
            $db->setQuery($query);
            try{
                return $db->execute();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
        }
    }
}
