<?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');
/**
 * MarketplaceControllerCommisions 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 MarketplaceControllerCommisions extends JControllerAdmin
{
    /**
     * __construct function
     */
    function __construct()
    {
        parent::__construct();
    }

    /**
     * Updatecomm function
     *
     * @return void
     */
    function updatecomm()
    {
        $jinput=JFactory::getApplication()->input;
        $cid  = $jinput->get('cid', array(0), 'post', 'array');
        
        $this->setRedirect(
            'index.php?option=com_marketplace&view=commisions&wk_set=1&ids='
            .urlencode(serialize($cid))
        );
    }
    /**
     * UpdateCommision function
     *
     * @return void
     */
    function updateCommision()
    {
        $jinput=JFactory::getApplication()->input;
        
        $value=$jinput->get('jform', 'post', 'array');
        if ($value['commision_ids']) {

        }
        $cid = $value['commision_ids'];
        $modal=$this->getModel('commisions');
        $ids=$jinput->get('commision_id');
        $val=$value['upcommision'];
        $type=$value['commisiontype'];
        
        if (!strlen($cid)) {
            $cid=$ids;
        }
        if (is_numeric($val)) {
            if ($modal->updateCommision($cid, $val, $type)) {
                JFactory::getDocument()->addScriptDeclaration(
                    "window.parent.location.href='index.php?option=com_m".
                    "arketplace&view=commisions&wk_redirect=1&pass=1';"
                );
            }
        } else {
            JFactory::getDocument()->addScriptDeclaration(
                "window.parent.location.href='index.php?option=com_ma".
                "rketplace&view=commisions&pass=1';"
            );
            
        }
    }
    /**
     * Payments function
     *
     * @return void
     */
    function payments()
    {
        $db=JFactory::getDBO();
        $jinput=JFactory::getApplication()->input;
        $cid  = $jinput->get('cid', array(0), 'post', 'array');
        $seller_id=$cid[0];
        $commision_query=$db->getQuery(true);
        $commision_query->select('*')
            ->from($db->quoteName('#__marketplace_commision'))
            ->where($db->quoteName('seller_id'). ' = ' .$db->quote($seller_id));
        $db->setQuery($commision_query);
        try{
            $commision_fetch = $db->loadObjectList();
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(),
                'error'
            );
            return false;
        }
        $amount_recieved = $commision_fetch[0]->amount_recieved
            +$commision_fetch[0]->amount_remain;
        $amount_paid = $commision_fetch[0]->amount_remain;

        $object = new stdClass();
        $object->amount_remain = 0;
        $object->amount_recieved = $amount_recieved;
        $object->amount_paid = $amount_paid;
        $object->seller_id = $seller_id;
        
        try{
            $result = $db->updateObject(
                '#__marketplace_commision',
                $object,
                'seller_id'
            );
        }catch(Exception $e){
            JFactory::getApplication()->enqueueMessage(
                $e->getMessage(),
                'error'
            );
            return false;
        }
        $msg= JText::_('SUCCESSFUL_PAYMENT');
        $this->setRedirect(
            'index.php?option=com_marketplace&view=commisions',
            $msg
        );
    }
    /**
     * Remitapay function
     *
     * @return void
     */
    function remitapay()
    {
        $app=JFactory::getApplication();
        $seller_id=$app->input->get('sellerid');
        $amount_to_pay=$app->input->get('seller_amount');
        $payer_name=$app->input->get('payer_name');
        $payer_email=$app->input->get('payer_email');
        $payer_phone=$app->input->get('payer_phone');
        $commisionsModel=$this->getModel('commisions');
        $seller_commission_info=$commisionsModel->getSellerCommisionInfo($seller_id);
        if ($seller_commission_info->amount_remain<0
            || $seller_commission_info->amount_remain<$amount_to_pay
        ) {
            $app->redirect(
                'index.php?option=com_marketplace&view=commisions',
                JText::_('SELLER_COMMISION_INSUFFICIENT_AMOUNT'),
                'error'
            );
            $app->close();
        }
        if (!$seller_commission_info) {
            $app->redirect(
                'index.php?option=com_marketplace&view=commisions',
                JText::_('SELLER_COMMISION_INFO_ERROR'),
                'error'
            );
            $app->close();
        }
        $seller_remita_info= $commisionsModel->getRemitaDetails($seller_id);
        if (!$seller_remita_info) {
            $app->redirect(
                'index.php?option=com_marketplace&view=commisions',
                JText::_('SELLER_INFO_ERROR'),
                'error'
            );
            $app->close();
        }
        $remita_params=$commisionsModel->getRemitaParams();
        $order_id='seller_'.$seller_remita_info->sellerid."_".DATE("dmyHis");
        $response_url=JURI::root().
            'administrator/index.php?option=com_marketplace&view=commisions&layout=success&amount='.
            $amount_to_pay.'&seller_id='.$seller_commission_info->seller_id.'&pay_mode=remitasplit';
        
        if ($remita_params) {
            $remita_mode=$remita_params['remita_payment_type'];
            if ($remita_mode) {
                $mer_id=$remita_params['remita_live_merchant_id'];
                $ser_id=$remita_params['remita_live_servicetype_id'];
                $api_key=$remita_params['remita_live_api_key'];
                $payer_account=$remita_params['remita_live_account'];
                $payer_bank_code=$remita_params['remita_live_bank_code'];
                $remita_url = 'https://login.remita.net/remita/ecomm/v2/init.reg';
                $remita_final_url= "https://login.remita.net/remita/ecomm/finalize.reg";
            } else {
                $mer_id=$remita_params['remita_test_merchant_id'];
                $ser_id=$remita_params['remita_test_servicetype_id'];
                $api_key=$remita_params['remita_test_api_key'];
                $payer_account=$remita_params['remita_test_account'];
                $payer_bank_code=$remita_params['remita_test_bank_code'];
                $remita_url= 'http://www.remitademo.net/remita/ecomm/v2/init.reg';
                $remita_final_url= "http://www.remitademo.net/remita/ecomm/finalize.reg";
            }
            $hash_string = $mer_id.$ser_id.$order_id.
            $amount_to_pay.$response_url.$api_key;
            $final_hash = hash('sha512', $hash_string); 
            $content='{"merchantId":"'.$mer_id.'", 
                "serviceTypeId":"'.$ser_id.'",  
                "totalAmount":"'.$amount_to_pay.'",
                "hash":"'.$final_hash.'",
                "orderId":"'.$order_id.'",
                "responseurl":"'.$response_url.'",
                "payerName":"'.$payer_name.'",
                "payerEmail":"'.$payer_email.'", 
                "payerPhone":"'.$payer_phone.'",
                "lineItems":[{"lineItemsId":"'.$order_id.
                '","beneficiaryName":"'.$seller_remita_info->name.
                '","beneficiaryAccount":"'.$seller_remita_info->account.
                '","bankCode":"'.$seller_remita_info->bankcode.
                '","beneficiaryAmount":"'.$amount_to_pay.
                '","deductFeeFrom":"1"}]
            }'; 

            $curl = curl_init($remita_url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt(
                $curl,
                CURLOPT_HTTPHEADER,
                array("Content-type: application/json")
            );
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
            $json_response = curl_exec($curl);
            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);
            $jsonData = substr($json_response, 6, -1);
            $response = json_decode($jsonData, true);
            $statuscode = $response['statuscode'];
            $statusMsg = $response['status']; 
            if ($statuscode=='025') {
                $rrr = trim($response['RRR']);
                $new_hash_string = $mer_id.$rrr.$api_key;
                $new_hash = hash('sha512', $new_hash_string);
                $html = "";
                $html .= JText::_('CONNECTING_SERVER')."<br /><br />";
                $html .= '<form method="post" action="'.$remita_final_url.'" name="vm_remita_form">' ;
                $html .= '<input id="merchantId" name="merchantId" value="'.$mer_id.'" type="hidden"/>
                    <input id="rrr" name="rrr" value="'.$rrr.'" type="hidden"/>
                    <input id="responseurl" name="responseurl" value="'.$response_url.'" type="hidden"/>
                    <input id="hash" name="hash" value="'.$new_hash.'" type="hidden"/>';
                $html .= '<input style="display:none" type="submit" name="remitasubmit" value="remita_submit"><br><br>';
                $html .= '</form>';
                $html .= '<script type="text/javascript">';
                   $html .= 'document.vm_remita_form.submit();';
                   $html .= '</script>';
                   $url=JUri::root().'administrator/index.php?option=com_marketplace&view=commisions';
                   echo $html;
                   JFactory::getApplication()->close();        
            } else {
                $html="<b>".JText::_('SOMETHING_WRONG')."-".$statuscode."-".$statusMsg."</b>";
                $url=JUri::root().'administrator/index.php?option=com_marketplace&view=commisions';
                $html .="<div><a class='btn btn-primary' href=$url>".JText::_('RETURN_BACK')."</a></div>";
                echo $html;
                JFactory::getApplication()->close();
            }
        }
    }
}
