<?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();
/**
 * MarketplaceModelMpusers 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 MarketplaceModelMpusers extends JModelList
{
    /**
     * __construct function
     *
     * @param array $config var
     */
    public function __construct($config = array())
    {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                'id', 'a.id',
                'name', 'a.name',
                'username', 'a.username',
                'email', 'a.email',
                'block', 'a.block',
                'sendEmail', 'a.sendEmail',
                'registerDate', 'a.registerDate',
                'lastvisitDate', 'a.lastvisitDate',
                'activation', 'a.activation',
                'active',
                'group_id',
                'range',
                'state',
            );
        }
        parent::__construct($config);
    }
    /**
     * CheckSeller function
     *
     * @param [type] $id var
     * 
     * @return void
     */
    public function checkSeller($id)
    {
        $db=$this->_db;
        $query=$db->getQuery(true);
        $query->select('*')
            ->from($db->quoteName('#__marketplace_sellerprofile'))
            ->where($db->quoteName('seller_id')."=".$id);
        try{
            $db->setQuery($query);
            return $db->loadObject();
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
        }
    }
    /**
     * GetTable function
     *
     * @param string $type   var
     * @param string $prefix var
     * @param array  $config var
     * 
     * @return void
     */
    public function getTable($type = 'User', $prefix = 'JTable', $config = array())
    {
        $table = JTable::getInstance($type, $prefix, $config);
        return $table;
    }
    /**
     * Block function
     *
     * @param [type]  $pks   var
     * @param integer $value var
     * 
     * @return void
     */
    public function block(&$pks, $value = 1)
    {
    
        $app        = JFactory::getApplication();
        $dispatcher = JEventDispatcher::getInstance();
        $user       = JFactory::getUser();
        $iAmSuperAdmin = $user->authorise('core.admin');
        $table         = $this->getTable();
        $pks           = (array) $pks;
        JPluginHelper::importPlugin($this->events_map['save']);
        foreach ($pks as $i => $pk) {
            if ($value == 1 && $pk == $user->get('id')) {
                unset($pks[$i]);
                JError::raiseWarning(
                    403, JText::_('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF')
                );
            } elseif ($table->load($pk)) {
                $old   = $table->getProperties();
                $allow = $user->authorise('core.edit.state', 'com_marketplace');
                $allow = (!$iAmSuperAdmin && JAccess::check($pk, 'core.admin'))
                    ? false : $allow;
                $options = array(
                    'clientid' => 0
                );
                if ($allow) {
                    // Skip changing of same state
                    if ($table->block == $value) {
                        unset($pks[$i]);
                        continue;
                    }
                    $table->block = (int) $value;
                    if ($table->block === 0) {
                        $table->resetCount = 0;
                    }
                    // Allow an exception to be thrown.
                    try
                    {
                        if (!$table->check()) {
                            $this->setError($table->getError());
                            return false;
                        }
                        // Trigger the before save event.
                        $result = $dispatcher->trigger(
                            $this->event_before_save,
                            array($old, false, $table->getProperties())
                        );
                        if (in_array(false, $result, true)) {
                            return false;
                        }
                        // Store the table.
                        if (!$table->store()) {
                            $this->setError($table->getError());
                            return false;
                        }
                        // Trigger the after save event
                        $dispatcher->trigger(
                            $this->event_after_save,
                            array($table->getProperties(), false, true, null)
                        );
                    }
                    catch (Exception $e)
                    {
                        $this->setError($e->getMessage());
                        return false;
                    }
                    // Log the user out.
                    if ($value) {
                        $app->logout($table->id, $options);
                    }
                } else {
                    // Prune items that you can't change.
                    unset($pks[$i]);
                    JError::raiseWarning(
                        403,
                        JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')
                    );
                }
            }
        }
        return true;
    }
    /**
     * Activate function
     *
     * @param array $pks var
     * 
     * @return void
     */
    public function activate(&$pks)
    {
        $db=JFactory::getDBO();
        $dispatcher = JEventDispatcher::getInstance();
        $user       = JFactory::getUser();
        $query = $db->getQuery(true);
        $query->select($db->quoteName('id'))
            ->from($db->quoteName('#__users'))
            ->where($db->quoteName('activation')." != 0")
            ->where($db->quoteName('activation')." != ''");
        $db->setQuery($query);
        try{
            $toids=$db->loadObjectList();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        $i=0;
        $id=array();
        foreach ($toids as $idsu) {
            $id[]=$idsu->id;
        }
        foreach ($pks as $i => $value) {
            if (!in_array($pks[$i], $id)) {
                unset($pks[$i]);
            } else {
                $i++;
            }
        }
        $pks=array_values($pks);
        $i=0;
        foreach ($pks as $value) {
            $query=$db->getQuery(true);
                    $query->update($db->quoteName('#__users'));
            $query->set('activation=""');
                $query->where('id="'.$value.'"');
            $db->setQuery($query);
            try{
                $db->execute();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
        }
        return count($id);
    }
    /**
     * 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);
        $active = $this->getUserStateFromRequest(
            $this->context . '.filter.active', 'filter_active'
        );
        $this->setState('filter.active', $active);
        $state = $this->getUserStateFromRequest(
            $this->context . '.filter.state', 'filter_state'
        );
        $this->setState('filter.state', $state);
        
        $params = JComponentHelper::getParams('com_marketplace');
        $this->setState('params', $params);
        parent::populateState('a.name', 'asc');
    }
    /**
     * GetListQuery function
     *
     * @return void
     */
    protected function getListQuery()
    {
        // Create a new query object.
        $db    = $this->getDbo();
        $query = $db->getQuery(true);
        // Select the required fields from the table.
        $query->select(
            $this->getState(
                'list.select',
                'a.*'
            )
        );
        $query->from($db->quoteName('#__users') . ' AS a');
        // If the model is set to check item state, add to the query.
        $state = $this->getState('filter.state');
        if (is_numeric($state)) {
            $query->where('a.block != ' . (int) $state);
        }
        // If the model is set to check the activated state, add to the query.
        $active = $this->getState('filter.active');
        if (is_numeric($active)) {
            if ($active == '0') {
                $query->where(
                    'a.activation IN (' . $db->quote('') .
                    ', ' . $db->quote('0') . ')'
                );
            } elseif ($active == '1') {
                $query->where($query->length('a.activation') . ' > 1');
            }
        }
        // Filter the items over the search string if set.
        if ($this->getState('filter.search') !== ''
            && $this->getState('filter.search') !== null
        ) {
            // Escape the search token.
            $search = $db->quote(
                '%' . str_replace(
                    ' ',
                    '%',
                    $db->escape(trim($this->getState('filter.search')), true) . '%'
                )
            );
            // Compile the different search clauses.
            $searches   = array();
            $searches[] = 'a.name LIKE ' . $search;
            $searches[] = 'a.username LIKE ' . $search;
            $searches[] = 'a.email LIKE ' . $search;
            // Add the clauses to the query.
            $query->where('(' . implode(' OR ', $searches) . ')');
        }
        $query->order(
            $db->qn($db->escape($this->getState('list.ordering', 'a.name'))) .
            ' ' . $db->escape($this->getState('list.direction', 'ASC'))
        );
        
        return $query;
    }
    /**
     * Synchronizeuser function
     *
     * @param array $ids var
     * 
     * @return void
     */
    function synchronizeuser($ids=array())
    {
        $db=JFactory::getDBO();
        $query=$db->getQuery(true);
        $query->select($db->quoteName('seller_id'))
            ->from($db->quoteName('#__marketplace_sellerprofile'));
        $db->setQuery($query);
        try{
            $wk_sellers=$db->loadColumn();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        $wk_seller = implode(',', $wk_sellers);
        if (!strlen($wk_seller)) {
            $wk_seller =0;
        }
        $query=$db->getQuery(true);
        $query->select('id')
            ->from($db->quoteName('#__users'))
            ->where('id NOT IN ('.$wk_seller.')');
        $db->setQuery($query);
        try{
            $wk_nonsellers = $db->loadAssocList();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        $wk_nonseller=array();
        foreach ($wk_nonsellers as $key => $value) {
            $wk_nonseller[]=$value['id'];
        }
        $wk_nonsellers=array_intersect($wk_nonseller, $ids);
        $params = JComponentHelper::getParams('com_marketplace');
        $comm = trim($params->get('commision'));
        $comm_type = trim($params->get('commision_option'));
        $count = 0;
        $super_msg="";
        foreach ($wk_nonsellers as $key=>$data) {
            $user = JFactory::getUser($data);
            $groups = $user->groups;
            if (!in_array(8, $groups)) {
                $query=$db->getQuery(true);
                $query->select($db->quoteName('virtuemart_user_id'))
                    ->from($db->quoteName('#__virtuemart_userinfos'))
                    ->where(
                        $db->quoteName('virtuemart_user_id')."=".
                        $db->quote($user->id)
                    );
                $db->setQuery($query);
                $result=$db->loadResult();
                if (!isset($result)) {
                    $query=$db->getQuery(true);
                    $column=array('virtuemart_user_id','address_type');
                    $value=array($db->quote($user->id), $db->quote('BT'));
                    $query->insert($db->quoteName("#__virtuemart_userinfos"))
                        ->columns($db->quoteName($column))
                        ->values(implode(",", $value));
                    $db->setQuery($query);
                    try{
                        $db->execute();
                    }catch(Exception $e){
                        JFactory::getApplication()->enqueueMessage(
                            $e->getMessage(), 'error'
                        );
                        return false;
                    }
                }
                $query=$db->getQuery(true);
                $column=array('seller_id','is_seller','commission');
                $value=array($data, '1',$comm);
                $query->insert($db->quoteName('#__marketplace_sellerprofile'))
                    ->columns($db->quoteName($column))
                    ->values("'".implode("','", $value)."'");
                $db->setQuery($query);
                try{
                    $db->execute();
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                }
                $query=$db->getQuery(true);
                $query->select('*')
                    ->from($db->quoteName('#__marketplace_commision'))
                    ->where($db->quoteName('seller_id').'='.$data);
                $db->setQuery($query);
                try{
                    $rs=$db->loadObject();
                }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(), 'error'
                    );
                    return false;
                }
                if (!class_exists('VmConfig')) {
                    include JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.
                    DIRECTORY_SEPARATOR.'com_virtuemart'.DIRECTORY_SEPARATOR.
                    'helpers'.DIRECTORY_SEPARATOR.'config.php';
                }
                $config = VmConfig::loadConfig();
                if (!class_exists('currencydisplay')) {
                    include JPATH_ADMINISTRATOR .
                    '/components/com_virtuemart/helpers/currencydisplay.php';
                }
                $currency = CurrencyDisplay::getInstance();
                $currency_id=$currency->getCurrencyForDisplay();
                if (!$rs) {
                    $query=$db->getQuery(true);
                    $columns=array(
                        'commision', 'seller_id','total_sales',
                        'amount_recieved','amount_remain',
                        'amount_paid','currency','commision_type'
                    );
                    $values=array($comm,$data,0,0,0,0,$currency_id,$comm_type);
                    $query->insert($db->quoteName('#__marketplace_commision'))
                        ->columns($columns)
                        ->values("'".implode("','", $values)."'");
                    $db->setQuery($query);
                    try{
                        $db->query();
                    }catch(Exception $e){
                        JFactory::getApplication()->enqueueMessage(
                            $e->getMessage(), 'error'
                        );
                        return false;
                    }
                }
                $params = JComponentHelper::getParams('com_marketplace');
                $body = trim($params->get('mp_temp_convert_seller'));
                $subject = trim($params->get('mp_sub_convert_seller'));
                $config=JFactory::getConfig();
                $mailer=JFactory::getMailer();
                $mailer->setSender($config->get('mailfrom'));
                $mailer->addRecipient($user->email);
                $mailer->isHtml(true);
                /* Replacing Value in Templates*/
                $body = str_replace(
                    '{[USER_NAME]}', ucwords($user->username),
                    $body
                );
                $subject= str_replace(
                    '{[USER_NAME]}', ucwords($user->username),
                    $subject
                );
                $body = str_replace(
                    '{[SELLER_SCREEN]}', ucwords($user->name),
                    $body
                );
                $subject= str_replace(
                    '{[SELLER_SCREEN]}', ucwords($user->name),
                    $subject
                );
                $body = str_replace(
                    '{[SITE_FROM_NAME]}', ucwords($config->get('fromname')),
                    $body
                );
                $mailer->setSubject($subject);
                $mailer->setBody($body);
                $mailer->send();
                $count++;
            } else {
                $super_msg= JText::_('SUPER_NOUSER_SYNCHRONIZE');
            }
        }
        $total  = $count;
        $msg="";
        if ($super_msg=="") {
            if ($count == 0) { 
                $msg  = JText::_('NOUSER_SYNCHRONIZE');
            } else {
                $msg  = $total.' '.JText::_('USER_SYNCHRONIZE');
            }
        }
        return $msg.$super_msg;
    }
}