<?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');
jimport('joomla.access.access');
if (!class_exists('VirtueMartModelUser')) {
    include JPATH_VM_ADMINISTRATOR .'/'. 'models'.'/'. 'user.php';
}
if (!class_exists('MarketplaceModelMarketplace')) {
    /**
     * MarketplaceModelMarketplace 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 MarketplaceModelMarketplace extends JModelList
    {
        var $_data = null;
        var $_total = null;
        var $_pagination = null;
        var $_id = null;
        /**
         * This is getCountryCode2 function
         *
         * @param integer $country_id var
         * 
         * @return void
         */
        public function getCountryCode2($country_id=0)
        {
            $db=$this->_db;
            $query=$db->getQuery(true);
            $query->select($db->quoteName('country_2_code'))
                ->from($db->quoteName('#__virtuemart_countries'))
                ->where(
                    $db->quoteName('virtuemart_country_id').
                    "=".$db->quote($country_id)
                );
            $db->setQuery($query);
            return $db->loadResult();
        }
        /**
         * This is saveItem function
         *
         * @param array $submit var
         * 
         * @return void
         */
        public function saveItem($submit=array())
        {
            $db = $this->_db;
            // Create an object for the record we are going to update.
            $object = new stdClass();
            // Must be a valid primary key value.
            $object->seller_id = $submit['seller_id'];
            // Update their details in the users table using id as the primary key.
            
            $inserarray=array();
            if (isset($submit['screenname'])&& strlen($submit['screenname'])) {
                $object->screenname = $submit['screenname'];
            }
            if (isset($submit['gender'])&& strlen($submit['gender'])) {
                $object->gender = $submit['gender'];
            }
            if (isset($submit['cover'])&& strlen($submit['cover'])) {
                $object->companybanner = $submit['cover'];
            }
            if (isset($submit['shoplogo'])&& strlen($submit['shoplogo'])) {
                $object->companylogo = $submit['shoplogo'];
            }
            if (isset($submit['shoplocality'])&& strlen($submit['shoplocality'])) {
                $object->companylocality = $submit['shoplocality'];
            }
            if (isset($submit['shopname'])&& strlen($submit['shopname'])) {
                $object->companyname = $submit['shopname'];
            }
            if (isset($submit['shopdescription'])
                && strlen($submit['shopdescription'])
            ) {
                $object->companydescription = $submit['shopdescription'];
            }
            if (isset($submit['countrylogo'])&& strlen($submit['countrylogo'])) {
                $object->countrylogo = $submit['countrylogo'];
            }
            if (isset($submit['shortdescription'])
                && strlen($submit['shortdescription'])
            ) {
                $object->descriptioninhtml = $submit['shortdescription'];
            }
            if (isset($submit['first_name'])
                && strlen($submit['first_name'])
            ) {
                $object->first_name = $submit['first_name'];
            }
            if (isset($submit['last_name'])
                && strlen($submit['last_name'])
            ) {
                $object->last_name = $submit['last_name'];
            }
            if (isset($submit['address'])
                && strlen($submit['address'])
            ) {
                $object->address = $submit['address'];
            }
            if (isset($submit['zip'])
                && strlen($submit['zip'])
            ) {
                $object->zip = $submit['zip'];
            }
            if (isset($submit['phone'])
                && strlen($submit['phone'])
            ) {
                $object->phone = $submit['phone'];
            }
            if (isset($submit['state_vm'])
                && strlen($submit['state_vm'])
            ) {
                $object->state_vm = $submit['state_vm'];
            }

            if (isset($submit['latitude'])
                && strlen($submit['latitude'])
                && isset($submit['logtitude'])&& strlen($submit['logtitude'])
            ) {
                $object->shop_location = $submit['latitude']."::".$submit['logtitude'];
            }
            if (isset($submit['facebook']) && $submit['facebook']) {
                $social_mode[]='FACEBOOK_CHECK';
            }
            $social_id[]=$submit['social0'];
            if (isset($submit['twitter']) && $submit['twitter']) {
                $social_mode[]='TWITTER_CHECK';
            }
            $social_id[]=$submit['social1'];
            if (isset($submit['google']) && $submit['google']) {
                $social_mode[]='GOOGLE_CHECK';
            }
            $social_id[]=$submit['social2'];
            if (isset($submit['linkedin'])&& $submit['linkedin']) {
                $social_mode[]='LINKEDIN_CHECK';
            }
            $social_id[]=$submit['social3'];
            $object->social_mode = implode(',', $social_mode);
            $object->social_id = implode(',', $social_id);
            $object->payment_mode = $submit['payment_mode'];
            $object->payment_desc = $submit['payment_desc'];
            
            try{
                $result = $this->_db->updateObject(
                    '#__marketplace_sellerprofile', $object, 'seller_id'
                );
            } catch(Exception $e){
                $this->setError($e->getMessage());
                return false;
            }
            return true;
        }
        /**
         * __construct function
         *
         * @param array $config var
         */
        public function __construct($config = array())
        {
            if (empty($config['filter_fields'])) {
                $config['filter_fields'] = array(
                    'c.seller_id',
                    'c.first_name',
                    'c.is_seller',
                    'a.username',
                    'a.email',
                    'a.block',
                    'mc.commision',
                );
            }
            parent::__construct($config);
        }
        /**
         * This is getEmail function
         *
         * @param array $cid var
         * 
         * @return void
         */
        public function getEmail($cid=array())
        {
            $db=JFactory::getDBO();
            $email=array();
            foreach ($cid as $value) {
                $query=$db->getQuery(true);
                $query->select($db->quoteName('email'))
                    ->from($db->quoteName('#__users'))
                    ->where($db->quoteName('id')."=".$value);
                $db->setQuery($query);
                try{
                    $email[]=$db->loadResult();
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                }
            }
            return $email;
        }
        /**
         * This is getListQuery function
         *
         * @return void
         */
        protected function getListQuery()
        {
            $db = $this->getDbo();
            $query = $db->getQuery(true);
            $query->select(
                $this->getState(
                    'list.select',
                    'c.*',
                    'c.is_seller AS partner'
                )
            );
            $query->from($db->quoteName('#__marketplace_sellerprofile').' AS c');
            $search = $this->getState('filter.search');
            $status=$this->getState('filter.status');
            if (is_numeric($status)) {
                $query->where('c.is_seller != ' . (int) $status);
            }
            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[] = 'a.id LIKE ' . $search;
                $searches[] = 'a.username LIKE ' . $search;
                $searches[] = 'a.email LIKE ' . $search;
                $query->where('(' . implode(' OR ', $searches) . ')');
            }
            $query->select('a.email');
            $query->select('mc.commision');
            $query->select('mc.commision_type')
                ->join('LEFT', '#__users AS a ON a.id = c.seller_id ')
                ->select('g.group_id AS groupid')
                ->join('LEFT', '#__user_usergroup_map AS g ON g.user_id = a.id')
                ->join(
                    'LEFT',
                    '#__marketplace_commision AS mc ON mc.seller_id=c.seller_id'
                );
            
            $query->group($db->quoteName('c.seller_id'));
            $productId = $this->getState('filter.seller_id');
            if (is_numeric($productId)) {
                $query->where('a.seller_id = '.(int) $productId);
            }
            $published = $this->getState('filter.published');
            if (is_numeric($published)) {
                $query->where('c.is_seller = '.(int) $published);
            } elseif ($published === '') {
                $query->where('(c.is_seller IN (0, 1))');
            }
            $orderCol       = $this->state->get('list.ordering', 'seller_id');
            $orderDirn      = $this->state->get('list.direction', 'asc');
            
            $query->order($db->escape($orderCol.' '.$orderDirn));
            return $query;
        }
        /**
         * GetTable function
         *
         * @param string $type   var
         * @param string $prefix var
         * @param array  $config var
         * 
         * @return void
         */
        public function getTable(
            $type = 'Marketplace', $prefix = 'MarketplaceTable', $config = array()
        ) {
            return JTable::getInstance($type, $prefix, $config);
        }
        /**
         * Add Partner function
         *
         * @param array   $cid var
         * @param integer $add var
         * 
         * @return void
         */
        function addpartner($cid = array(), $add = 1)
        {
            if (count($cid)) {
                $cids = implode(',', $cid);
                $db=JFactory::getDBO();
                $query=$db->getQuery(true);
                $query->update($db->quoteName('#__marketplace_sellerprofile'))
                    ->set($db->quoteName('is_seller')."="."1")
                    ->where($db->quoteName('seller_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('#__users'))
                    ->set($db->quoteName('block')."="."0")
                    ->set($db->quoteName('activation')."="."0")
                    ->where($db->quoteName('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('#__virtuemart_products', 'a'))
                    ->set($db->quoteName('a.published')."=".'1')
                    ->where($db->quoteName('a.created_by').' IN('.$cids.')');
        
            $db->setQuery($query);
            try{
                $db->execute();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            return true;
        }
        /**
         * Deleteseller function
         *
         * @param array $cid var
         * 
         * @return void
         */
        function deleteseller($cid = array())
        {
            $db=JFactory::getDbo();
            $del_suer=array();
            if (count($cid)) {
                foreach ($cid as $key => $val) {
                    plgSystemMarketplace::OnSellerDeleteFromJoomla($val);
                }
                $cids = implode(',', $cid);
                if (!$db->execute()) {
                    $this->setError($db->getErrorMsg());
                    return false;
                }
                $params = JComponentHelper::getParams('com_marketplace');
                $product_action_seller_delete = trim(
                    $params->get('product_action_seller_delete')
                );
            }
            
            $total  = count($cid);
            $msg  = $total.' '.JText::_('USER_DELETE');
            return $msg;
        }
        /**
         * GetForm function
         *
         * @param array   $data     var
         * @param boolean $loadData var
         * 
         * @return void
         */
        public function getForm($data = array(), $loadData = true)
        {
            $form = $this->loadForm(
                'com_marketplace.marketplace', 'sendmail',
                array('control' => 'jform', 'load_data' => $loadData)
            );
            if (empty($form)) {
                return false;
            }
            return $form;
        }
        /**
         * Denypartner function
         *
         * @param array   $cid  var
         * @param integer $deny var
         * 
         * @return void
         */
        function denypartner($cid = array(), $deny = 0)
        {
            $db=JFactory::getDBO();
            if (count($cid)) {
                $cids = implode(',', $cid);
                $query=$db->getQuery(true);
                $query->update($db->quoteName('#__marketplace_sellerprofile'))
                    ->set($db->quoteName('is_seller')."=".(int)$deny)
                    ->where($db->quoteName('seller_id').' IN('.$cids.')');
            
                $db->setQuery($query);
                if (!$db->execute()) {
                    $this->setError($db->getErrorMsg());
                    return false;
                }
                $query=$db->getQuery(true);
                $query->update($db->quoteName('#__virtuemart_products', 'a'))
                    ->set($db->quoteName('a.published')."=".'0')
                    ->where($db->quoteName('a.created_by').' IN('.$cids.')');
            
                $db->setQuery($query);
                try{
                    $db->execute();
                }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');
            // 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('a.username', 'asc');
        }
        /**
         * GetSellerInfo function
         *
         * @param [type] $seller_id var
         * 
         * @return void
         */
        public function getSellerInfo($seller_id)
        {
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $query->select('a.*,b.email')
                ->from($db->quoteName('#__marketplace_sellerprofile', 'a'))
                ->join(
                    'LEFT',
                    $db->quoteName('#__users', 'b') . ' ON (' . 
                    $db->quoteName('a.seller_id') . ' = ' .
                    $db->quoteName('b.id') . ')'
                )
                ->where($db->quoteName('seller_id')."=".$seller_id)
                ->group($db->quoteName('b.id'));
            $db->setQuery($query);
            try{
                return $db->loadObject();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
        }
        /**
         * GetCountry function
         *
         * @return void
         */
        public function getCountry()
        {
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $query->select('*')
                ->from($db->quoteName('#__virtuemart_countries'));
            $db->setQuery($query);
            try{
                $country_result = $db->loadObjectList();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            return $country_result;
        }
        /**
         * GetCountryIdByCountryCode function
         *
         * @param string $country_code Country code 2
         * 
         * @return void
         */
        public function getCountryIdByCountryCode($country_code='')
        {
            if ($country_code=='') {
                return false;
            }
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $query->select($db->quoteName('virtuemart_country_id'))
                ->from($db->quoteName('#__virtuemart_countries'))
                ->where(
                    $db->quoteName('country_2_code')."=".$db->quote($country_code)
                );
            $db->setQuery($query);
            try{
                $country_result = $db->loadObject();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            return $country_result;
        }
        /**
         * GetCountryIdNameList function
         *
         * @param boolean $published Only published
         * 
         * @return void
         */
        public function getCountryIdNameList($published=true)
        {
            $status = $published?1:0;
            $db=JFactory::getDBO();
            $query=$db->getQuery(true);
            $query->select(
                $db->quoteName(
                    array('virtuemart_country_id','country_name'),
                    array('value','text')
                )
            )
                ->from($db->quoteName('#__virtuemart_countries'))
                ->where($db->quoteName('published')."=".$status)
                ->order($db->quoteName('country_name').' ASC');
            $db->setQuery($query);
            try{
                $country_result = $db->loadObjectList();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return array();
            }
            return $country_result;
        }
    }
}
