<?php
/**
 * Marketplace - Component Marketplace 
 * ******************************************************************
 *
 * PHP version 7.0
 *
 * @category   Component
 * @package    Joomla
 * @author     WebKul software private limited <support@webkul.com>
 * @copyright  2010 WebKul software private limited
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @version    GIT:5.2
 * @filesource http://store.webkul.com
 * @link       Technical Support:  webkul.uvdesk.com
 * ******************************************************************
 */
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.form.form');
jimport('joomla.application.component.controller');
JHTML::_('behavior.modal');
jimport('joomla.filesystem.folder');
if (!class_exists('MarketplaceControllerMarketplace')) {
    /**
     * MarketplaceControllerMarketplace 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 MarketplaceControllerMarketplace extends JControllerAdmin
    {
        /**
         * __construct function
         */
        public function __construct()
        {
            parent::__construct();
        }
        /**
         * This is add function
         *
         * @return void
         */
        public function add()
        {
            $jinput=JFactory::getApplication()->input;
            $cid = $jinput->get('cid', array(0), 'post', 'array');
            if (!is_array($cid) || count($cid) < 1) {
                JError::raiseError(500, JText::_('SELECT_UNPUBLISH'));
            }
            $model = $this->getModel('marketplace');
            if (!$model->addpartner($cid)) {
                echo "<script> alert('".
                $model->getError().
                "'); window.history.go(-1); </script>\n";
            }
            $total = count($cid);
            $msg = $total.' '.JText::_('PARTNER_ADDED');
            $this->setRedirect(
                'index.php?option=com_marketplace&view=marketplace',
                $msg
            );
        }
        /**
         * Deny function
         *
         * @return void
         */
        function deny()
        {
            $jinput=JFactory::getApplication()->input;
            $cid = $jinput->getVar('cid', array(0), 'post', 'array');
            if (!is_array($cid) || count($cid) < 1) {
                JError::raiseError(
                    500,
                    JText::_('SELECT_UNPUBLISH')
                );
            }

            $model = $this->getModel('marketplace');
            if (!$model->denypartner($cid)) {
                echo "<script> alert('".$model->getError()
                ."'); window.history.go(-1); </script>\n";
            }

            $total = count($cid);
            $msg = $total.' '.JText::_('PARTNER_REMOVE');
            $this->setRedirect(
                'index.php?option=com_marketplace&view=marketplace',
                $msg
            );
        }
        /**
         * This is saveseller function
         *
         * @return void
         */
        public function saveseller()
        {
            $app=JFactory::getApplication()->input;
            $submit=array();
            $jform1=$app->files->get('jform');
            $jform=$app->get('jform', 'post', 'array');
            $filter = JFilterInput::getInstance();
            
            $jform["shortdescription"]=$filter->clean($jform["shortdescription"], "STRING");
            
            $payment=$app->get('payment', "post", 'array');
            $payment_mode=$app->get('payment_mode', "post", 'array');
            
            foreach ($payment as $key => $value) {
                if ($value == "") {
                    unset($payment[$key]);
                }
            }
            $payment=array_values($payment);
            $country_id = $app->getString('countries', "");
            $state_id = $app->getInt('virtuemart_state_id', 0);
            foreach ($jform as $key => $value) {
                $submit[$key]=$value;
            }
            
            $model=$this->getModel('marketplace');
            $submit['countrylogo'] = $country_id;
            $submit['state_vm'] = $state_id;
            $submit['seller_id']=$app->get('seller_id', 0, 'INT');
            if (in_array('remitasplit', $payment_mode)) {
                $remitaIndex=array_search('remitasplit', $payment_mode);
                $remita_account=$app->get('remita_account', "post");
                $remita_name=$app->get('remita_name', "post");
                $remita_bank_code=$app->get('remita_bank_code', "post");
                if (strlen(trim($remita_name)) !=0
                    && strlen(trim($remita_account)) !=0
                    && strlen(trim($remita_bank_code)) !=0
                ) {
                    if (!class_exists('MarketplaceHelper')) {
                        include JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.
                        'components'.DIRECTORY_SEPARATOR.'com_marketplace'.
                        DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.
                        'marketplace.php';
                    }
                    $mpHelp=new MarketplaceHelper();
                    $modProfFE=$mpHelp->getMarketModelS('Profile');
                    $modProfFE->saveRemitaDetails(
                        $remita_name,
                        $remita_account,
                        $remita_bank_code,
                        $submit['seller_id']
                    );
                } else {
                    JFactory::getApplication()->enqueueMessage(
                        JText::_('EMPTY_REMITA_FIELDS'),
                        'warning'
                    );
                }
            }
            $submit['payment_mode']=implode(',', $payment_mode);
            $submit['payment_desc']=implode(',', $payment);
            $customerfolder = JPATH_ROOT.'/media/marketplace';
            if (!JFolder::exists($customerfolder)) {
                $suc_create = JFolder::create($customerfolder, 0777);
                if (!$suc_create) {
                    $message = "MP_FOLDER_CUSTOM_PARTNER_CREATE_MESS_ERROR. ";
                    return false;
                }
            }
            $customer_id =$app->get('seller_id', '', 'post');;
            $uploadpath =  $customerfolder .'/user'.$customer_id;
            if (!JFolder::exists($uploadpath)) {
                $suc_create = JFolder::create($customerfolder, 0777);
                if (!$suc_create) {
                    $message = "MP_FOLDER_CREATE_MESS_ERROR."; 
                    return false;
                }
            }
            $webPath = '';
            if (!empty($jform1['cover']['name'])) {
                $safename = JFile::makeSafe($jform1['cover']['name']);
                $safename = strtolower($safename);
                $res = JFile::upload(
                    $jform1['cover']['tmp_name'], $uploadpath ."/". $safename
                );
                if (!$res) {
                    $this->setRedirect(
                        'index.php?option=com_marketplace&view=marketp'.
                        'lace&layout=edit_seller_form&seller_id='.
                        $submit['seller_id'],
                        $this->getError(),
                        'error'
                    );
                }
                $webPath ='media/marketplace/user'.$customer_id.'/'. $safename; 
                $submit['cover']= $webPath; 
            }
            if (!empty($jform1['shoplogo']['name'])) {
                $safename = JFile::makeSafe($jform1['shoplogo']['name']);
                $safename = strtolower($safename);
                if (!JFile::upload(
                    $jform1['shoplogo']['tmp_name'],
                    $uploadpath ."/". $safename
                )
                ) {
                    $this->setRedirect(
                        'index.php?option=com_marketplace&view=marketpla'.
                        'ce&layout=edit_seller_form&seller_id='.
                        $submit['seller_id'],
                        $this->getError(),
                        'error'
                    );
                    $this->redirect();
                }
                $webPath = 'media/marketplace/user'.$customer_id.'/'. $safename;
                $submit['shoplogo'] = $webPath;
            }
            $model=$this->getModel('marketplace');
            $result_save =$model->saveItem($submit);
            if (!$result_save) {
                $this->setRedirect(
                    'index.php?option=com_marketplace&view=marketplace&lay'.
                    'out=edit_seller_form&seller_id='.$submit['seller_id'],
                    $model->getError(),
                    'error'
                );
            } else {
                $this->setRedirect(
                    'index.php?option=com_marketplace&view=marketplace&layo'.
                    'ut=edit_seller_form&seller_id='.$submit['seller_id'],
                    JText::_('SELLER_PROFILE_SUSS_SAVE')
                );
            }
        }
        /**
         * This is remove function
         *
         * @return void
         */
        public function remove()
        {
            global $option;
            $jinput=JFactory::getApplication()->input;
            $cid = $jinput->getVar('cid', array(0), 'post', 'array');
            if (!is_array($cid) || count($cid) < 1) {
                JError::raiseError(500, JText::_('SELECT_DELETE'));
            }
            $model = $this->getModel('marketplace');
            $msg = $model->deleteseller($cid);
            $cache = JFactory::getCache('com_marketplace');
            $cache->clean();
            $this->setRedirect(
                'index.php?option=com_marketplace&view=marketplace',
                $msg
            );
        }
        /**
         * This is mailtoseller function
         *
         * @return void
         */
        public function mailtoseller()
        {
            $jinput=JFactory::getApplication()->input;
            $cid = $jinput->getVar('cid', array(0), 'post', 'array');
            $model = $this->getModel('marketplace');
            $emails=$model->getEmail($cid);
            $jinput->set('view', 'marketplace');
            $jinput->set('layout', 'sendmail');
            $this->setRedirect(
                'index.php?option=com_marketplace&view=marketplac'.
                'e&wk_set=webkul&emails='.urlencode(serialize($emails))
            );
        }
        /**
         * This is cancel function
         *
         * @return void
         */
        public function cancel()
        {
            $_input = JFactory::getApplication()->input;
            $cid =$_input->get('seller_id', 0, 'INT');
            $this->setRedirect(
                'index.php?option=com_marketplace&view=market'.
                'place&layout=edit_seller&seller_id="'
                .$cid.'"'
            );
        }
        /**
         * This is cancel function
         *
         * @return void
         */
        public function cancel1()
        {
            $this->setRedirect('index.php?option=com_marketplace&view=marketplace');
        }
        /**
         * This is sellerinfo function
         *
         * @return void
         */
        public function sellerinfo()
        {
            $input=JFactory::getApplication()->input;
            $seller_id=$input->get('seller_id');
            $model=$this->getModel('marketplace');
            $info=$model->getSellerInfo($seller_id);
            $view = $this->getView('marketplace', 'html');
            $view->setLayout('edit_seller');
            $view->assignRef('data_list', $info); 
            $this->setRedirect(
                'index.php?option=com_marketplace&view=marketpl'.
                'ace&layout=edit_seller',
                $info
            );
        }
        /**
         * This is sendmail function
         *
         * @return void
         */
        public function sendmail()
        {
            $jinput=JFactory::getApplication()->input;
            $postvar = $jinput->get('jform', array(), 'array');
            
            $body=$postvar['description'];
            $subject=$postvar['subject'];
            $email=$postvar['reciepient'];
            $emails=explode(',', $email);
            $body.="<p> </p>";
            foreach ($emails as $mail) {
                $mailer=JFactory::getMailer();
                $mainframe = JFactory::getApplication();
                $adminadd=$mainframe->getCfg('mailfrom');
                $mailer->setSender($adminadd);
                $mailer->addRecipient($mail);
                $mailer->setSubject($subject);
                $mailer->setBody($body);
                $mailer->isHTML(true);
                $mailer->send();
            }
            JFactory::getDocument()->addScriptDeclaration(
                "window.parent.location.href='index.php?option=com_m".
                "arketplace&view=marketplace&wk_redirect=1'; "
            );
        }
        /**
         * Editseller function
         *
         * @return void
         */
        public function editseller()
        {
            $input=JFactory::getApplication()->input;
            $seller_id=$input->getInt('seller_id', 0);
            $this->setRedirect(
                'index.php?option=com_marketplace&view=marketplace&l'.
                'ayout=edit_seller_form&seller_id='.$seller_id
            );
        }
        /**
         * GetCountryState function
         *
         * @return void
         */
        function getCountryState()
        {
            $db = JFactory::getDBO();
            $app = JFactory::getApplication();
            $_input = $app->input;
            $id = $_input->getInt('ID', 0);
            $query=$db->getQuery(true);
            $query->select($db->quoteName('virtuemart_state_id'))
                ->select($db->quoteName('state_name'))
                ->select($db->quoteName('virtuemart_country_id'))
                ->from($db->quoteName('#__virtuemart_states'))
                ->where($db->quoteName('virtuemart_country_id')."=".$db->quote($id));
            $db->setQuery($query);
            try{
                $state_details=$db->loadObjectList();
            }catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
                return false;
            }
            foreach ($state_details as $state) {
                $selectedstate='';
                if ($state->virtuemart_state_id) {
                    $selectedstate='selected';
                }

                echo '<option class="country'.$state->virtuemart_country_id.
                '" value="'.$state->virtuemart_state_id.'" >'.$state->state_name
                .'</option>';
            }
            JFactory::getApplication()->close();
        }
    }
}
