<?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('');
jimport('joomla.installer.installer');
/**
 * Com_MarketplaceInstallerScript 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 com_MarketplaceInstallerScript
{
    /**
     * Preflight function
     *
     * @param [type] $type   var
     * @param [type] $parent var
     * 
     * @return void
     */
    public function preflight($type, $parent)
    {
        $installed=JComponentHelper::isInstalled('com_virtuemart');
        $installedMp=JComponentHelper::isInstalled('com_marketplace');
        $app=JFactory::getApplication();
        if (!$installed) {
            $app->redirect(
                'index.php?option=com_installer',
                "Virtuemart Not Installed<strong> Click Here To".
                " Download </strong><a target='_blank' href='//vi".
                "rtuemart.net/downloads'>Virtuemart</a>",
                'error'
            );
        } elseif (!$enabled=JComponentHelper::isEnabled('com_virtuemart')) {
            $app->redirect(
                'index.php?option=com_installer',
                "Please Enable Virtuemart First",
                'error'
            );
        }
    }
    /**
     * Postflight function
     *
     * @param [type] $type   var
     * @param [type] $parent var
     * 
     * @return void
     */
    public function postflight($type, $parent)
    {
        $dbo=JFactory::getConfig();
        $db=JFactory::getDBO();
        $dbName=$dbo->get('db');
        $prefix=$dbo->get('dbprefix');
        
        $query=$db->getQuery(true);
        $query="SELECT * FROM INFORMATION_SCHEMA.COLUMNS  WHERE table_name = '".
            $prefix."marketplace_orderstatus' AND table_schema = '".
            $dbName."' AND column_name = 'seller_id'";
        $db->setQuery($query);
        try {
            $res = $db->loadObject();
        } catch (Exception $e) {
              JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
              return false;
        }
        
        if (!isset($res) || $res == null) {
            $query="CREATE TABLE IF NOT EXISTS `#__marketplace_orderstatus` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `virtuemart_order_id` int(11) NOT NULL,
                `seller_id` int(11) NOT NULL,
                `order_status` varchar(30) NOT NULL,
                PRIMARY KEY (`id`)
                ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
            ";
            $db->setQuery($query);
            try {
                $check = $db->execute();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
                return false;
            }
        }

        $query=$db->getQuery(true);
        $query="SELECT * FROM INFORMATION_SCHEMA.COLUMNS  WHERE table_name = '".
            $prefix."marketplace_ask_admin' AND table_schema = '".
            $dbName."' AND column_name = 'seller_id'";
        $db->setQuery($query);
        try {
            $res = $db->loadObject();
        } catch (Exception $e) {
              JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
              return false;
        }
        
        if (!isset($res) || $res == null) {
            $query="CREATE TABLE `#__marketplace_ask_admin` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `subject` varchar(255) NOT NULL,
                `message` varchar(2000) NOT NULL,
                `seller_id` int(11) NOT NULL,
                `time` datetime NOT NULL,
                `reply` varchar(2000) NOT NULL,
                `reply_time` datetime NOT NULL,
                PRIMARY KEY (`id`)
            );
            ";
            $db->setQuery($query);
            try {
                $check = $db->execute();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
                return false;
            }
        }

        $columnMpp=$db->getTableColumns("#__marketplace_product");
        $colChk_mpp=array_key_exists("viewed", $columnMpp);
        if (!$colChk_mpp) {
            $query = "ALTER TABLE `#__marketplace_product` 
            ADD COLUMN `viewed` int(5) NOT NULL DEFAULT 0;";
            $db->setQuery($query);
            try {
                $db->execute();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
                return false;
            }
        }
        $columnArr=$db->getTableColumns("#__marketplace_orderlist");
        $colChk=array_key_exists("update_status", $columnArr);
        if (!$colChk) {
            $query="ALTER TABLE `#__marketplace_orderlist` ADD CO".
                "LUMN update_status SMALLINT(6) NOT NULL DEFAULT 0";
            $db->setQuery($query);
            try {
                $db->execute();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
                return false;
            }
        }
        $query="ALTER TABLE `#__marketplace_category_request` MODIFY CO".
            "LUMN `requested_date` datetime DEFAULT NULL";
        $db->setQuery($query);
        try {
            $db->execute();
        } catch (Exception $e) {
            JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
            return false;
        }
        $columnArr=$db->getTableColumns("#__marketplace_sellerprofile");
        $selprof_query_count=0;
        $sp_query_part = array();
        if (!array_key_exists("shop_location", $columnArr)) {
            $sp_query_part[$selprof_query_count++]
                ="ADD COLUMN `shop_location` varchar(200) NOT NULL,
                ADD COLUMN `social_enable` int(10) NOT NULL DEFAULT '0',
                ADD COLUMN `social_mode` varchar(100) NOT NULL,
                ADD COLUMN `social_id` varchar(100) NOT NULL,
                DROP `twitterid`,
                DROP `facebookid`";
        }
        if (!array_key_exists("first_name", $columnArr)) {
            $sp_query_part[$selprof_query_count++]
                ="ADD COLUMN `first_name` varchar(255) NOT NULL,
                ADD COLUMN `last_name` varchar(255) NOT NULL,
                ADD COLUMN `phone` varchar(32) NOT NULL,
                ADD COLUMN `address` varchar(255) NOT NULL,
                ADD COLUMN `state_vm` varchar(255) NOT NULL,
                ADD COLUMN `zip` varchar(25) NOT NULL,
                DROP `shortprofile`,
                DROP `avatar`,
                DROP `backgroundcolor`,
                DROP `social_enable`";
        }
        
        if ($selprof_query_count) {
            $query_sp = "ALTER TABLE `#__marketplace_sellerprofile`";
            $query_sp.= implode(',', $sp_query_part);
            $db->setQuery($query_sp);
            $db->execute();
        }
        $columnArr=$db->getTableColumns("#__marketplace_seller_follower");
        if (!array_key_exists("f_id", $columnArr)) {
            $query="ALTER TABLE `#__marketplace_seller_follower`
            MODIFY COLUMN `id` TO `f_id`,
            ";
            $db->setQuery($query);
            $db->execute();
        }
        $columnArr=$db->getTableColumns("#__marketplace_commision");
        if (!array_key_exists("commision_type", $columnArr)) {
            $query="ALTER TABLE `#__marketplace_commision`
            ADD COLUMN `commision_type` varchar(10) NOT NULL DEFAULT 'r'
            ";
            $db->setQuery($query);
            $db->execute();
        }
        $query=$db->getQuery(true);

        $query->select($db->quoteName("msp.seller_id"))
            ->from($db->quoteName("#__marketplace_sellerprofile", "msp"))
            ->join(
                'INNER',
                $db->quoteName('#__user_usergroup_map', 'uum') . ' ON (' .
                $db->quoteName('msp.seller_id') . ' = ' .
                $db->quoteName('uum.user_id') . ')'
            )->where($db->quoteName('uum.group_id')."=".$db->quote("8"));
        $db->setQuery($query);
        $result=$db->loadObjectList();
        if (isset($result) && count($result)>0) {
            $ids="";
            foreach ($result as $key => $value) {
                $ids.=$value->seller_id;
                if ($key<count($result)-1) {
                    $ids.=",";
                }
            }

            $query = $db->getQuery(true);
            $conditions = array(
                $db->quoteName('seller_id') . ' IN('.$ids.')'
            );
            $query->delete($db->quoteName('#__marketplace_sellerprofile'));
            $query->where($conditions);
            $db->setQuery($query);
            $result1 = $db->execute();
        }
        ob_start();

        ?>
        <style type="text/css">
            table{
                border-collapse: separate !important;
            }
            div#wk-installer * {
                -webkit-box-sizing: border-box;
                -moz-box-sizing: border-box;
                box-sizing: border-box;
            }
            div#wk-installer{
                width: 90%;
            }
            div#wk-installer,
            div#wk-installer p,
            div#wk-installer div
            {
                font-family: 'Lucida Grande', 'Gisha', 'Lucida Sans Unicode', 'Lucida Sans', Lucida, Arial, Verdana, sans-serif;
                font-size: 11px;
            }

            div#wk-installer .clearfix,
            div#wk-installer .box-hd,
            div#wk-installer .box-bd {
                clear:none;display:block;
            }
            div#wk-installer .clearfix:after,
            div#wk-installer .box-hd,
            div#wk-installer .box-bd {
                content:"";display:table;clear:both;
            }

            div#wk-installer .box
            {
                background: #F9FAFC;
                border: 1px solid #D3D3D3;
                padding: 0px;
                margin-bottom: 20px;
                color: #777;

                -webkit-border-radius: 3px;
                -moz-border-radius: 3px;
                border-radius: 3px;
            }
            div#wk-installer .box-hd {
                background: #F6F7F9;
                border-bottom: 1px solid #d3d3d3;
                width: 100%;
                padding: 8px 15px 3px;

                -webkit-border-radius: 3px 3px 0 0;
                -moz-border-radius: 3px 3px 0 0;
                border-radius: 3px 3px 0 0;
            }
            div#wk-installer .box-hd .wk-title {
                float: left;
            }
            div#wk-installer .box-hd .wk-logo {
                float: right;
            }
            div#wk-installer .box-hd .wk-logo img {
                width: 100%!important;
            }
            div#wk-installer .box-hd .wk-social {
                float: right;
            }

            div#wk-installer .box-bd {
                padding: 16px !important;
            }
            div#wk-installer .box-bd b{
                color: #333;
            }
            div#wk-installer h1.wk-title {
                font-size: 22px;
                line-height: 24px;
                color: #333;
            }
            div#wk-installer .btn-install {
                font-size: 12px;
                padding: 6px 16px;
                background-color: #2196F3;
                background-image: linear-gradient(to bottom, #2196F3, #0C89ED);
                background-repeat: repeat-x;
                border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
                color: #FFFFFF;
                text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
            }
            div#wk-installer .btn-install:hover {
                background-position: 0 0;
            }
            div#wk-installer .box p
            {
                font-weight: normal;
                text-align: left;
            }
            div#wk-installer .box p img
            {
                padding: 0 25px 0 0;
            }
            div#wk-installer .fb-like,
            div#wk-installer .fb-like iframe{
                width: 85px !important;
                max-width: 85px !important;
            }
            div#wk-installer .twitter-follow-button{
                margin-left: 5px;
                margin-bottom: -5px;
            }
            div#wk-installer .actions{
                text-align: left !important;
                display: inline-block;
            }
            .wk-logo-img
            {
                display: inline-block;
                background-color: #2196F3;
                padding: 1px;
                width: 40%;
            }
            .wk-productby
            {
                float: left;
                margin-top: 7px;
            }
            .helpdesk
            {
                display: inline-block;
            }
            .set-ats
            {
                margin-top: 15px;
                float: right;
            }
        </style>
        <?php
        $db = JFactory::getDBO();
        $status = new stdClass;
        $status->modules = array();
        $status->plugins = array();
        $src = $parent->getParent()->getPath('source');
        $manifest = $parent->getParent()->manifest;
        $plugins = $manifest->xpath('plugins/plugin');
        foreach ($plugins as $plugin) {
            $name = (string)$plugin->attributes()->plugin;
            $group = (string)$plugin->attributes()->group;
            $path = $src.'/plugins/'.$group;
            if (JFolder::exists($src.'/plugins/'.$name)) {
                $path = $src.'/plugins/'.$name;
            }
            $installer = new JInstaller;
            $result = $installer->install($path);

            $query = "UPDATE #__extensions SET enabled=1,param".
                "s='{\"wk_Seller_attach_class\":\"addtocart-area\"}' W".
                "HERE type='plugin' AND element=".$db->Quote($name).
                " AND folder=".$db->Quote($group);
            $db->setQuery($query);
            $db->query();
            $status->plugins[] = array(
                'name' => $name,
                'group' => $group,
                'result' => $result
            );
        }
        $modules = $manifest->xpath('modules/module');
        foreach ($modules as $module) {
            $name = (string)$module->attributes()->module;
            $client = (string)$module->attributes()->client;
            if (is_null($client)) {
                $client = 'site';
            }
            ($client == 'administrator') ? $path = $src.
                '/administrator/modules/'.$name : $path = $src.'/modules/'.$name;


            $installer = new JInstaller;
            $result = $installer->install($path);
            $status->modules[] = array(
                'name' => $name,
                'client' => $client,
                'result' => $result
            );

        }

        $component_id=$this->getComponentId('com_marketplace');
        
        $marketplace_modules=array();
        $query="SELECT id FROM `#__modules` WHERE module='mod_shop'";
        $db->setQuery($query);
        $modules_shop=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_profile'";
        $db->setQuery($query);
        $modules_profile=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_collection'";
        $db->setQuery($query);
        $modules_collection=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_seller_banner'";
        $db->setQuery($query);
        $modules_banner=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_sellercategory'";
        $db->setQuery($query);
        $modules_category=$db->loadResult();

        $menuType = JTable::getInstance('MenuType');
        $menuExists = $menuType->load(array('menutype' => 'marketplace'));
        if ($menuExists) {
            $menuType->delete();
        }
        
        /* Creating menu type */
        if ($this->mpInstallerCreateMenutype('marketplace', 'marketplace') === true) {

            /* Creating menu item for marketplace */
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'My Profile Preview',
                'index.php?option=com_marketplace&view=sellerprofile',
                array( 'component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Seller List',
                'index.php?option=com_marketplace&view=sellerlist',
                array( 'component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Products',
                'index.php?option=com_marketplace&view=products',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Order History',
                'index.php?option=com_marketplace&view=orderhistory',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'My Profile',
                'index.php?option=com_marketplace&view=profile',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'My Payments',
                'index.php?option=com_marketplace&view=mypayments',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Follower',
                'index.php?option=com_marketplace&view=follow',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Products Category',
                'index.php?option=com_marketplace&view=category',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Dashboard',
                'index.php?option=com_marketplace&view=dashboard',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Product List',
                'index.php?option=com_marketplace&view=productlist',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Add Products',
                'index.php?option=com_marketplace&view=addproduct',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Want To Become A Seller',
                'index.php?option=com_marketplace&view=mpregistration',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Buyer Information',
                'index.php?option=com_marketplace&view=customer',
                array('component_id' => (int)$component_id)
            );
            $this->mpInstallerCreateMenuitem(
                'marketplace', 'Ask To Admin',
                'index.php?option=com_marketplace&view=asktoadmin',
                array('component_id' => (int)$component_id)
            );
        }
        $super_user=JFactory::getUser()->id;
        $query="UPDATE `#__virtuemart_products` SET created_by='".$super_user."' WHERE created_by=0";
        $db->setQuery($query);
        $db->execute();
        $query="SELECT id FROM `#__menu` WHERE link='index.php?option=com_marketplace&view=productlist' AND menutype='marketplace'";
        $db->setQuery($query);
        $productlistmenu=$db->loadResult();
        $query="SELECT id FROM `#__menu` WHERE link='index.php?option=com_marketplace&view=category' AND menutype='marketplace'";
        $db->setQuery($query);
        $categorymenu=$db->loadResult();
        $query="SELECT id FROM `#__menu` WHERE link='index.php?option=com_marketplace&view=sellerprofile' AND menutype='marketplace'";
        $db->setQuery($query);
        $sellerprofilemenu=$db->loadResult();
        $query="SELECT id FROM `#__menu` WHERE link='index.php?option=com_marketplace&view=products' AND menutype='marketplace'";
        $db->setQuery($query);
        $productmenu=$db->loadResult();
        $query="INSERT INTO `#__modules_menu` (`moduleid`,`menuid`)
         VALUES('".$modules_collection."','".$categorymenu."'),
         ('".$modules_profile."','".$sellerprofilemenu."'),
         ('".$modules_profile."','".$categorymenu."'),
         ('".$modules_profile."','".$productmenu."'),
         ('".$modules_banner."','".$sellerprofilemenu."'),
         ('".$modules_category."','".$productlistmenu."'),
         ('".$modules_category."','".$categorymenu."'),
         ('".$modules_shop."','".$sellerprofilemenu."'),
         ('".$modules_shop."','".$productmenu."')
         ON DUPLICATE KEY UPDATE moduleid=moduleid ";
        $db->setQuery($query);
        $db->execute();
        $query="UPDATE `#__modules` SET `showtitle` = '0',`published` = '1',`position` = CASE
            WHEN  id = ".$modules_banner."  THEN 'wk_marketplace-top'
            WHEN  id =".$modules_profile." OR id=".$modules_category." OR id=".$modules_shop."  OR id=".$modules_collection." THEN 'wk_marketplace-right'
            END WHERE id IN(".$modules_banner.",".$modules_profile.",".$modules_category.",".$modules_shop.",".$modules_collection.")";

        $db->setQuery($query);
        $db->execute();
        ?>
        <div id="wk-installer">
            <div class="box">
                <div class="box-hd">
                    <div class="wk-title">
                        <b>Joomla Virtuemart Multi Vendor Marketplace</b> Successfully Installed.
                    </div>
                    <div class="wk-social socialize">
                        <div id="fb-root"></div>
                        <script>(function(d, s, id) {
                          var js, fjs = d.getElementsByTagName(s)[0];
                          if (d.getElementById(id)) return;
                          js = d.createElement(s); js.id = id;
                          js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.5&appId=406369119482668";
                          fjs.parentNode.insertBefore(js, fjs);
                        }(document, 'script', 'facebook-jssdk'));</script>
                        <div class="fb-like" data-href="http://www.facebook.com/webkul" data-layout="button_count" data-show-faces="false" data-send="false"></div>
                        <a href="https://twitter.com/webkul" class="twitter-follow-button" data-show-count="false">Follow @webkul</a>
                        <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
                    </div>
                    <div class="wk-logo">
                        <div class="wk-productby">
                            Another product by&nbsp;
                        </div>
                        <div class="wk-logo-img">
                            <a href="https://store.webkul.com/" target="_blank"><img src="components/com_marketplace/assets/images/webkul_logo.png" alt=""></a>
                        </div>
                    </div>
                </div>
                <div class="box-bd">
                    <h1 class="wk-title">
                        Thank you for your recent purchase of Joomla Virtuemart Multi Vendor Marketplace.
                    </h1>
                    <p>
                        Thank you for your recent purchase of Joomla Virtuemart Multi Vendor Marketplace and congratulations on making the choice to use one of the best extension available for Joomla Virtuemart! Please read out documentation and Configure the package.<b> Kindly save configurations before setting up and testing the whole extension.</b>
                    </p>
                    <div class="helpdesk">
                        <p>
                            Shoot a ticket on our helpdesk for any support.
                        </p>
                        <div class="actions">
                        <a href="mailto:support@webkul.com" target="_top">support@webkul.com</a></p>

                        </div>
                    </div>
                    <div class="actions set-ats">
                        <a href="index.php?option=com_marketplace" class="btn btn-success btn-install"><span class="icon-cogs icon-large"></span> &nbsp;&nbsp;Go To Component &raquo;</a>
                    </div>
                    <div style="clear:both;"></div>
                </div>
            </div>
        </div>
        <?php
        $this->_installationResults($status);
        $contents   = ob_get_contents();
        ob_end_clean();
        echo $contents;
    }
    /**
     * Uninstall function
     *
     * @param [type] $parent var
     * 
     * @return void
     */
    public function uninstall($parent)
    {
        ob_start();
        ?>
        <style type="text/css">
            table{
                border-collapse: separate !important;
            }
            div#wk-installer * {
                -webkit-box-sizing: border-box;
                -moz-box-sizing: border-box;
                box-sizing: border-box;
            }
            div#wk-installer{
                width: 95%;
            }
            div#wk-installer,
            div#wk-installer p,
            div#wk-installer div
            {
                font-family: 'Lucida Grande', 'Gisha', 'Lucida Sans Unicode', 'Lucida Sans', Lucida, Arial, Verdana, sans-serif;
                font-size: 11px;
            }

            div#wk-installer .clearfix,
            div#wk-installer .box-hd,
            div#wk-installer .box-bd {
                clear:none;display:block;
            }
            div#wk-installer .clearfix:after,
            div#wk-installer .box-hd,
            div#wk-installer .box-bd {
                content:"";display:table;clear:both;
            }

            div#wk-installer .box
            {
                background: #F9FAFC;
                border: 1px solid #D3D3D3;
                padding: 0px;
                margin-bottom: 20px;
                color: #777;

                -webkit-border-radius: 3px;
                -moz-border-radius: 3px;
                border-radius: 3px;
            }
            div#wk-installer .box-hd {
                background: #F6F7F9;
                border-bottom: 1px solid #d3d3d3;
                width: 100%;
                padding: 8px 15px 3px;

                -webkit-border-radius: 3px 3px 0 0;
                -moz-border-radius: 3px 3px 0 0;
                border-radius: 3px 3px 0 0;
            }
            div#wk-installer .box-hd .wk-title {
                float: left;
            }
            div#wk-installer .box-hd .wk-logo {
                float: right;
            }
            div#wk-installer .box-hd .wk-logo img {
                width: 100%!important;
            }
            div#wk-installer .box-hd .wk-social {
                float: right;
            }

            div#wk-installer .box-bd {
                padding: 16px !important;
            }
            div#wk-installer h1.wk-title {
                font-size: 22px;
                line-height: 24px;
                color: #333;
            }

            div#wk-installer .btn-install {
                font-size: 12px;
                padding: 6px 16px;
                background-color: #2196F3;
                background-image: linear-gradient(to bottom, #2196F3, #0C89ED);
                background-repeat: repeat-x;
                border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
                color: #FFFFFF;
                text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
            }
            div#wk-installer .btn-install:hover {
                background-position: 0 0;
            }
            div#wk-installer .box p
            {
                font-weight: normal;
                text-align: left;
            }
            div#wk-installer .box p img
            {
                padding: 0 25px 0 0;
            }
            div#wk-installer .twitter-follow-button{
                margin-left: 5px;
                margin-bottom: -5px;
            }
            div#wk-installer .actions{
                margin-top: 15px;
                text-align: left !important;
            }
            .wk-logo-img
            {
                display: inline-block;
                background-color: #2196F3;
                padding: 1px;
                width: 40%;
            }
            .wk-productby
            {
                float: left;
                margin-top: 7px;
            }
        </style>
        <?php
        if (!class_exists('VmConfig')) {
            include JPATH_ADMINISTRATOR .
                '/components/com_virtuemart/helpers/config.php';
        }

        VmConfig::loadConfig();
        $db = JFactory::getDBO();
        $query=$db->getQuery(true);
        $query->select($db->quoteName('seller_id'))
            ->from($db->quoteName('#__marketplace_sellerprofile'));
        $db->setQuery($query);
        $seller_data=$db->loadObjectList();
        if ($seller_data) {
            $seller_ids=array();
            foreach ($seller_data as $key => $value) {
                $seller_ids[] = $value->seller_id;
            }
            $query=$db->getQuery(true);
            $query->select($db->quoteName('virtuemart_product_id'))
                ->from($db->quoteName('#__virtuemart_products'))
                ->where($db->quoteName('created_by')." IN(".$seller_ids.")");
            $db->setQuery($query);
            $results=$db->loadObjectList();
            $productModel=VmModel::getModel('product');
            $productsArr=array();
            foreach ($results as $key => $value) {
                $productsArr[]=$value->virtuemart_product_id;
            }
            $productModel->remove($productsArr);
        }

        $query=$db->getQuery(true);
        $query->select($db->quoteName("user_id"))
            ->from($db->quoteName("#__user_usergroup_map"))
            ->where($db->quoteName("group_id").'='.$db->quote("8"));
        $db->setQuery($query);
        $res=$db->loadObject();

        $query = $db->getQuery(true);
        $fields = array(
            $db->quoteName('created_by') . ' = ' . $db->quote($res->user_id)
        );
        $query->update($db->quoteName('#__virtuemart_products'))->set($fields);
        $db->setQuery($query);
        $result = $db->execute();

        
        $marketplace_modules=array();
        $query=null;
        $query="SELECT id FROM `#__modules` WHERE module='mod_shop'";
        $db->setQuery($query);
        $marketplace_modules[]=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_profile'";
        $db->setQuery($query);
        $marketplace_modules[]=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_collection'";
        $db->setQuery($query);
        $marketplace_modules[]=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_seller_banner'";
        $db->setQuery($query);
        $marketplace_modules[]=$db->loadResult();
        $query="SELECT id FROM `#__modules` WHERE module='mod_sellercategory'";
        $db->setQuery($query);
        $marketplace_modules[]=$db->loadResult();
        if (strlen($marketplace_modules[0])) {
            $query="DELETE FROM `#__modules_menu` WHERE menuid IN(".implode(',', $marketplace_modules).") ";
            $db->setQuery($query);
            $db->execute();
        }
        $query="DELETE FROM `#__menu` WHERE menutype='marketplace'";
        $db->setQuery($query);
        $db->execute();
        $query="DELETE FROM `#__menu_types` WHERE menutype='marketplace'";
        $db->setQuery($query);
        $db->execute();
        $status = new stdClass;
        $status->modules = array();
        $status->plugins = array();
        $manifest = $parent->getParent()->manifest;
        $plugins = $manifest->xpath('plugins/plugin');
        foreach ($plugins as $plugin) {
            $name = (string)$plugin->attributes()->plugin;
            $group = (string)$plugin->attributes()->group;
            $query = "SELECT `extension_id` FROM #__extensions WHERE `type`='plugin' AND element = ".$db->Quote($name)." AND folder = ".$db->Quote($group);
            $db->setQuery($query);
            $extensions = $db->loadColumn();
            if (count($extensions)) {
                foreach ($extensions as $id) {
                    $installer = new JInstaller;
                    $result = $installer->uninstall('plugin', $id);
                }
                $status->plugins[] = array('name' => $name, 'group' => $group, 'result' => $result);
            }
        }
        $modules = $manifest->xpath('modules/module');
        foreach ($modules as $module) {
            $name = (string)$module->attributes()->module;
            $client = (string)$module->attributes()->client;
            $db = JFactory::getDBO();
            $query = "SELECT `extension_id` FROM `#__extensions` WHERE `type`='module' AND element = ".$db->Quote($name);
            $db->setQuery($query);
            $extensions = $db->loadColumn();
            if (count($extensions)) {
                foreach ($extensions as $id) {
                    $installer = new JInstaller;
                    $result = $installer->uninstall('module', $id);
                }
                $status->modules[] = array(
                    'name' => $name,
                    'client' => $client,
                    'result' => $result
                );
            }
        }
        ?>
