<?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');
if (!class_exists('Vmconfig')) {
    include JPATH_ADMINISTRATOR.'/components/com_virtuemart/helpers/config.php';
}
Vmconfig::loadConfig();
if (!class_exists('CurrencyDisplay')) {
    include JPATH_ADMINISTRATOR.
    '/components/com_virtuemart/helpers/currencydisplay.php';
}
/**
 * MarketplaceHelper Class - Helper methods for genral use can be found here
 * 
 * @category  Module
 * @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
 * @link      Technical Support:  webkul.uvdesk.com
 */
class MarketplaceHelper
{
    /**
     * AddSubmenu function
     *
     * @param [str] $vName var
     * 
     * @return void
     */
    public static function addSubmenu($vName)
    {
        $doc=JFactory::getDocument();
        $style="
            #j-main-container>table>thead>tr>th>a {
                text-decoration: none;
                color: #FFFFFF;
                vertical-align: top;
            }

            .js-stools,
            .clearfix {
                margin-bottom: 10px;
            }

            .adminproducts-submenuicon {
                background-position: -9px -149px;
            }

            .commisions-submenuicon {
                background-position: -9px -93px;
            }

            .dashboard-submenuicon {
                background-position: -9px -9px;
            }

            .feedback-submenuicon {
                background-position: -9px -122px;
            }

            .orders-submenuicon {
                background-position: -9px -232px;
            }

            .products-submenuicon {
                background-position: -9px -36px;
            }

            .marketplace-submenuicon {
                background-position: -9px -64px;
            }

            .mpusers-submenuicon {
                background-position: -9px -262px;
            }

            .add-ons-submenuicon {
                background-position: -9px -292px;
            }

            .suggested-submenuicon {
                background-position: -9px -319px;
            }
            .messages-submenuicon {
                background-position: -9px -205px !important;
            }

