<?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');
/**
 * MarketplaceModelCommisions 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 MarketplaceModelCommisions extends JModelList
{
    var $_data = null;
    var $_total = null;
    var $_pagination = null;
    var $_id = null;
    /**
     * __construct function
     *
     * @param array $config var
     */
    public function __construct($config = array())
    {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                'a.commision_id',
                'a.commision', 'seller_id',
                'a.total_sales', 'a.amount_recieved',
                'a.amount_remain', 'a.amount_paid', 'us.email',
                'us.username','us.registerDate'
            );
        }
        if (!class_exists('VmConfig')) {
            include JPATH_SITE.
            '/administrator/components/com_virtuemart/helpers/config.php';
        }
        VmConfig::loadConfig();
        $this->lang=VmConfig::get('vmlang');
        parent::__construct($config);
    }
    /**
     * UpdateCommision function
     *
     * @param [type] $ids   var
     * @param string $value var
     * @param string $type  var
     * 
     * @return void
     */
    public function updateCommision($ids,$value='',$type='')
    {
        $db=JFactory::getDBO();
        $query=$db->getQuery(true);
        $fields = array(
        $db->quoteName('commision') . ' ='.$db->quote($value),
           $db->quoteName('commision_type') . ' ="'.$type.'"');
        $query->update($db->quoteName('#__marketplace_commision'))
            ->set($fields)
            ->where($db->quoteName('commision_id')." IN(".$ids.")");
        $db->setQuery($query);
        
        try{
            return $db->execute();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
    }
    /**
     * GetPaymentElement function
     *
     * @param [type] $pay_option_finals var
     * 
     * @return void
     */
    function getPaymentElement($pay_option_finals)
    {
        $db=JFactory::getDBO();
        $q1=$db->getQuery(true);
        $q1->select($db->quoteName('virtuemart_paymentmethod_id'))
            ->from($db->quoteName('#__virtuemart_paymentmethods_'.$this->lang.''))
            ->where($db->quoteName('payment_name').'="'.$pay_option_finals.'"');
        $db->setQuery($q1);
        try {
            $pay_id=$db->loadResult();
        } catch(Exception $e) {
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        if (isset($pay_id)) {
            $q1=$db->getQuery(true);
            $q1->select($db->quoteName('payment_element'))
                ->from($db->quoteName('#__virtuemart_paymentmethods'))
                ->where($db->quoteName('virtuemart_paymentmethod_id').'='.$pay_id);
            $db->setQuery($q1);
            try{
                $pay_content=$db->loadResult();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            return $pay_content;
        }
    }
    /**
     * Successcommision function
     *
     * @param integer $seller_id        var
     * @param float   $amount_pay       var
     * @param string  $pay_mode         var
     * @param integer $totalAmountToPay var
     * @param float   $totalCommission  var
     * 
     * @return void
     */
    function successcommision(
        $seller_id,$amount_pay,$pay_mode,
        $totalAmountToPay=0,$totalCommission=0
    ) {
        $db=JFactory::getDBO();
        $query=$db->getQuery(true);
        $query->select('*')
            ->from($db->quoteName('#__marketplace_commision'))
            ->where($db->quoteName('seller_id')."=".$seller_id);
        $db->setQuery($query);
        try{
            $commision_fetch = $db->loadObjectList();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        if ($commision_fetch[0]->amount_remain!=$totalAmountToPay) {
            return false;
        }
        if ($amount_pay>0 && $commision_fetch[0]->amount_remain>0 ) {
            if ($commision_fetch[0]->amount_remain<=$amount_pay) {
                $amount_paid=$commision_fetch[0]->amount_remain;
                $amount_recieved = $commision_fetch[0]->amount_recieved+$amount_paid;
                $amount_remain
                    = $commision_fetch[0]->total_sales
                        -($amount_recieved+$totalCommission+$amount_paid);
                if ($amount_remain<0) {
                    $amount_remain=0;
                }
            } else {
                $amount_remain
                    = $commision_fetch[0]->total_sales
                        -($commision_fetch[0]->amount_recieved
                        +$totalCommission+$amount_pay);
                $amount_paid = $amount_pay;
                $amount_recieved = $commision_fetch[0]->amount_recieved+$amount_paid;
            }
            $commision_update=$db->getQuery(true);
            $fields=array($db->quoteName('amount_remain')."='".$amount_remain."'",
                $db->quoteName('amount_recieved')."='".$amount_recieved."'",
                $db->quoteName('amount_paid')."='".$amount_paid."'");
            $commision_update->update($db->quoteName('#__marketplace_commision'))
                ->set($fields)
                ->where($db->quoteName('seller_id')."='".$seller_id."'");
            $db->setQuery($commision_update);
            try{
                $db->execute();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
            $query=$db->getQuery(true);
            $query->select($db->quoteName('vendor_currency'))
                ->from($db->quoteName('#__virtuemart_vendors'))
                ->where($db->quoteName('virtuemart_vendor_id')."="."1");
            $db->setQuery($query);
            try{
                $curr_id = $db->loadObject();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
                return false;
            }
            $vendor_currency_id = $curr_id->vendor_currency;
            $pmode=$pay_mode;
            $tran=$db->getQuery(true);
            $config = JFactory::getConfig(); 
            $site_offset = $config->get('offset'); 
            $jdate=JFactory::getDate('now', $site_offset);
            $column=array(
                'seller_id','amount','remain_amount',
                'date','currency','payment_mode'
            );
            $values=array(
                $seller_id,$amount_paid,$amount_remain,
                $jdate->format('Y-m-d H:i:s', true),$vendor_currency_id,$pmode
            );
            $tran->insert($db->quoteName('#__marketplace_payments'))
                ->columns($column)
                ->values("'".implode("','", $values)."'");
            $db->setQuery($tran);
            try{
                return $db->execute();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(), 'error'
                );
                return false;
            }
        }
    }
    /**
     * GetListQuery function
     *
     * @return void
     */
    protected function getListQuery()
    {
        $db  = $this->getDbo();
        $query = $db->getQuery(true);
        $query->select(
            $this->getState('list.select', 'a.*')
        );
        $query->from($db->quoteName('#__marketplace_commision').' AS a');
                $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[] = 'us.username LIKE ' . $search;
            $searches[] = 'us.email LIKE ' . $search;
            $searches[] = 'a.commision_id LIKE ' . $search;
            $query->where('(' . implode(' OR ', $searches) . ')');
        }
        if ($this->getState('list.commision_type')!="") {
            $query->where(
                $db->quoteName('commision_type').
                "='".$this->getState('list.commision_type')."'"
            );
        }
        $query->select('g.group_id AS groupid');
        $query->join(
            'LEFT',
            '#__user_usergroup_map AS g ON g.user_id = a.seller_id'
        );
        $query->select('us.username as username,us.email as email, us.registerDate as registerDate');
        $query->join('LEFT', '#__users AS us ON us.id = a.seller_id ')
            ->select(
                'c.first_name as first_name, c.last_name as last_name,'.
                'c.is_seller AS partner, c.payment_mode AS payment_m'.
                'ode, c.payment_desc AS payment_desc'
            )
            ->join(
                'LEFT',
                '#__marketplace_sellerprofile AS c ON c.seller_id = a.seller_id'
            );
        $query->group(
            $db->quoteName('c.seller_id')
        );
        $productId = $this->getState('filter.virtuemart_product_id');
        if (is_numeric($productId)) {
            $query->where('a.virtuemart_product_id = '.(int) $productId);
        }
        $sellerId = $this->getState('filter.seller_id');
        if (is_numeric($sellerId)) {
            $query->where('a.created_by = '.(int) $sellerId);
        }
        $query->order(
            $db->qn($db->escape($this->getState('list.ordering', 'a.commision_id')))
            . ' ' . $db->escape($this->getState('list.direction', 'ASC'))
        );
        
        return $query;
    }
    /**
     * GetCurrencyDetails function
     *
     * @param [type] $id var
     * 
     * @return void
     */
    function getCurrencyDetails($id)
    {
        $query=$this->_db->getQuery(true);
        $query->select("a.*")
            ->select($this->_db->quoteName('b.currency_symbol'))
            ->select($this->_db->quoteName('b.virtuemart_currency_id'))
            ->from($this->_db->quoteName('#__marketplace_commision', 'a'))
            ->join(
                'LEFT',
                $this->_db->quoteName('#__virtuemart_currencies', 'b').
                ' ON('.$this->_db->quoteName('a.currency').
                '='.$this->_db->quoteName('b.virtuemart_currency_id').')'
            )
            ->where($this->_db->quoteName('a.seller_id')."=".$id."");
        $this->_db->setQuery($query);
        try{
            return $this->_db->loadObject();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
    }
    /**
     * GetTotalOrder function
     *
     * @param [type] $user var
     * 
     * @return void
     */
    function getTotalOrder($user)
    {
        $db=$this->_db;
        $userdetails=JFactory::getUser();
        $query=$db->getQuery(true);
        $query->select(array('a.*'))
            ->from($db->quoteName('#__marketplace_orderlist')." AS a")
            ->where('virtuemart_seller_id='.$user);
        try{
            $db->setQuery($query);
            return $db->loadObjectList();
        } catch(Exception $e) {
               JFactory::getApplication()->enqueueMessage(
                   $e->getMessage(), 'error'
               );
        }
    }
    /**
     * GetCurrencySymbol function
     *
     * @return void
     */
    function getCurrencySymbol()
    {
        $db=JFactory::getDBO();
        $query=$db->getQuery(true);
        $query->select($db->quoteName('vendor_currency'))
            ->from($db->quoteName('#__virtuemart_vendors'))
            ->where($db->quoteName('virtuemart_vendor_id')."=1");
        $db->setQuery($query);
        try{
            $vendor_curr_id = $db->loadResult();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        if ($vendor_curr_id=="") {
            JFactory::getApplication()->enqueueMessage(
                JText::_('SET_VM_VENDOR_CURRENCY'), 'error'
            );
            return false;
        }
        $query=$db->getQuery(true);
        $query->select('currency_code_3,currency_symbol')
            ->from($db->quoteName('#__virtuemart_currencies'))
            ->where(
                $db->quoteName('virtuemart_currency_id')."=".$vendor_curr_id
            );
        $db->setQuery($query);
        try{
            $vendor_currencies_output = $db->loadAssoc();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        $currency_symbol = $vendor_currencies_output['currency_symbol']; 
        $vendor_currency_code_3 = $vendor_currencies_output['currency_code_3']; 
        return $vendor_currencies_output; 
    }
    /**
     * Delete function
     *
     * @param array $cid var
     * 
     * @return void
     */
    function delete($cid = array())
    {
        if (count($cid)) {
            $cids = implode(',', $cid);
            $query = $db->getQuery(true);

            // delete all custom keys for user 1001.
            $conditions = array(
                $db->quoteName('u.commision_id') . ' IN ('. $cids .')'
            );

            $query->delete($db->quoteName('#__marketplace_commision', 'u'));
            $query->where($conditions);

            $this->_db->setQuery($query);
            try{
                if (!$this->_db->query()) {
                    $this->setError($this->_db->getErrorMsg());
                    return false;
                }
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
                return false;
            }
        }
        $total  = count($cid);
        $msg  = $total.' '.JText::_('USER_COMMISION_DELETE');
        return $msg;
    }
    /**
     * SaveItem function
     *
     * @param [type] $data var
     * 
     * @return void
     */
    function saveItem($data)
    {
        if (isset($data['commision_rate_fix'])) {
            $comm_amt=0;
            if ($data['commision_rate_fix']=='r') {
                $comm_amt=$data['commision_rate'];
            } else {
                $comm_amt=$data['commision_fix'];
            }
            $object = new stdClass();
            // Must be a valid primary key value.
            $object->commision_id = $data['commision_id'];
            $object->commision = $comm_amt;
            $object->commision_type = $data['commision_rate_fix'];
            try{
                $result = $this->_db->updateObject(
                    '#__marketplace_commision', $object, 'commision_id'
                );
            }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.commision_id', 'asc');
    }
    /**
     * GetForm function
     *
     * @param array   $data     var
     * @param boolean $loadData var
     * 
     * @return void
     */
    public function getForm($data = array(), $loadData = true)
    {
        $form = $this->loadForm(
            'com_marketplace.commisions',
            'commisions',
            array('control' => 'jform', 'load_data' => $loadData)
        );
        if (empty($form)) {
            return false;
        } 
        return $form;
    }
    /**
     * [getSellerCommisionInfo fetch commission data of seller for remita pay]
     * 
     * @param [type] $sellerid [int]
     * 
     * @return object
     */
    function getSellerCommisionInfo($sellerid)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("*");
        $query->where($db->quoteName('seller_id')."=".$db->quote($sellerid));
        $query->from($db->quoteName('#__marketplace_commision'));
        $db->setQuery($query);  
        try{
            $commision_data=$db->loadObject();
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                'unable to fetch seller info',
                'warning'
            );
        }
        return $commision_data;
    }
    /**
     * GetRemitaDetails function
     *
     * @param integer $sellerid var
     * 
     * @return void
     */
    function getRemitaDetails($sellerid)
    {
        $db=JFactory::getDBO();
        $q=$db->getQuery(true);
        $q ->select('*')
            ->from($db->quoteName('#__marketplace_remitapayment_connectedseller'))
            ->where($db->quoteName('sellerid')."=".$db->quote($sellerid));
        $db->setQuery($q);
        try{
            $seller_remita_info = $db->loadObject();
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(),
                'error'
            );
            return false;
        }
        return $seller_remita_info;
    }
    /**
     * GetRemitaParams function
     *
     * @return void
     */
    function getRemitaParams()
    {
        $remita_params=array();
        $db=JFactory::getDBO();
        $q=$db->getQuery(true);
        $q ->select($db->quoteName('payment_params'))
            ->from($db->quoteName('#__virtuemart_paymentmethods'))
            ->where($db->quoteName('payment_element')."=".$db->quote('remitasplit'));
        $db->setQuery($q);
        try{
            $remita_params_string = $db->loadResult();
            $remita_params_arr=explode('|', $remita_params_string);
            foreach ($remita_params_arr as $key => $value) {
                $str_split=explode('=', $value);
                if (isset($str_split[0]) && isset($str_split[1])) {
                    $str_split[1]=str_replace('"', '', $str_split[1]);
                    $remita_params[$str_split[0]]=$str_split[1];
                }
            }
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
        return $remita_params;
    }
    /**
     * UpdateSellerCommisionAmount function
     *
     * @param [type] $amountPay var
     * @param [type] $sellerid  var
     * 
     * @return void
     */
    function updateSellerCommisionAmount($amountPay,$sellerid)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("*");
        $query->where($db->quoteName('seller_id')."=".$db->quote($sellerid));
        $query->from($db->quoteName('#__marketplace_commision'));
        $db->setQuery($query);  
        try{
            $commision_fetch=$db->loadObject();
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                'unable to fetch seller info', 'warning'
            );
        } 
        $amount_recieved = $commision_fetch->amount_recieved+$amountPay;
        $amount_remain = $commision_fetch->amount_remain - $amountPay;
        $query = $db->getQuery(true);
        $query->update($db->quoteName('#__marketplace_commision'))
            ->set($db->quoteName('amount_remain')."=".$db->quote($amount_remain))
            ->set($db->quoteName('amount_recieved')."=".$db->quote($amount_recieved))
            ->set($db->quoteName('amount_paid')."=".$db->quote($amountPay))
            ->where($db->quoteName('seller_id')."=".$db->quote($sellerid));
        $db->setQuery($query);
        try{
            $db->execute();
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'warning'
            );
        }
        $tm=time();
        $query = $db->getQuery(true);
        $query->select($db->quoteName('vendor_currency'))
            ->from($db->quoteName('#__virtuemart_vendors'))
            ->where($db->quoteName('virtuemart_vendor_id')."=".$db->quote(1));

        $db->setQuery($query);
        $curr_id = $db->loadObject();
        $vendor_currency_id = $curr_id->vendor_currency;
        $query = $db->getQuery(true);

        $columns = array(
            'seller_id', 'amount', 'remain_amount', 'currency','payment_mode'
        );
        
        $values = array(
            $db->quote($sellerid), $db->quote($amountPay),
            $db->quote($amount_remain),
            $db->quote($vendor_currency_id),$db->quote('remitasplit')
        );
        
        $query
            ->insert($db->quoteName('#__marketplace_payments'))
            ->columns($db->quoteName($columns))
            ->values(implode(',', $values));
        $db->setQuery($query);
        try{
            $db->execute(); 
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return false;
        }
    }
}