<div id="wk-installer">
    <div class="box">
        <div class="box-hd">
            <div class="wk-title">
                <b>Joomla Virtuemart Multi Vendor Marketplace</b> Successfully Uninstalled.
            </div>
            <div class="wk-social socialize">
                <div id="fb-root"></div>
                <script>
                    (function (d, s, id) {
                        var js, fjs = d.getElementsByTagName(s)[0];
                        if (d.getElementById(id)) return;
                        js = d.createElement(s);
                        js.id = id;
                        js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.5&appId=406369119482668";
                        fjs.parentNode.insertBefore(js, fjs);
                    }(document, 'script', 'facebook-jssdk'));
                </script>
                <div class="fb-like" data-href="http://www.facebook.com/webkul" data-layout="button_count" data-show-faces="false" data-send="false"></div>
                <a href="https://twitter.com/webkul" class="twitter-follow-button" data-show-count="false">Follow @webkul</a>
                <script>
                    ! function (d, s, id) {
                        var js, fjs = d.getElementsByTagName(s)[0];
                        if (!d.getElementById(id)) {
                            js = d.createElement(s);
                            js.id = id;
                            js.src = "//platform.twitter.com/widgets.js";
                            fjs.parentNode.insertBefore(js, fjs);
                        }
                    }(document, "script", "twitter-wjs");
                </script>
            </div>
        </div>
        <div class="box-bd">
            <h1 class="wk-title">
                Thank you for using Joomla Virtuemart Multi Vendor Marketplace.
            </h1>
            <p>
                Thank you for using Joomla Virtuemart Multi Vendor Marketplace. It's sad to see you going away. If you faced any trouble
                in using the extension or unsatisfied by any other functionality, you can tell us by shooting a ticket on
                our helpdesk.
            </p>
            <div class="actions">
                <a href="https://webkul.com/ticket/" target="_blank" class="btn btn-success btn-install">Helpdesk &raquo;</a>
            </div>
            <div style="clear:both;"></div>
        </div>
    </div>
