<?php
/**
 * Marketplace - Component Marketplace 
 * ******************************************************************
 *
 * PHP version 7.0
 *
 * @category   Component
 * @package    Joomla
 * @author     WebKul software private limited <support@webkul.com>
 * @copyright  2010 WebKul software private limited
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @version    GIT:5.2
 * @filesource http://store.webkul.com
 * @link       Technical Support:  webkul.uvdesk.com
 * ******************************************************************
 */
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
if (!class_exists('VmConfig')) {
    include JPATH_ADMINISTRATOR.
    '/components/com_virtuemart/helpers/config.php';
}
VmConfig::loadConfig();
if (!class_exists('MarketplaceModelAddproduct')) {
    /**
     * Marketplace Model Addproduct 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 MarketplaceModelAddproduct extends JModelForm
    {
        var $_data = null;
        /**
         * __construct function
         */
        function __construct()
        {
            parent::__construct();
        }
        /**
         * _buildQuery function
         *
         * @return void
         */
        function _buildQuery()
        {
            $db = JFactory::getDBO();
            $app = JFactory::getApplication();
            $_input = $app->input;
            $productid = $_input->get('virtuemart_product_id', 0, "INT");
            $user = JFactory::getUser();
            $userid = $user->get('id');
            $defaultcountry_code=VmConfig::$vmlang;

            $query=$db->getQuery(true);
            $query->select('p.*')
                ->select($db->quoteName('vp.product_s_desc'))
                ->select($db->quoteName('vp.product_desc'))
                ->select($db->quoteName('vp.product_name'))
                ->select($db->quoteName('pp.product_price'))
                ->select($db->quoteName('pp.product_tax_id'))
                ->select($db->quoteName('pp.product_discount_id'))
                ->from($db->quoteName('#__virtuemart_products', 'p'))
                ->join(
                    "LEFT",
                    $db->quoteName(
                        '#__virtuemart_products_'.$defaultcountry_code,
                        'vp'
                    )." ON ".$db->quoteName('vp.virtuemart_product_id')."=".
                    $db->quoteName('p.virtuemart_product_id')
                )
                ->join(
                    "LEFT",
                    $db->quoteName(
                        '#__virtuemart_product_prices',
                        'pp'
                    )." ON ".$db->quoteName('p.virtuemart_product_id')."=".
                    $db->quoteName('pp.virtuemart_product_id')
                )
                ->where($db->quoteName('p.created_by')."=".$db->quote($userid))
                ->where(
                    $db->quoteName('vp.virtuemart_product_id').
                    "=".$db->quote($productid)
                );
            return $query;
        }
        /**
         * Get Form function
         *
         * @param array   $data     var
         * @param boolean $loadData var
         * 
         * @return void
         */
        public function getForm($data = array(), $loadData = true)
        {
            $form = $this->loadForm(
                'com_marketplace.addproduct',
                'marketplace_captcha',
                array('control' => 'jform', 'load_data' => $loadData)
            );
            if (empty($form)) {
                return false;
            }
            return $form;
        }
        /**
         * Get Product Detail function
         *
         * @param [INT] $virtuemart_product_id var
         * 
         * @return void
         */
        function getProductDetail($virtuemart_product_id)
        {
            $db = $this->_db;
            $user = JFactory::getUser();
            $userid = $user->get('id');
            $defaultcountry_code=VmConfig::$vmlang;
            $query=$db->getQuery(true);
            $query->select(
                'p.*',
                $db->quoteName('vp.product_s_desc'),
                $db->quoteName('vp.product_desc'),
                $db->quoteName('vp.product_name'),
                $db->quoteName('pp.product_price'),
                $db->quoteName('pp.product_tax_id'),
                $db->quoteName('pp.product_discount_id')
            )
                ->from($db->quoteName('#__virtuemart_products', 'p'))
                ->join(
                    "LEFT",
                    $db->quoteName(
                        '#__virtuemart_products_'.$defaultcountry_code,
                        'vp'
                    )." ON ".$db->quoteName('vp.virtuemart_product_id')."=".
                    $db->quoteName('p.virtuemart_product_id')
                )
                ->join(
                    "LEFT",
                    $db->quoteName(
                        '#__virtuemart_product_prices',
                        'pp'
                    )." ON ".$db->quoteName('p.virtuemart_product_id')."=".
                    $db->quoteName('pp.virtuemart_product_id')
                )
                ->where(
                    $db->quoteName('vp.virtuemart_product_id')."=".
                    $db->quote($virtuemart_product_id)
                );
            try {
                $db->setQuery($query);
                return $db->loadObjectlist();
            } catch(Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Check Seller Product function
         *
         * @param integer $VirtuemartProductId var
         * 
         * @return void
         */
        public function checkSellerProduct($VirtuemartProductId=0)
        {
            $db = $this->_db;
            $query=$db->getQuery(true);
            $query->select($db->quoteName('created_by'));
            $query->from($db->quoteName('#__virtuemart_products'));
            $query->where(
                $db->quoteName('virtuemart_product_id')."=".
                $db->quote($VirtuemartProductId)
            );
            $db->setQuery($query);
            try{
                return $db->loadResult();
            } catch(Exception $e) {
                JFactory::getApplication()->enqueueMessage($e->getMessage());
            }
        }
        /**
         * Is Seller function
         *
         * @param [int] $id var
         * 
         * @return boolean
         */
        public function isSeller($id)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->select($db->quoteName('is_seller'))
                    ->from($db->quoteName('#__marketplace_sellerprofile'))
                    ->where($db->quoteName('seller_id')."=".$db->quote($id));
                $db->setQuery($query);
                return $db->loadResult();
            } catch (Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Category Request function
         *
         * @param [Str] $catname      Category Name
         * @param [Str] $catdesc      Category Description
         * @param [Str] $catinfo      Category Information
         * @param [Str] $seller_email Seller Email Id
         * @param [Str] $recipient    Email id of receiver
         * 
         * @return void
         */
        public function categoryRequest(
            $catname,
            $catdesc,
            $catinfo,
            $seller_email,
            $recipient
        ) {
            try{
                $db=$this->_db;
                $config = JFactory::getConfig();  
                $site_offset = $config->get('offset');
                $jdate=JFactory::getDate('now', $site_offset);

                $query=$db->getQuery(true);
                $query->select('id')
                    ->from($db->quoteName('#__marketplace_category_request'))
                    ->where(
                        $db->quoteName('category_name')."=".
                        $db->quote($catname)
                    );
                $db->setQuery($query);

                try{
                    $db->execute();
                    $result=$db->getNumRows();

                }
                catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
                }

                if (!class_exists('VmConfig')) {
                    include JPATH_ADMINISTRATOR.
                    '/components/com_virtuemart/helpers/config.php';
                }
                $vmconf=VmConfig::loadConfig();

                $query=$db->getQuery(true);
                $query->select('virtuemart_category_id')
                    ->from(
                        $db->quoteName(
                            '#__virtuemart_categories_'.
                            $vmconf->get("vmlang")
                        )
                    )
                    ->where(
                        $db->quoteName('category_name')."=".$db->quote($catname)
                    );
                $db->setQuery($query);
                try{
                    $db->execute();
                    $resVm=$db->getNumRows();
                }
                catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
                }
                if ($result==0 && $resVm==0) {
                    $query=$db->getQuery(true);
                    $columns = array(
                        $db->quoteName('category_name'),
                        $db->quoteName('category_desc'),
                        $db->quoteName('requested_by'),
                        $db->quoteName('requested_date'),
                        $db->quoteName('additional_info')
                    );
                    $value = array(
                        $db->quote($catname),
                        $db->quote($catdesc),
                        $db->quote($seller_email),
                        $db->quote($jdate->format('Y-m-d H:i:s', true)),
                        $db->quote($catinfo)
                    );
                    $query->insert($db->quoteName('#__marketplace_category_request'))
                        ->columns($columns)
                        ->values(implode(',', $value));
                    $db->setQuery($query);
                    try{
                        return $db->execute();
                    }
                    catch(Exception $e){
                        JFactory::getApplication()->enqueueMessage(
                            $e->getMessage(),
                            'error'
                        );
                    }
                } elseif ($result!=0) {
                    return 0;
                } else {
                    return -2;
                }
            }catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
            }
        }
        /**
         * Check Update Lang Table function
         *
         * @param [str] $country_table_name    var
         * @param [int] $virtuemart_product_id var
         * @param [str] $defaultcountry_code   var
         * 
         * @return void
         */
        public function checkUpdateLangTable(
            $country_table_name,
            $virtuemart_product_id,
            $defaultcountry_code
        ) {
            try{
                $db=$this->_db;
                if ($country_table_name == "") {
                    $country_table_name = $defaultcountry_code;
                }
                $query=$db->getQuery(true);
                $query->select($db->quoteName('product_s_desc'))
                    ->select($db->quoteName('product_desc'))
                    ->select($db->quoteName('product_name'))
                    ->from(
                        $db->quoteName(
                            '#__virtuemart_products_'.
                            $country_table_name
                        )
                    )
                    ->where(
                        $db->quoteName('virtuemart_product_id').
                        "=".$db->quote($virtuemart_product_id)
                    );
                $db->setQuery($query);
                return $result = $db->loadObjectlist();
            } catch(Exception $e) {
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Select Product function
         *
         * @param [str] $keyword var
         * 
         * @return void
         */
        public function selectProduct($keyword)
        {
            $db=$this->_db;
            $query=$db->getQuery(true);
            $query->select(
                $db->quoteName("a.virtuemart_product_id").
                ",".$db->quoteName("a.product_name")
            )
                ->from(
                    $db->quoteName(
                        '#__virtuemart_products_'.
                        VmConfig::$vmlang, "a"
                    )
                )
                ->join(
                    "INNER",
                    $db->quoteName('#__virtuemart_products', 'vp').
                    " ON ".$db->quoteName('vp.virtuemart_product_id')."=".
                    $db->quoteName('a.virtuemart_product_id')
                )
                ->where(
                    $db->quoteName('a.product_name')." LIKE ".
                    $db->quote($keyword."%")
                )
                ->where($db->quoteName('vp.published')."= 1")
                ->order($db->quoteName('virtuemart_product_id'));
            $db->setQuery($query);
            try{
                return $db->loadObjectList();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
                return false;
            }
        }
        /**
         * Delete Image function
         *
         * @param [int] $virtuemart_media_id var
         * 
         * @return void
         */
        public function deleteimage($virtuemart_media_id)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->delete($db->quoteName('#__virtuemart_medias'))
                    ->where(
                        $db->quoteName('virtuemart_media_id').
                        "=".$db->quote($virtuemart_media_id)
                    );
                $db->setQuery($query);
                try{
                    $db->execute();
                }
                catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
                }

                $query=$db->getQuery(true);
                $query->delete($db->quoteName('#__virtuemart_product_medias'))
                    ->where(
                        $db->quoteName('virtuemart_media_id')."=".
                        $db->quote($virtuemart_media_id)
                    );
                $db->setQuery($query);
                try{
                    return $db->execute();
                }
                catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
                    return false;
                }
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Get Category Of Edit Product function
         *
         * @param [int] $virtuemart_product_id var
         * 
         * @return void
         */
        function getCategoryOfEditProduct($virtuemart_product_id)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->select($db->quoteName('virtuemart_category_id'))
                    ->from($db->quoteName('#__virtuemart_product_categories'))
                    ->where(
                        $db->quoteName('virtuemart_product_id').
                        "=".$db->quote($virtuemart_product_id)
                    );
                $db->setQuery($query);
                return $db->loadObjectList();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Get Product Categories function
         *
         * @param [int] $pid var
         * 
         * @return void
         */
        function getProductCategories($pid)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->select($db->quoteName('virtuemart_category_id'))
                    ->from($db->quoteName('#__virtuemart_product_categories'))
                    ->where(
                        $db->quoteName('virtuemart_product_id')."=".
                        $db->quote($pid)
                    );
                $db->setQuery($query);
                return $db->loadObjectList();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Get Data function
         *
         * @return void
         */
        function getData()
        {
            // Lets load the data if it doesn't already exist
            if (empty($this->_data)) {
                try{
                    $query = $this->_buildQuery();
                    return $this->_getList($query);
                }
                catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
                    return false;
                }
            }

        }
        /**
         * Get Discount Calculation Name function
         *
         * @param [int] $calc_id var
         * 
         * @return void
         */
        function getDiscountCalculationName($calc_id)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->select($db->quoteName('c.calc_name'))
                    ->from($db->quoteName('#__virtuemart_calcs', 'c'))
                    ->where(
                        $db->quoteName('c.virtuemart_calc_id')."=".
                        $db->quote($calc_id)
                    );
                $db->setQuery($query);
                return $db->loadResult();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Get Tax Calculation Name function
         *
         * @param [int] $calc_id var
         * 
         * @return void
         */
        function getTaxCalculationName($calc_id)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->select($db->quoteName('c.calc_name'))
                    ->from($db->quoteName('#__virtuemart_calcs', 'c'))
                    ->where(
                        $db->quoteName('c.virtuemart_calc_id')."=".
                        $db->quote($calc_id)
                    );
                $db->setQuery($query);
                return $db->loadResult();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Get Country Name function
         *
         * @param [type] $countrytag var
         * 
         * @return void
         */
        public function getCountryName($countrytag)
        {
            try{
                $db=$this->_db;
                $query=$db->getQuery(true);
                $query->select($db->quoteName('country_name'))
                    ->from($db->quoteName('#__virtuemart_countries'))
                    ->where(
                        $db->quoteName('country_2_code')."="
                        .$db->quote($countrytag)
                    );
                $db->setQuery($query);
                return $db->loadResult();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
        }
        /**
         * Get Image Path function
         *
         * @return void
         */
        public function getImagePath()
        {
            $db = JFactory::getDBO();
            $app = JFactory::getApplication()->input;
            $productid = $app->get('virtuemart_product_id', 0, 'INT');
            $query = $db->getQuery(true);
            $query->select($db->quoteName("virtuemart_media_id"))
                ->from($db->quoteName("#__virtuemart_product_medias"))
                ->where($db->quoteName("virtuemart_product_id")."=".$productid);
            $db->setQuery($query);
            
            try{
                $result = $db->loadColumn();
            }
            catch(Exception $e){
                JFactory::getApplication()->enqueueMessage(
                    $e->getMessage(),
                    'error'
                );
            }
            if ($result) {
                $imagesids = implode(',', $result);
                $query2 = $db->getQuery(true);
                $query2->select(
                    $db->quoteName(
                        array(
                            "virtuemart_media_id",
                            "file_url"
                        )
                    )
                )
                    ->from($db->quoteName("#__virtuemart_medias"))
                    ->where(
                        $db->quoteName("virtuemart_media_id")
                        ."in (".$imagesids.")"
                    );
                $db->setQuery($query2);
                try{
                    $images = $db->loadObjectList();
                }
                catch(Exception $e){
                    JFactory::getApplication()->enqueueMessage(
                        $e->getMessage(),
                        'error'
                    );
                    return false;
                }
                return $images;
            } else {
                return false;
            }
        }
    }
}