            #submenu .active .adminproducts-submenuicon {
                background-position: -39px -149px !important;
            }

            #submenu .active .commisions-submenuicon {
                background-position: -39px -93px !important;
            }

            #submenu .active .dashboard-submenuicon {
                background-position: -39px -9px !important;
            }

            #submenu .active .feedback-submenuicon {
                background-position: -39px -122px !important;
            }

            #submenu .active .marketplace-submenuicon {
                background-position: -39px -64px !important;
            }

            #submenu .active .orders-submenuicon {
                background-position: -39px -233px !important;
            }

            #submenu .active .mpusers-submenuicon {
                background-position: -39px -262px !important;
            }

            #submenu .active .add-ons-submenuicon {
                background-position: -39px -292px !important;
            }

            #submenu .active .products-submenuicon {
                background-position: -39px -36px !important;
            }

            #submenu .active .suggested-submenuicon {
                background-position: -39px -319px !important;
            }
            #submenu .active .messages-submenuicon {
                background-position: -39px -205px !important;
            }
            [class$='submenuicon'] {
                background-image: url('components/com_marketplace/assets/images/sprite-icon.png');
                background-repeat: no-repeat;
                display: inline-block;
                height: 22px;
                vertical-align: middle;
                width: 22px;
                margin-right: 5px;
            }
        ";
        $doc->addStyleDeclaration($style);
            JHtmlSidebar::addEntry(
                '<span class="dashboard-submenuicon"></span>'.
                JText::_('WK_DASHBOARD'),
                'index.php?option=com_marketplace&view=dashboard',
                $vName == 'dashboard'
            );
            JHtmlSidebar::addEntry(
                '<span class="marketplace-submenuicon"></span>'.
                JText::_('SELLERS'),
                'index.php?option=com_marketplace&view=marketplace',
                $vName == 'marketplace'
            );
            JHtmlSidebar::addEntry(
                '<span class="mpusers-submenuicon"></span>'.
                JText::_('WK_USERS'),
                'index.php?option=com_marketplace&view=mpusers',
                $vName == 'mpusers'
            );
            JHtmlSidebar::addEntry(
                '<span class="commisions-submenuicon"></span>'.
                JText::_('COMMISIONS'),
                'index.php?option=com_marketplace&view=commisions',
                $vName == 'commisions'
            );
            JHtmlSidebar::addEntry(
                '<span class="orders-submenuicon"></span>'.
                JText::_('WK_ORDERS'),
                'index.php?option=com_marketplace&view=mporders',
                $vName == 'mporders'
            );
            JHtmlSidebar::addEntry(
                '<span class="products-submenuicon"></span>'.
                JText::_('PRODUCTS'),
                'index.php?option=com_marketplace&view=products',
                $vName == 'products'
            );
            JHtmlSidebar::addEntry(
                '<span class="adminproducts-submenuicon"></span>'.
                JText::_('ADMINPRODUCTS'),
                'index.php?option=com_marketplace&view=adminproducts',
                $vName == 'adminproducts'
            );
            JHtmlSidebar::addEntry(
                '<span class="feedback-submenuicon"></span>'.
                JText::_('FEEDBACK'),
                'index.php?option=com_marketplace&view=feedback',
                $vName == 'feedback'
            );
            JHtmlSidebar::addEntry(
                '<span class="suggested-submenuicon"></span>'.
                JText::_('SUGGESTED_CATEGORY'),
                'index.php?option=com_marketplace&view=suggestedcategory',
                $vName == 'suggestedcategory'
            );
            JHtmlSidebar::addEntry(
                '<span class="messages-submenuicon"></span>'.
                JText::_('MESSAGES'),
                'index.php?option=com_marketplace&view=messages',
                $vName == 'messages'
            );
            JHtmlSidebar::addEntry(
                '<span class="add-ons-submenuicon"></span>'.JText::_('ADD_ONS'),
                'index.php?option=com_marketplace&view=mpaddons',
                $vName == 'mpaddons'
            );
    }
    /**
     * Is Curl Installed check function
     *
     * @return boolean
     */
    public static function isCurlInstalled()
    {
        if (in_array('curl', get_loaded_extensions())) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * Get Seller Options function
     *
     * @return Object
     */
    public static function getsellerOptions()
    {
        $options = array();
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('u.id AS value, u.username AS text');
        $query->from('`#__users` as u');
        $query->join(
            'INNER',
            '`#__marketplace_sellerprofile` as s ON s.seller_id=u.id'
        );
        $query->order('username');
        $db->setQuery($query);
        try {
            $options = $db->loadObjectList();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage());
        }
        return $options;
    }
    /**
     * CheckSeller
     *
     * @param [numeric] $seller_id var
     * 
     * @return bool
     */
    public static function checkSeller($seller_id)
    {
        if (!is_numeric($seller_id)) {
            return false;
        }
        $db=JFactory::getDBO();
        $query=$db->getQuery(true);
        $query->select($db->quoteName('is_seller'))
            ->from($db->quoteName('#__marketplace_sellerprofile'))
            ->where($db->quoteName('seller_id')."=".$db->quote($seller_id));
        try{
            $db->setQuery($query);
            return $db->loadResult();
        }
        catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(),
                'error'
            );
            return false;
        }
    }
    /**
     * Get Seller
     *
     * @param [numeric] $seller_id var
     * @param array     $fields    var
     * 
     * @internal pass field array with u.fieldname for fields of #__users table
     * @internal and s.fieldname for #__marketplace_sellerprofile
     * 
     * @return Object
     */
    public static function getSeller($seller_id, $fields=array())
    {
        if (!is_numeric($seller_id)) {
            return false;
        }
        if (empty($fields)) {
            $getTxt="*";
        } else {
            $getTxt=implode(',', $fields);
        }
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select($getTxt)
            ->from('`#__users` as u')
            ->join(
                'INNER',
                '`#__marketplace_sellerprofile` as s ON s.seller_id=u.id'
            )->where($db->quoteName('s.seller_id')." = ".$db->quote($seller_id));
        $db->setQuery($query);
        try {
            return $db->loadObject();
        } catch (Exception $e) {
            JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
            return null;
        }
    }

    /**
     * Get Marketplace Model Admin function
     *
     * @param string $name   Marketplace
     * @param string $prefix MarketplaceModel
     * @param array  $config var
     * 
     * @return Object
     */
    public static function getMarketModelA(
        $name = 'Marketplace',
        $prefix = 'MarketplaceModel',
        $config = array('ignore_request' => true)
    ) {
        JModelLegacy::addIncludePath(
            JPATH_ADMINISTRATOR .
            '/components/com_marketplace/models'
        );
        include_once JPATH_ADMINISTRATOR .
        '/components/com_marketplace/models/'.strtolower($name).'.php';
        $model = JModelLegacy::getInstance($name, $prefix);
        if ($model==false) {
            $class=$prefix.$name;
            new $class();
            $model = JModelLegacy::getInstance($name, $prefix);
        }
        return $model;
    }
    /**
     * Get Marketplace Model Site function
     *
     * @param string $name   Marketplace
     * @param string $prefix MarketplaceModel
     * @param array  $config var
     * 
     * @return Object
     */
    public static function getMarketModelS(
        $name = 'Marketplace',
        $prefix = 'MarketplaceModel',
        $config = array('ignore_request' => true)
    ) {
        JModelLegacy::addIncludePath(
            JPATH_SITE .
            '/components/com_marketplace/models'
        );
        include_once JPATH_SITE .
        '/components/com_marketplace/models/'.strtolower($name).'.php';
        $model = JModelLegacy::getInstance($name, $prefix);
        if ($model==false) {
            $class=$prefix.$name;
            new $class();
            $model = JModelLegacy::getInstance($name, $prefix);
        }
        return $model;
    }
    /**
     * Get Actions function
     *
     * @param integer $sellerId var
     * 
     * @return void
     */
    public static function getActions($sellerId = 0)
    {
        $user = JFactory::getUser();
        $result = new JObject;
        if (empty($sellerId)) {
            $assetName = 'com_marketplace';
            $level = 'component';
        } else {
            $assetName = 'com_marketplace.category.'.(int) $sellerId;
            $level = 'created_by';
        }
        $actions = JAccess::getActions('com_marketplace', $level);
        foreach ($actions as $action) {
            $result->set(
                $action->name,
                $user->authorise(
                    $action->name,
                    $assetName
                )
            );
        }
        return $result;
    }
    /**
     * Order mail Send function
     *
     * @param [int] $order var
     * 
     * @return void
     */
    public static function ordermailSend($order)
    {
        /* Loading Language */
        $lang = JFactory::getLanguage();
        $extension = 'com_marketplace';
        $base_dir = JPATH_SITE;
        $lang->load($extension, $base_dir);

        /* Getting email template */
        $params = JComponentHelper::getParams('com_marketplace');
        $template = trim($params->get('mp_temp_mail_order_done'));
        $subject_temp = trim($params->get('mp_sub_mail_order_done'));
        
        /* Collecting Required Data For Mail For sellers*/
        $db=JFactory::getDBO();
        $seller_ids=array();
        $currencydisplay=CurrencyDisplay::getInstance(
            $order['details']['BT']->order_currency
        );
        $symbol=$currencydisplay->getSymbol();
        $cusMod=VmModel::getModel("customfields");
        $item_index = 0;
        foreach ($order['items'] as $item) {
            $query = $db->getQuery(true);
            $productid = $item->virtuemart_product_id;
            $query->select($db->quoteName('vmp.created_by'));
            $query->from($db->quoteName('#__virtuemart_products', 'vmp'));
            $query->join(
                'LEFT',
                $db->quoteName(
                    '#__marketplace_sellerprofile',
                    'mps'
                ).' ON '.$db->quoteName('vmp.created_by').
                "=".$db->quoteName('mps.seller_id')
            );
            $query->where(
                $db->quoteName('vmp.virtuemart_product_id').
                "=".$db->quote($productid)
            );
            $query->where(
                $db->quoteName('mps.seller_id').
                "=".$db->quote($item->created_by)
            );
            $db->setQuery($query);
            try {
                $seller_id=$db->loadResult();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
                return false;
            }
            if (isset($seller_id)) {
                $seller_ids[$seller_id][$item_index]['custom']="";
                if (count($item->customfields)) {
                    $seller_ids
                        [$seller_id]
                        [$item_index]
                        ['custom']=$cusMod->CustomsFieldOrderDisplay(
                            $item,
                            'FE'
                        );
                }
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['sku']=$item->product_sku;
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['quantity']=$item->product_quantity;
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['productname']=$item->order_item_name;
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['price']=$item->product_priceWithoutTax;
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['tax']=$item->product_tax;
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['discount']=$item->product_subtotal_discount;
                $seller_ids
                    [$seller_id]
                    [$item_index]
                    ['total']=$item->product_subtotal_with_tax;
            }
            $item_index++;
        }
        $userFieldsModel = VmModel::getModel('userfields');
        /* Sending mail to seller(s) */
        foreach ($seller_ids as $key=>$item) {
            $seller_data = self::getSeller(
                $key, array('u.username', 'u.name', 's.screenname')
            );
            $body = $template;
            $mailer=JFactory::getMailer();
            $totalprice=0.0;
            $config=JFactory::getConfig();
            $email=JFactory::getUser($key)->email;
            $sku = JText::_('S_KU');
            $qty = JText::_('QUALITY');
            $prod_name = JText::_('PROD_NAME');
            $price = JText::_('PR_ICE');
            $tax = JText::_('T_AX');
            $discount = JText::_('DI_SCOUNT');
            $total = JText::_('T_OTL');
            $wk_products='';
            foreach ($item as $key1 => $value) {
                $totalprice+=$value['total'];
                $wk_products.="<tr align='left'>
                    <td align='left'>".$value['sku']."</td>
                    <td align='left'>".$value['quantity']."</td>
                    <td align='left'>".$value['productname'].$value['custom']."</td>
                    <td align='right'>"
                    .$currencydisplay->getFormattedCurrency(
                        $currencydisplay->roundForDisplay(
                            $value['price']
                        )
                    )."</td><td align='right'>".
                    $currencydisplay->getFormattedCurrency(
                        $currencydisplay->roundForDisplay(
                            $value['tax']
                        )
                    )."</td><td align='right'>"
                    .$currencydisplay->getFormattedCurrency(
                        $currencydisplay->roundForDisplay(
                            $value['discount']
                        )
                    )."</td><td align='right'>".
                    $currencydisplay->getFormattedCurrency(
                        $currencydisplay->roundForDisplay(
                            $value['total']
                        )
                    )."</td>
                </tr>";
            }
            $product_details = "<table width='100%' cellspacing='0' cellpadding='0' border='0'>
                <tbody>
                    <tr align='left'>
                        <th align='left'>".$sku."</th>
                        <th align='left'>".$qty."</th>
                        <th align='left'>".$prod_name."</th>
                        <th align='right'>".$price."</th>
                        <th align='right'>".$tax."</th>
                        <th align='right'>".$discount."</th>
                        <th align='right'>".$total."</th>
                    </tr>".$wk_products
                ."</tbody>
            </table>";
            if (!isset($seller_data->screenname) || $seller_data->screenname == "") {
                $seller_data->screenname = $seller_data->name;
            }
            $subject = $subject_temp;
            /* Getting User Shiment and Billing Address */
            $_userFields = $userFieldsModel->getUserFields(
                'account',
                array('captcha' => true, 'delimiters' => true),
                array('delimiter_userinfo','user_is_vendor' ,'username',
                'password', 'password2', 'agreed', 'address_type')
            );
            $orderbt = $order['details']['BT'];
            $orderst = (array_key_exists('ST', $order['details'])) ? $order['details']['ST'] : $orderbt;
            $userfields = $userFieldsModel->getUserFieldsFilled(
                $_userFields, $orderbt
            );
            $_userFields = $userFieldsModel->getUserFields(
                'shipment',
                array(),
                array('delimiter_userinfo', 'username', 'email', 'password',
                'password2', 'agreed', 'address_type')
            );
            $shipmentfields = $userFieldsModel->getUserFieldsFilled(
                $_userFields, $orderst
            );
            $field_value="";
            foreach ($userfields['fields'] as $field) {
                if (!empty($field['value'])) {
                    $field_value.= '<tr><th style="text-align: left;" colspan="2">'
                        . $field['title'] . '</th>' . '<td  class="key">';
                    if (strtolower($field['title']) === "title") {
                        if ($field['value']==1 || $field['value']==2) {
                            $field_value.=$field['value']==1?"male":"female";
                        }
                        $field_value.=" ";
                    } else {
                        $field_value.=$field['value'];
                    }
                    $field_value .='</td></tr>';
                }
            }
            $billing_add = "<table>".$field_value."</table>";
            $field_value="";
            foreach ($shipmentfields['fields'] as $field) {
                if (!empty($field['value'])) {
                    $field_value.='<tr ><th style="text-align: left;" colspan="2">' . $field['title'] . '</th>'
                    . '<td  class="key">' . $field['value'] . '</td></tr>';
                }
            }
            $site_curr_total = $currencydisplay->getFormattedCurrency(
                $currencydisplay->roundForDisplay(
                    $totalprice
                )
            );
            $shipping_add = "<table>".$field_value."</table>";
            /* Replacing Value in Templates*/
            $body = str_replace(
                '{[RECEPIENT_SELLER_SCREEN]}', ucwords($seller_data->screenname),
                $body
            );
            $subject= str_replace(
                '{[RECEPIENT_SELLER_SCREEN]}', ucwords($seller_data->screenname),
                $subject
            );
            $body = str_replace(
                '{[RECEPIENT_NAME]}', ucwords($seller_data->name), $body
            );
            $subject= str_replace(
                '{[RECEPIENT_NAME]}', ucwords($seller_data->name), $subject
            );
            $body = str_replace(
                '{[ORDER_PRODUCT_DETAILS]}', $product_details, $body
            );
            $subject= str_replace(
                '{[ORDER_NUMBER]}', $order['details']['BT']->order_number, $subject
            );
            $body = str_replace(
                '{[ORDER_NUMBER]}', $order['details']['BT']->order_number, $body
            );
            $subject= str_replace(
                '{[ORDER_NAME]}', ucwords($order['details']['BT']->order_name),
                $subject
            );
            $body = str_replace(
                '{[ORDER_NAME]}', ucwords($order['details']['BT']->order_name), $body
            );
            $body = str_replace(
                '{[BILL_TO_ORDER]}', $billing_add, $body
            );
            $body = str_replace(
                '{[SHIP_TO_ORDER]}', $shipping_add, $body
            );
            $body = str_replace(
                '{[ORDER_TOTAL]}', $site_curr_total, $body
            );
            
            /* Setting Values to Mailer */
            $mailer->setSender($config->get('mailfrom'));
            $mailer->addRecipient($email);
            $mailer->setSubject($subject);
            $mailer->isHTML(true);
            $mailer->Encoding = 'base64';
            $mailer->setBody($body);
            /* Send mail */
            $send = $mailer->Send();
        }
    }
    /**
     * Helper Set order status of seller
     *
     * @param [int]  $seller_id var
     * @param [str]  $order_id  var
     * @param [char] $status    var
     * 
     * @return bool
     */
    public static function setOrderStatus($seller_id, $order_id, $status)
    {
        $app = JFactory::getApplication();
        if (!self::checkSeller($seller_id) || !isset($order_id) || !isset($status)) {
            return false;
        }
        $orderModel = $this->getMarketModelS('Orderhistory');
        if (!$orderModel) {
            return false;
        }
        $res = $orderModel->setOrderStatus($seller_id, $order_id, $status);
        return $res;
    }
    /**
     * Helper to get Menu Item Id and Title for Mp Views
     *
     * @param [str] $view var
     * 
     * @return Object{ID, TITLE}
     */
    public static function getMpMenuItem($view)
    {
        $view = strtolower($view);
        $db = JFactory::getDbo();
        $genral_query = $db->getQuery(true);
        $link = 'index.php?option=com_marketplace&view='.$view;
        $genral_query->select($db->quoteName(array("id","title")))
            ->from($db->quoteName('#__menu'))
            ->where('link='.$db->quote($link))
            ->where('menutype='.$db->quote('marketplace'));
        $db->setQuery($genral_query);
        try {
            $Itemids=$db->loadObject();
        } catch (Exception $e) {
            $Itemids = null;
        }
        return $Itemids;
    }
    /**
     * GetSellerProductList function
     *
     * @param integer $seller_id Seller Id
     * 
     * @return array
     */
    public static function getSellerProductList($seller_id = 0)
    {
        $db=JFactory::getDBO();
        $seller_id = (int)$seller_id;
        $query = $db->getQuery(true);
        $query->select($db->quoteName('virtuemart_product_id'))
            ->from($db->quoteName('#__virtuemart_products'))
            ->where($db->quoteName('created_by')."=".$db->quote($seller_id));
        $db->setQuery($query);
        try {
            $seller_products=$db->loadAssocList();
        } catch(Exception $e) {
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return array();
        }
        $seller_products=array_column($seller_products, 'virtuemart_product_id');
        return $seller_products;
    }
    /**
     * GetUserIdByEmail function
     *
     * @param string $email User email
     * 
     * @return void
     */
    public static function getUserIdByEmail($email)
    {
        $db=JFactory::getDBO();
        $query = $db->getQuery(true);
        $query->select($db->quoteName('id'))
            ->from($db->quoteName('#__users'))
            ->where($db->quoteName('email')."=".$db->quote($email));
        $db->setQuery($query);
        try {
            $user=$db->loadObject();
            if ($user == null) {
                $user_id=0;
            } else {
                $user_id=$user->id;
            }
        } catch(Exception $e) {
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(), 'error'
            );
            return 0;
        }
        return $user_id;
    }
    /**
     * GetCountrySelectField function
     *
     * @param string $country_val       country code 2
     * @param string $country_html_id   html attr id
     * @param string $country_html_name html attr name
     * @param string $style_string      css inline style
     * 
     * @return void
     */
    public static function getCountrySelectField(
        $country_val="",$country_html_id="",$country_html_name="",
        $style_string="",$class=""
    ) {
        $document = JFactory::getDocument();

        $mod_mp_resgister = self::getMarketModelS('Mpregistration');
        $country_html_id = $country_html_id!=""?$country_html_id:"wkcountries";
        $country_html_name = $country_html_name!=""?$country_html_name:"countries";

        $document->addStyleSheet(
            JURI::root().'components/com_marketplace/css/msdropdown/dd.css'
        );
        $document->addStyleSheet(
            JURI::root().'components/com_marketplace/css/msdropdown/flags.css'
        );
        $document->addScript(
            JURI::root().'components/com_marketplace/js/msdropdown/jquery.dd.min.js'
        );
        $document->addScriptDeclaration(
            'jQuery(document).ready(function() {
                jQuery("#'.$country_html_id.'").msDropdown();
            });'
        );
        
        $select_field = '<select class="wkselect'.$class.'" name="'.$country_html_name.
            '" id="'.$country_html_id.'" style="'.$style_string.'">'.
            '<option value="">'.JText::_('SELECT_COUNTRY').'</option>';
        $image_path = JURI::root().
            'components/com_marketplace/images/msdropdown/icons/blank.gif';
        $country_data = $mod_mp_resgister->getCountryList();
        foreach ($country_data as $key => $value) {
            $checked="";
            $country_2_code = strtolower($value->country_2_code);
            if ($country_val === $country_2_code) {
                $checked=" selected='selected'";
            }
            
            $select_field .= '<option value="'.$country_2_code.
                '" data-image="'.$image_path.'" '.'data-id="'.
                $value->virtuemart_country_id.'" '.
                'data-imagecss="flag '.$country_2_code.'" '
                .'data-title="'.$value->country_name.'"'.$checked.'>'.$value->country_name.'</option>';
        }
        $select_field.="</select>";
        return $select_field;
    }
    /**
     * Get Following Sellers function
     *
     * @param string $user_email var
     * 
     * @return void
     */
    public static function getFollowingSellers($user_email = "")
    {
        if ($user_email === "") {
            return array();
        }
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select($db->quoteName("seller_id"))
            ->from($db->quoteName("#__marketplace_seller_follower"))
            ->where(
                $db->quoteName("follower_email"). " = " .$db->quote($user_email)
            );
        $db->setQuery($query);
        try {
            return $db->loadObjectList();
        } catch (Exception $e) {
            return array();
        }
    }
    /**
     * Get Sellers Block Html for list of seller in a table function
     *
     * @param array $seller_ids Array of ids
     * 
     * @return void
     */
    public static function getSellersBlockHtml($seller_ids = array())
    {
        $html = '<table class="table table-bordered table-striped webkul-tab" >'.
                '<thead id="wk_seller_list">'.
                '<tr>'.
                '<th class="center ">'.JText::_('SELLER').'</th>'.
                '<th class="center ">'.JText::_('SELLER_NAME').'</th>'.
                '<th class="center ">'.JText::_('SHOP_NAME').'</th>'.
                '<th class="center ">'.JText::_('CONTACT_NO').'</th>'.
                '<th class="center ">'.JText::_('E_MAIL').'</th>'.
                ' </tr></thead><tbody class="sellers_table">';
        if (!count($seller_ids)) {
            $html.= "<tr ><td colspan='5'><div class='alert alert-info'>".
                "<strong>Info!</strong>".JText::_('NO_RECORD_FOUND')."</div></td></tr>";
        } else {
            $model=self::getMarketModelS('Sellerlist');
            $i=0;
            $params = JComponentHelper::getParams('com_marketplace');
            $lazy_limit=trim($params->get('wk_lazy_load_limit'));
            if ($lazy_limit < 1) {
                $lazy_limit=10;
            }
            foreach ($seller_ids as $key=>$value) {
                $request_fields = array(
                    's.phone','u.email','s.screenname','u.name',
                    's.companyname','s.companylogo'
                );
                $data = self::getSeller($value->seller_id, $request_fields);
                if ($data->phone==null) {
                    $data->phone='N/A';
                }
                if ($data->email==null) {
                    $data->email='N/A';
                }
                if (!strlen($data->screenname)) {
                    $data->screenname=$data->name;
                } else {
                    $data->screenname=$data->screenname;
                }
                if ($data->companyname==null) {
                    $data->companyname='N/A';
                }
                if (strlen(trim($data->companylogo))) {
                    $src=$data->companylogo;
                } else {
                    $src='administrator/components/com_marketplace/assets/images/no-image.png';
                }
                if ($i%2==0) {
                    $class="active";
                } else {
                    $class="warning";
                }
                $sellerprofilemenu = self::getMpMenuItem('sellerprofile');
                $html.='<tr  class="mprow '. $class.'" >'.
                    '<td data-title="'. JText::_('SELLER').'" class="center">'.
                    '<a class="seller_avatar" href="'. JRoute::_(
                        'index.php?option=com_marketplace&view=sellerprofile&Itemid='
                        .$sellerprofilemenu->id.'&seller_id='.$value->seller_id,
                        false
                    ).'">'.'<img class="avatarimg" src="'. $src .'"/>'.
                    '</a></td><td class="center" data-title="'.
                    JText::_('SELLER_NAME').'"><a href="'.JRoute::_(
                        'index.php?option=com_marketplace&view=sellerprofile&Itemid='.
                        $sellerprofilemenu->id.'&seller_id='.$value->seller_id, false
                    ).'">'.$data->screenname.'</a>'.
                    '</td>'.'<td class="center" data-title="'. JText::_('SHOP_NAME').'">'.
                    '<a href="'.JRoute::_(
                        'index.php?option=com_marketplace&view=sellerprofile&Itemid='
                        .$sellerprofilemenu->id.'&seller_id='.$value->seller_id,
                        false
                    ).'">'. $data->companyname.'</a></td><td '.
                    'class="center" data-title="'. JText::_('CONTACT_NO').'">'.
                    $data->phone.'</td><td  data-title="'. JText::_('E_MAIL').
                    '" class="center">'. $data->email.'</td></tr>';
                $i++;
            }
        }
        $html.= '</tbody><tfoot></tfoot></table>';
        return $html;
    }
    /**
     * Get Top Viewed Seller Products function
     *
     * @param integer $seller_id var
     * @param integer $limit     var
     * 
     * @return void
     */
    public static function getTopViewedSellerProducts($seller_id, $limit = 5)
    {
        $db = JFactory::getDbo();
        $user = JFactory::getUser();
        $userid = $user->get('id');
        $params = JComponentHelper::getParams('com_languages');
        $defaultcountry_code = VmConfig::$vmlang;
        $GLOBALS['virtuemart_categories_table_name'] = $defaultcountry_code;
        $query=$db->getQuery(true);
        $query->select($db->quoteName('b.created_by'))
            ->select($db->quoteName('b.virtuemart_product_id'))
            ->select($db->quoteName('b.created_on'))
            ->select($db->quoteName('a.block'))
            ->select($db->quoteName('a.viewed'))
            ->select($db->quoteName('b.published'))
            ->select('e.*')
            ->select($db->quoteName('f.rating'))
            ->select($db->quoteName('g.product_price'))
            ->select($db->quoteName('g.override'))
            ->select($db->quoteName('g.product_override_price'))
            ->select($db->quoteName('g.product_tax_id'))
            ->select($db->quoteName('g.product_discount_id'))
            ->select($db->quoteName('g.product_currency'))
            ->select($db->quoteName('vm.file_url'))
            ->select($db->quoteName('vm.virtuemart_media_id'))
            ->from($db->quoteName('#__virtuemart_products', 'b'))
            ->join(
                'LEFT',
                $db->quoteName(
                    '#__virtuemart_products_'.
                    $GLOBALS['virtuemart_categories_table_name'], 'e'
                )
                ." ON ".$db->quoteName('e.virtuemart_product_id').
                "=".$db->quoteName('b.virtuemart_product_id').""
            )
            ->join(
                'LEFT',
                $db->quoteName(
                    '#__marketplace_product', 'a'
                ).
                " ON ".$db->quoteName('a.virtuemart_product_id').
                "=".$db->quoteName('b.virtuemart_product_id')
            )
            ->join(
                "LEFT",
                $db->quoteName('#__virtuemart_product_prices', 'g').
                " ON ".$db->quoteName('g.virtuemart_product_id').
                "=".$db->quoteName('b.virtuemart_product_id')
            )
            ->join(
                "LEFT",
                $db->quoteName('#__virtuemart_product_medias', 'vpm').
                " ON ".$db->quoteName('vpm.virtuemart_product_id').
                "=".$db->quoteName('b.virtuemart_product_id')
            )
            ->join(
                "LEFT",
                $db->quoteName('#__virtuemart_medias', 'vm')." ON "
                .$db->quoteName('vm.virtuemart_media_id').
                "=".$db->quoteName('vpm.virtuemart_media_id')
            )
            ->join(
                'LEFT',
                $db->quoteName('#__virtuemart_ratings', 'f')." ON ".
                $db->quoteName('b.virtuemart_product_id').
                "=".$db->quoteName('f.virtuemart_product_id')
            )
            ->where($db->quoteName('b.created_by')."=".$seller_id."")
            ->group($db->quoteName('b.virtuemart_product_id'))
            ->order('a.viewed DESC')
            ->setLimit($limit);
        try{
            $db->setQuery($query);
            return $db->loadObjectList();
        } catch(Exception $e){
            return array();
        }
        
        $query = $db->getQuery(true);
        $query->select(
            $db->quoteName(array("virtuemart_product_id","viewed","block"))
        )
            ->from($db->quoteName("#__marketplace_product"))
            ->where(
                $db->quoteName("seller_id"). " = " .$seller_id
            )
            ->order('viewed DESC')
            ->setLimit($limit);
        $db->setQuery($query);
        try {
            return $db->loadObjectList();
        } catch (Exception $e) {
            
        }
    }
    /**
     * Get Mp Products Html function
     *
     * @param array $product_ids var
     * 
     * @return void
     */
    public static function getMpProductsHtml($product_ids=array())
    {
        if (!count($product_ids)) {
            return '<div style="text-align:center;">'.
                JText::_('NO_PRODUCT_ADDED_YET').'</div>';
        } else {
            $html="";
            VmConfig::loadConfig();
            $productModel = VmModel::getModel('Product');
            $currencyInstance = CurrencyDisplay::getInstance();
            $changeCurrency=$currencyInstance->getCurrencyForDisplay();
            $addproductmenu = self::getMpMenuItem('addproduct');
            foreach ($product_ids as $item) {
                if (isset($item->virtuemart_product_id)) {
                    $proMod = $productModel->getProduct($item->virtuemart_product_id, true, true, false);
                    $dot='';
                    $b='';
                    $dis_price_indx = 0;
                    foreach ($proMod->allPrices as $key => $value) {
                        if (isset($value["salesPrice"])) {
                            $dis_price_indx = $key;
                            break;
                        }
                    }
                    if (!$proMod->published) {
                        continue;
                    }
                    
                    $html.=
                        '<div class="recent_pro_md">'.
                        '<div class="pro_img"><a href="'.
                        JRoute::_(
                            "index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=".
                            $item->virtuemart_product_id, false
                        ).'"target="">';
                    if (!strlen($item->file_url)) {
                        $html.='<img class="image_pro" src="'.JURI::root().
                            $vmconfig->get("assets_general_path").
                            "images/vmgeneral/".
                            $vmconfig->get("no_image_set").'" width="100%"/>';
                    } else {
                        $html.='<img class="image_pro" width="100%" src="'.$item->file_url.'"/>';
                    }
                    $html.='</a></div><div class="pro_name">
                        <a style="text-decoration:none;" href="index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.
                        $item->virtuemart_product_id.'" target="">';
                    if (strlen($item->product_name)>30) {
                        $dot='...';
                    }
                    $html.= substr($item->product_name, 0, 27).$dot.'</a><div class="rating">';
                    if ($item->rating!=null) {
                        $rt=round($item->rating);
                    } else {
                        $rt=0;
                    }
                    $xv= 5-$rt;
                    $html.='<span class="yellow">';
                    for ($i=0; $i < $rt ; $i++) {
                        $html.='<i class="pad_none fa fa-star"></i>';
                    }
                    if ($xv>0) {
                        for ($i=0; $i <$xv ; $i++) {
                            $html.='<i class="pad_none fa fa-star-o"></i>';
                        }
                    }
                    $html.='</span></div><div class="pro_price">';
                    if (isset($proMod->allPrices[$dis_price_indx])) {
                        if ($proMod->allPrices[$dis_price_indx]["basePriceWithTax"]>$proMod->allPrices[$dis_price_indx]["salesPrice"]) {
                            $html.='<span style="text-decoration:line-through">'.$currencyInstance->getFormattedCurrency(
                                $currencyInstance->roundForDisplay(
                                    $currencyInstance->convertCurrencyTo(
                                        $changeCurrency,
                                        $proMod->allPrices[$dis_price_indx]["basePriceWithTax"],
                                        false
                                    )
                                )
                            ).'</span>&nbsp;&nbsp;';
                        }
                        $html.= '<span class="current">'. $currencyInstance->getFormattedCurrency(
                            $currencyInstance->roundForDisplay(
                                $currencyInstance->convertCurrencyTo(
                                    $changeCurrency,
                                    $proMod->allPrices[$dis_price_indx]["salesPrice"],
                                    false
                                )
                            )
                        ).'</span>';
                    }
                    $html.='</div><div class="pro_detail"><span>'.
                        (strlen($item->product_s_desc)>50 ?substr($item->product_s_desc, 0, 50).'...' : $item->product_s_desc).
                        '</span></div><div class="action"><a style="display:inline-block;margin-bottom:10px;" href="'.
                        JRoute::_(
                            'index.php?option=com_marketplace&view=addproduct&Itemid='.
                            $addproductmenu->id.'&virtuemart_product_id='.$item->virtuemart_product_id,
                            false
                        ).'"><input type="button" class="btn-success btn" name="edit" value="'.
                        JText::_('MARKETPLACE_EDIT').'"></a></div></div></div>';
                }
            }
            return $html;
        }
    }
    /**
     * Product Assigned To Seller Mail function
     *
     * @param integer $virtuemart_product_id var
     * @param integer $sellerid              var
     * 
     * @return void
     */
    public static function productAssignedToSellerMail(
        $virtuemart_product_id=0, $sellerid=0
    ) {
        if ($virtuemart_product_id==0 || $sellerid==0) {
            return;
        }
        /* Getting email template */
        $params = JComponentHelper::getParams('com_marketplace');
        $body = trim($params->get('mp_temp_product_assigned'));
        $subject = trim($params->get('mp_sub_product_assigned'));
        VmConfig::loadConfig();
        $productModel = VmModel::getModel('Product');
        /* Collecting Required Data For Mail For sellers*/
        $db=JFactory::getDBO();
        $proMod = $productModel->getProduct($virtuemart_product_id, true, true, false);
        $productModel->addImages($proMod);
        $theme_url = VmConfig::get('vm_themeurl', 0);
        if (empty($theme_url)) {
            $theme_url = 'components/com_virtuemart/';
        }
        $no_image= $theme_url.'assets/images/vmgeneral/'.VmConfig::get('no_image_set');
        if (isset($proMod->images) && isset($proMod->images[0]) && $proMod->images[0]->file_url!="") {
            $file_url = $proMod->images[0]->file_url;
        } else {
            $file_url = $no_image;
        }

        $currencyInstance=CurrencyDisplay::getInstance();
        $changeCurrency=$currencyInstance->getCurrencyForDisplay();

        /* Sending mail to seller(s) */
        $seller_data = self::getSeller(
            $sellerid, array('u.username', 'u.name', 's.screenname')
        );
        $mailer=JFactory::getMailer();
        $config=JFactory::getConfig();
        $email=JFactory::getUser($sellerid)->email;
        if (!isset($seller_data->screenname) || $seller_data->screenname == "") {
            $seller_data->screenname = $seller_data->name;
        }
        $dis_price_indx = 0;
        foreach ($proMod->allPrices as $key => $value) {
            if (isset($value["salesPrice"])) {
                $dis_price_indx = $key;
                break;
            }
        }
        $site_curr_total =$currencyInstance->getFormattedCurrency(
            $currencyInstance->roundForDisplay(
                $currencyInstance->convertCurrencyTo($changeCurrency, $proMod->allPrices[$dis_price_indx]["salesPrice"], false)
            )
        );
        /* Replacing Value in Templates*/
        $body = str_replace(
            '{[SELLER_SCREEN]}', ucwords($seller_data->screenname),
            $body
        );
        $subject= str_replace(
            '{[SELLER_SCREEN]}', ucwords($seller_data->screenname),
            $subject
        );
        $body = str_replace(
            '{[PRODUCT_IMG]}', "<img src='".JUri::root().$file_url.
            "' style='height:150px; width:150px; float:left; border: 1px solid #7f8c8d;' >",
            $body
        );
        $body = str_replace(
            '{[PRODUCT_NAME]}', ucwords($proMod->product_name),
            $body
        );
        $subject= str_replace(
            '{[PRODUCT_NAME]}', ucwords($proMod->product_name),
            $subject
        );
        $body = str_replace(
            '{[PRODUCT_PRICE]}', $site_curr_total,
            $body
        );
        /* Setting Values to Mailer */
        $mailer->setSender($config->get('mailfrom'));
        $mailer->addRecipient($email);
        $mailer->setSubject($subject);
        $mailer->isHTML(true);
        $mailer->Encoding = 'base64';
        $mailer->setBody($body);

        /* Send mail */
        $send = $mailer->Send();
    }
}