</div>
        <?php
        $this->_uninstallationResults($status);
        $contents   = ob_get_contents();
        ob_end_clean();
        echo $contents;
    }
    /**
     * Update function
     *
     * @param [type] $parent var
     * 
     * @return void
     */
    function update($parent)
    {
        $dbo=JFactory::getConfig();
        $db=JFactory::getDBO();
        $dbName=$dbo->get('db');
        $prefix=$dbo->get('dbprefix');
        $query="CREATE TABLE IF NOT EXISTS `".$prefix."marketplace_category_request` (`id` int(5) NOT NULL AUTO_INCREMENT,`category_name` varchar(255) DEFAULT NULL,
  `category_desc` text,`requested_by` varchar(255) DEFAULT NULL,`requested_date` date DEFAULT NULL,`additional_info` text,`status` tinyint(4) NOT NULL,PRIMARY KEY (`id`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ";
        $db->setQuery($query);
        $result=$db->execute();
    }
    /**
     * InstallationResults function
     *
     * @param [type] $status var
     * 
     * @return void
     */
    private function _installationResults($status)
    {
        $comparams='{"head_bg_color":"#404040","head_txt_color":"#ffffff","paypal_shop_mode":"s","commision_option":"f","commision":"10","commision_amount":"500","commisionUpdateOn":["C"],"mapkey":"AIzaSyCX2m_RlPCDa0l0NLIWwPuXPt31-97q8QQ","wk_fbloginselect":"0","appid":"","secretkey":"","recaptcha_enable":"0","captcha":"0","wk_addproduct_imgsize":"2000","product_action_seller_delete":"ps","create_product":"1","create_seller":"1","wk_feedback_approv":"0","wk_price_discount":"1","wk_price_tax":"1","wk_lazy_load_limit":"5","mp_reg_term":"0","mp_reg_rules":"","mp_add_term":"0","mp_add_rules":"","mp_sub_mail_order_done":"Confirmed Order By {[ORDER_NAME]}","mp_temp_mail_order_done":"<p>Hello <strong>{[RECEPIENT_SELLER_SCREEN]}<\/strong>,<br \/><strong>{[ORDER_NAME]}<\/strong> placed an order with a total of {[ORDER_TOTAL]},his\/her order number {[ORDER_NUMBER]}.<\/p>\r\n<h2>Bill To<\/h2>\r\n<p>{[BILL_TO_ORDER]}<\/p>\r\n<h2>Product Details<\/h2>\r\n<p>{[ORDER_PRODUCT_DETAILS]}<\/p>\r\n<p><br \/><br \/><\/p>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_mail_order_status":"Order Status Changed","mp_temp_mail_order_status":"<div class=\"moz-text-html\" lang=\"x-unicode\">\r\n<h3><span style=\"color: #000000;\">Hello {[RECEPIENT_NAME]}<\/span><\/h3>\r\n<h4><span style=\"color: #000000;\">Order Status Changed<\/span><\/h4>\r\n<div><span style=\"width: 48%; display: inline-block;\"><strong>Order No<\/strong> : {[ORDER_NO]}<\/span><span style=\"width: 48%; display: inline-block;\"><strong>Seller Name<\/strong> : {[SELLER_NAME]}<br \/><\/span><\/div>\r\n<hr \/><span style=\"color: #000000;\">{[ORDER_PRODUCT_STATUS_CHANGES]}<\/span><\/div>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_new_product":"{[SELLER_SCREEN]} added a new product : {[PRODUCT_NAME]}","mp_temp_new_product":"<p>Hello <strong>{[SITE_FROM_NAME]}<\/strong>,<br \/>\u00a0\u00a0 Seller {[SELLER_SCREEN]} Added a new product<\/p>\r\n<p>\u00a0\u00a0 Product Name : {[PRODUCT_NAME]} .<br \/><br \/><\/p>\r\n<div style=\"border: 3px solid #d35400; display: block; margin: 9px; padding: 30px; min-width: 550px; width: 50%; height: auto; border-redius: 12px;\">\r\n<div id=\"mail-price-alert-left\">{[PRODUCT_IMG]}<\/div>\r\n<div id=\"mail-price-alert-right\" style=\"color: #2980b9; display: inline-block; padding-left: 30px;\">\r\n<h1>{[PRODUCT_NAME]}<\/h1>\r\n<h2>Product Price : {[PRODUCT_PRICE]}<\/h2>\r\n<\/div>\r\n<\/div>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_new_product_approval":"Approval For Add Product By Seller :  {[SELLER_SCREEN]}","mp_temp_new_product_approval":"<p>Hello <strong>{[SITE_FROM_NAME]}<\/strong>,<br \/>\u00a0\u00a0 Seller {[SELLER_SCREEN]} wants to add a new product.<br \/>\u00a0\u00a0 Please Click On Link to View the Seller Product.<br \/><br \/><br \/><\/p>\r\n<div style=\"border: 3px solid #d35400; display: block; margin: 9px; padding: 30px; min-width: 550px; width: 50%; height: auto; border-redius: 12px;\">\r\n<div id=\"mail-price-alert-left\">{[PRODUCT_IMG]}<\/div>\r\n<div id=\"mail-price-alert-right\" style=\"color: #2980b9; display: inline-block; padding-left: 30px;\">\r\n<h1>{[PRODUCT_NAME]}<\/h1>\r\n<h2>Product Price : {[PRODUCT_PRICE]}<\/h2>\r\n<p><a href=\"{[PRODUCTS_LINK]}\">Click Here To View Products<\/a><\/p>\r\n<\/div>\r\n<\/div>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_seller_register":"A new seller registration from {[SELLER_SCREEN]}","mp_temp_seller_register":"<p>Hello <strong>{[SITE_FROM_NAME]}<\/strong>,<br \/><br \/>A new seller registration request is received for <strong>{[SELLER_SCREEN]}<\/strong>.<br \/><br \/>Please go to\u00a0<a href=\"{[SELLERS_VIEW_ADMIN]}\">{[SELLERS_VIEW_ADMIN]}<\/a> for details.<\/p>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_convert_seller":"Seller registration Confirmation: {[USER_NAME]} ","mp_temp_convert_seller":"<p>Hello\u00a0{[USER_NAME]},<\/p>\r\n<p>\u00a0 \u00a0 \u00a0 \u00a0 You have been registered\/converted into seller of SIte\u00a0{[SITE_FROM_NAME]}<\/p>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_product_assigned":"Admin has assigned you a product","mp_temp_product_assigned":"<p>Hello <strong>{[SELLER_SCREEN]}<\/strong>,<br \/>\u00a0\u00a0 Admin has assigned you a new product.<\/p>\r\n<div style=\"border: 3px solid #d35400; display: block; margin: 9px; padding: 30px; min-width: 550px; width: 50%; height: auto; border-redius: 12px;\">\r\n<div id=\"mail-price-alert-left\">{[PRODUCT_IMG]}<\/div>\r\n<div id=\"mail-price-alert-right\" style=\"color: #2980b9; display: inline-block; padding-left: 30px;\">\r\n<h1>{[PRODUCT_NAME]}<\/h1>\r\n<h2>Product Price : {[PRODUCT_PRICE]}<\/h2>\r\n<\/div>\r\n<\/div>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>","mp_sub_seller_removed":"Admin has removed your seller account.","mp_temp_seller_removed":"<p>Your seller account has been removed.<\/p>\r\n<div class=\"moz-text-html\" lang=\"x-unicode\">\u00a0<\/div>\r\n<div style=\"text-align: center;\"><strong>Thank You<\/strong><\/div>"}';
        $db = JFactory::getDBO();
        $componentid = $this->getComponentId('com_marketplace');
        $table = JTable::getInstance('extension');
        $table->load($componentid);
        $table->bind(array('params' => $comparams));
        if (!$table->store()) {

        }
        $rows = 0; ?>
        <h2><?php echo JText::_('Virtuemart Marketplace For Joomla Install Status'); ?></h2>
        <table class="adminlist table table-striped">
            <thead>
                <tr>
                    <th class="title" colspan="2"><?php echo JText::_('Extension'); ?></th>
                    <th width="30%"><?php echo JText::_('Status'); ?></th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <td colspan="3"></td>
                </tr>
            </tfoot>
            <tbody>
                <tr>
                    <th><?php echo JText::_('Component'); ?></th>
                    <th><?php echo JText::_('Location'); ?></th>
                    <th></th>
                </tr>
                <tr class="row0">
                    <td class="key"><?php echo JText::_('MarketPlace for virtuemart'); ?></td>
                    <td class="key">Administrator+Site</td>
                    <td><strong><?php echo JText::_('Installed'); ?></strong></td>
                </tr>
                <?php if (count($status->modules)) : ?>
                <tr>
                    <th><?php echo JText::_('Module'); ?></th>
                    <th><?php echo JText::_('Client'); ?></th>
                    <th></th>
                </tr>
                <?php foreach ($status->modules as $module) : ?>
                <tr class="row<?php echo(++$rows % 2); ?>">
                    <td class="key"><?php echo $module['name']; ?></td>
                    <td class="key"><?php echo ucfirst($module['client']); ?></td>
                    <td><strong><?php echo ($module['result'])?JText::_('Installed'):JText::_('Not Installed'); ?></strong></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
                <?php if (count($status->plugins)) : ?>
                <tr>
                    <th><?php echo JText::_('Plugin'); ?></th>
                    <th><?php echo JText::_('Group'); ?></th>
                    <th></th>
                </tr>
                <?php foreach ($status->plugins as $plugin) : ?>
                <tr class="row<?php echo(++$rows % 2); ?>">
                    <td class="key"><?php echo ucfirst($plugin['name']); ?></td>
                    <td class="key"><?php echo ucfirst($plugin['group']); ?></td>
                    <td><strong><?php echo ($plugin['result'])?JText::_('Installed'):JText::_('Not Installed'); ?></strong></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    <?php
    }
    /**
     * UninstallationResults function
     *
     * @param [type] $status var
     * 
     * @return void
     */
    private function _uninstallationResults($status)
    {
        $rows = 0;
    ?>
        <h2><?php echo JText::_('Virtuemart Marketplace For Joomla Removal Status'); ?></h2>
        <table class="adminlist table table-striped">
            <thead>
                <tr>
                    <th class="title" colspan="2"><?php echo JText::_('Extension'); ?></th>
                    <th width="30%"><?php echo JText::_('Status'); ?></th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <td colspan="3"></td>
                </tr>
            </tfoot>
            <tbody>
                <tr>
                    <th><?php echo JText::_('Component'); ?></th>
                    <th><?php echo JText::_('Location'); ?></th>
                    <th></th>
                </tr>
                <tr class="row0">
                    <td class="key"><?php echo JText::_('MarketPlace for virtuemart'); ?></td>
                    <td class="key">Administrator+Site</td>
                    <td><strong><?php echo JText::_('UnInstalled'); ?></strong></td>
                </tr>
                <?php if (count($status->modules)) : ?>
                <tr>
                    <th><?php echo JText::_('Module'); ?></th>
                    <th><?php echo JText::_('Client'); ?></th>
                    <th></th>
                </tr>
                <?php foreach ($status->modules as $module): ?>
                <tr class="row<?php echo(++$rows % 2); ?>">
                    <td class="key"><?php echo $module['name']; ?></td>
                    <td class="key"><?php echo ucfirst($module['client']); ?></td>
                    <td><strong><?php echo ($module['result'])?JText::_('UnInstalled'):JText::_('Not Removed'); ?></strong></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>

                <?php if (count($status->plugins)) : ?>
                <tr>
                    <th><?php echo JText::_('Plugin'); ?></th>
                    <th><?php echo JText::_('Group'); ?></th>
                    <th></th>
                </tr>
                <?php foreach ($status->plugins as $plugin): ?>
                <tr class="row<?php echo(++$rows % 2); ?>">
                    <td class="key"><?php echo ucfirst($plugin['name']); ?></td>
                    <td class="key"><?php echo ucfirst($plugin['group']); ?></td>
                    <td><strong><?php echo ($plugin['result'])?JText::_('UnInstalled'):JText::_('Not Removed'); ?></strong></td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    <?php
    }
    /**
     * Get Component Id
     *
     * @param string $option var
     * 
     * @return void
     */
    function getComponentId($option)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select($db->quoteName('extension_id'))
            ->from($db->quoteName('#__extensions'))
            ->where($db->quoteName('element')."=".$db->quote($option));
        $db->setQuery($query);
        try{
            $component = $db->loadObject();
            return $component->extension_id;
        } catch(Exception $e) {
            return null;
        }
    }
    /**
     * MpInstallerCreateMenuitem function by Pratyush
     *
     * @param [type] $menuType   var
     * @param [type] $title      var
     * @param [type] $url        var
     * @param array  $properties var
     * 
     * @return void
     */
    function mpInstallerCreateMenuitem(
        $menuType, $title, $url, $properties = array()
    ) {
        $alias = trim(
            preg_replace(
                '/_+/', '-', preg_replace(
                    '/\W+/', '', str_replace(
                        ' ', '_', str_replace('_', '', trim(strtolower($title)))
                    )
                )
            )
        );
        $table = JTable::getInstance('Menu');
        while ( $table->load(array('alias' => $alias))) {
            $matches = null;
            if (preg_match('#-(\d+)$#', $alias, $matches)) {
                $alias = preg_replace(
                    '#-(\d+)$#', '-' . ($matches[1] + 1) . '', $alias
                );
            } else {
                $alias .= '-2';
            }
        }

        $menu = JTable::getInstance('menu');
        $menu->menutype    = $menuType;
        $menu->title    = $title;
        $menu->alias    = $alias;
        $menu->link     = $url;
        $menu->type     = 'component';
        $menu->language    = '*';
        $menu->published   = 1;

        if ($properties) {
            $menu->bind($properties);
        }

        $menu->check();
        if (!$menu->store()) {
            return false;
        } else {
            if (!$menu->parent_id) {
                $menu->parent_id = 1;
            }
            if (! $menu->level) {
                $menu->level  = 1;
            }

            if (!$menu->store()) {
                return false;
            }
        }
        return true;
    }
    /**
     * MpInstallerCreateMenutype function by Pratyush
     *
     * @param [type] $type        var
     * @param [type] $title       var
     * @param [type] $description var
     * @param array  $properties  var
     * 
     * @return void
     */
    function mpInstallerCreateMenutype(
        $type, $title, $description = null, $properties = array()
    ) {
        $menuType = JTable::getInstance('MenuType');
        if (!$menuType->load(array('menutype' => $type))) {
            $menuType->menutype  = $type;
            $menuType->title  = $title;
            $menuType->description = $description;

            if ($properties) {
                $menuType->bind($properties);
            }
            $menuType->check();
            if (!$menuType->store()) {
                return false;
            }
        } else {
            return null;
        }
        return true;
    }
}
