<?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
 * ******************************************************************
 */
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
if (!class_exists('VirtueMartModelProduct')) {
    include JPATH_VM_ADMINISTRATOR . DIRECTORY_SEPARATOR .
        'models' . DIRECTORY_SEPARATOR . 'product.php';
}
if (!class_exists('MarketplaceHelper')) {
    include JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.
    DIRECTORY_SEPARATOR.'com_marketplace'.DIRECTORY_SEPARATOR.'helpers'.
    DIRECTORY_SEPARATOR.'marketplace.php';
}
if (!class_exists('MarketplaceModelAdminproducts')) {
    if (!class_exists('VmConfig')) {
        include JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR .
        'components' . DIRECTORY_SEPARATOR . 'com_virtuemart'.
        DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'config.php';
    }
    VmConfig::loadConfig();
    /**
     * MarketplaceModelAdminproducts 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 MarketplaceModelAdminproducts extends JModelList
    {
        var $_data = null;
        var $_total = null;
        var $_pagination = null;
        var $_id = null;
        var $products = null;
        var $decimals = array(
            'product_length',
            'product_width',
            'product_height',
            'product_weight',
            'product_packaging'
        );
        var $_onlyQuery  = false;
        /**
         * __construct function
         *
         * @param array $config var
         */
        public function __construct($config = array())
        {
            if (empty($config['filter_fields'])) {
                $config['filter_fields'] = array(
                    'product_price','pp.product_price',
                    'product_description_short',
                    'product_description  ',
                    'product_sku', 
                    'product_in_stock','v.product_in_stock',
                    'published',
                    'product_name',
                    'virtuemart_product_id','v.virtuemart_product_id'
                );
            }
            parent::__construct($config);
        }
        /**
         * GetListQuery function
         *
         * @return void
         */
        protected function getListQuery()
        {
            $db = $this->getDbo();
            $query = $db->getQuery(true);
            $params = JComponentHelper::getParams('com_languages');
            $defaultcountry_code = VmConfig::$vmlang;
            
            $query->select(
                $this->getState(
                    'list.select',
                    'v.published,v.product_in_stock,v.product_ordered, v.created_b'.
                    'y,v.virtuemart_product_id,v.product_sku,v.product_in_stock'
                )
            );
            $query->from($db->quoteName('#__virtuemart_products').' AS v');
            $query->select('vpe.product_name');
            $query->join(
                'LEFT',
                "`#__virtuemart_products_".$defaultcountry_code.
                "` AS vpe ON vpe.virtuemart_product_id = v.virtuemart_product_id"
            );
            $query->select('pp.product_price');
            $query->join(
                'LEFT',
                '#__virtuemart_product_prices AS pp ON pp.virtuemart_product_id '.
                '= v.virtuemart_product_id '
            );
            $query->join(
                'LEFT',
                '#__virtuemart_product_categories as c ON v.virtuemart_product_id'.
                '=c.virtuemart_product_id'
            );
            $query->select('u.username');
            $query->join('LEFT', '#__users AS u ON u.id = v.created_by');

            $query->where(
                'v.created_by NOT IN (SELECT seller_id FROM '.
                '#__marketplace_sellerprofile where is_seller = 1)'
            );
            $search = $this->getState('filter.search');
            if ($this->getState('filter.search') !== ''
                && $this->getState('filter.search') !== null
            ) {
                $search = $db->quote(
                    '%' . str_replace(
                        ' ',
                        '%',
                        $db->escape(
                            trim($this->getState('filter.search')),
                            true
                        ) . '%'
                    )
                );
                $searches   = array();
                $searches[] = 'v.virtuemart_product_id  LIKE ' . $search;
                $searches[] = 'vpe.product_name LIKE ' . $search;
                $query->where('(' . implode(' OR ', $searches) . ')');
            }
            $published = $this->getState('filter.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);
            }
            $query->order(
                $db->qn(
                    $db->escape($this->getState('list.ordering', 'vpe.product_name'))
                ) . ' ' . $db->escape($this->getState('list.direction', 'ASC'))
            );
            $query->group('v.virtuemart_product_id');
            return $query;
        }
        /**
         * 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;
            }
        }
        /**
         * GetForm function
         *
         * @param array   $data     var
         * @param boolean $loadData var
         * 
         * @return void
         */
        public function getForm($data = array(), $loadData = true)
        {
        
            $form = $this->loadForm(
                'com_marketplace.adminproducts',
                'assigntoseller',
                array(
                    'control' => 'jform',
                    'load_data' => $loadData
                )
            );
            if (empty($form)) {
                return false;
            }
            return $form;
        }
        /**
         * ProductCustomsfieldsClone function
         *
         * @param integer $virtuemart_product_id var
         * 
         * @return void
         */
        function productCustomsfieldsClone($virtuemart_product_id)
        {
            $db = JFactory::getDBO();
            $query = $db->getQuery(true);
            $query->select('*')
                ->from($db->quoteName('#__virtuemart_product_customfields'))
                ->where(
                    $db->quoteName('virtuemart_product_id').
                    "=".$db->quote($virtuemart_product_id)
                );
            $db->setQuery($query);
            try {
                $customfields = $db->loadAssocList();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            if ($customfields) {
                foreach ($customfields as &$customfield) {
                    unset(
                        $customfield['virtuemart_product_id'],
                        $customfield['virtuemart_customfield_id']
                    );
                }
                return $customfields;
            } else {
                return null;
            }
        }
        /**
         * CreateClone function
         *
         * @param [type] $id var
         * 
         * @return void
         */
        public function createClone($id)
        {
            $VmModel=VmModel::getModel('product');
            $newId=$VmModel->createClone($id);
            return $newId;
        }
        /**
         * CopyProduct function
         *
         * @param array   $cid      var
         * @param integer $sellerid var
         * 
         * @return void
         */
        public function copyProduct($cid, $sellerid)
        {
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $vmproduct=VmModel::getModel('product');
            $product = $vmproduct->getProduct($cid, false, false, false);
            $product->field = $this->productCustomsfieldsClone($cid);
            $product->virtuemart_product_id
                = $product->virtuemart_product_price_id = 0;
            $product->mprices = $this->productPricesClone($cid);
            $product->created_by = $sellerid;
            $product->slug = $product->slug . '-' . $cid;
            $product->originId = $cid;
            $product->published=1;
            $product->product_sales=0;
            $product->product_ordered=0;
            $langs = VmConfig::get('active_languages', array());
            if ($langs and count($langs) > 1) {
                $langTable = $this->getTable('products');
                foreach ($langs as $lang) {
                    if ($lang==VmConfig::$vmlangTag) {
                        continue;
                    }
                    $langTable->emptyCache();
                    $langTable->setLanguage($lang);
                    $langTable->_ltmp = true;
                    $langTable->load($cid);
                    if ($langTable->_loaded) {
                        if (!empty($langTable->virtuemart_product_id)) {
                            $langTable->virtuemart_product_id = $cid;
                            $langTable->bindChecknStore($langTable);
                        }
                    }
                }
            }
            $media=VmModel::getModel('media');
            $mediafiles=$media->getFiles(false, false, $cid);

            $profile = new stdClass();
            $profile->created_by = $sellerid;
            $profile->virtuemart_product_id = $cid;
            $profile->block=0;

            // Insert the object into the user profile table.
            $result = $db->insertObject('#__marketplace_product', $profile);
            MarketplaceHelper::productAssignedToSellerMail($cid, $sellerid);
            $query=$db->getQuery(true);
            $query->update($db->quoteName('#__virtuemart_products'));
            $query->set($db->quoteName('published')."=1");
            $query->set($db->quoteName('created_by')."=".$db->quote($sellerid));
            $query->where(
                $db->quoteName('virtuemart_product_id')."=".$db->quote($cid)
            );
            $db->setQuery($query);
            try {
                return $db->execute();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
                return false;
            }
        }
        /**
         * UpdateXrefAndChildTables function
         *
         * @param [type]  $data      var
         * @param [type]  $tableName var
         * @param boolean $preload   var
         * 
         * @return void
         */
        public function updateXrefAndChildTables($data, $tableName, $preload = false)
        {
            $VmModel=VmModel::getModel('product');
            $product_table_Parent = $VmModel->getTable($tableName);
            if ($preload) {
                $product_table_Parent->load($data['virtuemart_product_id']);
            }
            try {
                $product_table_Parent->bindChecknStore($data);
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            return $data;
        }
        /**
         * ProductPricesClone function
         *
         * @param integer $virtuemart_product_id var
         * 
         * @return void
         */
        function productPricesClone($virtuemart_product_id)
        {
            $db = JFactory::getDBO();
            $q = $db->getQuery(true);
            
            $q->select('*')
                ->from($db->quoteName('#__virtuemart_product_prices'))
                ->where(
                    $db->quoteName('virtuemart_product_id').
                    "=".$db->quote($virtuemart_product_id)
                );
            $db->setQuery($q);
            try {
                $prices = $db->loadAssocList();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            if ($prices) {
                foreach ($prices as $k => &$price) {
                    unset(
                        $price['virtuemart_product_id'],
                        $price['virtuemart_product_price_id']
                    );
                    foreach ($price as $i => $value) {
                        if (empty($mprices[$i])) {
                             $mprices[$i] = array();
                        }
                        $mprices[$i][$k] = $value;
                    }
                }
                return $mprices;
            } else {
                return null;
            }
        }
        /**
         * MoveProduct function
         *
         * @param array   $cid      var
         * @param integer $sellerid var
         * 
         * @return void
         */
        public function moveProduct($cid, $sellerid)
        {
            $db=$this->_db;
            $cids = implode(',', $cid);
            $i=0;
            if (count($cid)) {
                $productModel = VmModel::getModel('product');
                $totalMoveIds=array();
                foreach ($cid as $id) {
                    if ($productModel->checkChildProducts($id)!='0') {
                        $arr = array();
                        $newarr = array();
                        $arr = $productModel->getProductChildIds($id);
                        $temparr = $arr;
                        foreach ($arr as $arrvalue) {
                            $newarr=$productModel->getProductChildIds($arrvalue);
                            foreach ($newarr as $newarrvalue) {
                                $arr[]=$newarrvalue;
                            }
                        }
                        while (true) {
                            if (count($temparr)<>count($arr)) {
                                $temparr = $arr;
                                foreach ($arr as $arrvalue) {
                                    $newarr=$productModel->getProductChildIds(
                                        $arrvalue
                                    );
                                    foreach ($newarr as $newarrvalue) {
                                        $arr[]=$newarrvalue;
                                    }
                                }
                                $arr = array_unique($arr);
                            } else {
                                break;
                            }
                        }
                        $arr = array_values($arr);
                        $totalChilds=array();
                        foreach ($arr as $value) {
                            $check=$this->checkProductInMP($value, $sellerid);
                            if (!isset($check)) {
                                $totalChilds[]=$value;
                            }
                        }
                        array_unshift($totalChilds, $id);
                    } else {
                        $totalChilds=array();
                        $totalChilds[0]=$id;
                    }
                    $totalMoveIds=array_merge($totalMoveIds, $totalChilds);
                    MarketplaceHelper::productAssignedToSellerMail($id, $sellerid);
                }
                
                $queryproduct=$db->getQuery(true);
                $queryproduct->update($db->quoteName('#__virtuemart_products'))
                    ->set(
                        array(
                            $db->quoteName('created_by')."=".$sellerid."",
                            $db->quoteName('created_on')."= now()"
                        )
                    )
                    ->where(
                        $db->quoteName('virtuemart_product_id').
                        " IN(".implode(',', $totalMoveIds).")"
                    );
                try {
                    $db->setQuery($queryproduct);
                    $db->execute();
                }
                catch (Exception $e) {
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                }
                $queryprice=$db->getQuery(true);
                $queryprice->update($db->quoteName('#__virtuemart_product_prices'))
                    ->set(
                        array(
                            $db->quoteName('created_by')."=".$sellerid.""
                        )
                    )
                    ->where(
                        $db->quoteName('virtuemart_product_id').
                        " IN(".implode(',', $totalMoveIds).")"
                    );
                try {
                    $db->setQuery($queryprice);
                    $db->execute();
                } catch (Exception $e) {
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                }
                $customfields=$db->getQuery(true);
                $customfields->update(
                    $db->quoteName('#__virtuemart_product_customfields')
                )
                    ->set(
                        array($db->quoteName('created_by')."=".$sellerid)
                    )
                    ->where(
                        $db->quoteName('virtuemart_product_id').
                        " IN(".implode(',', $totalMoveIds).")"
                    );
                try {
                    $db->setQuery($customfields);
                    $db->execute();
                } catch (Exception $e) {
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                }
                foreach ($totalMoveIds as $key => $value) {
                    $profile = new stdClass();
                    $profile->created_by = $sellerid;
                    $profile->virtuemart_product_id = $value;
                    $profile->block=0;

                    // Insert the object into the user profile table.
                    $result = $db->insertObject('#__marketplace_product', $profile);
                }
            }
            return count($totalMoveIds);
        }
        /**
         * CheckProductInMP function
         *
         * @param [type] $id       var
         * @param [type] $sellerId var
         * 
         * @return void
         */
        public function checkProductInMP($id, $sellerId)
        {
            $db = $this->_db;
            $query=$db->getQuery(true);
            $query->select($db->quoteName('virtuemart_product_id'))
                ->from($db->quoteName('#__virtuemart_products'))
                ->where($db->quoteName('created_by')."=".$db->quote($sellerId))
                ->where($db->quoteName('virtuemart_product_id')."=".$db->quote($id));
            try {
                $db->setQuery($query);
                return $db->loadResult();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
            }
        }
        /**
         * PopulateState function
         *
         * @param [type] $ordering  var
         * @param [type] $direction var
         * 
         * @return void
         */
        protected function populateState($ordering = null, $direction = null)
        {
            $app = JFactory::getApplication('administrator');
            // Load the filter state.
            $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);
            $sellerId = $this->getUserStateFromRequest(
                $this->context.'.filter.seller_id', 'filter_seller_id', ''
            );
            $this->setState('filter.seller_id', $sellerId);
            $published = $this->getUserStateFromRequest(
                $this->context.'.filter.published', 'filter_state', ''
            );
            $this->setState('filter.published', $published);
            $language = $this->getUserStateFromRequest(
                $this->context.'.filter.language', 'filter_language', ''
            );
            $this->setState('filter.language', $language);
            // Load the parameters.
            $params = JComponentHelper::getParams('com_marketplace');
            $this->setState('params', $params);
            // List state information.
            parent::populateState('vpe.product_name', 'asc');
        }
        /**
         * Adminpublished function
         *
         * @param array   $cid     var
         * @param integer $publish var
         * 
         * @return void
         */
        function adminpublished($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 true;
        }
        /**
         * Adminunpublished function
         *
         * @param array   $cid       var
         * @param integer $unpublish var
         * 
         * @return void
         */
        function adminunpublished($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 true;
        }
    }
}