<?php

class FundsController extends Controller {

    public $layout = 'column2';

    public function accessRules() {
        return array(
            array('allow', // allow trader user to perform actions
                'actions' => array('depositBonus', 'internalTransfer', 'basicInformation', 'transferBankDetails', 'deposit', 'withdrawal', 'altDeposit', 'hmDeposit', 'paymentCards'),
                'roles' => array('user6', 'user4'),
            ),
            array('deny', // deny all users
                'actions' => array('depositBonus', 'internalTransfer', 'basicInformation', 'transferBankDetails', 'deposit', 'withdrawal', 'altDeposit', 'hmDeposit', 'paymentCards'),
                'users' => array('*'),
            ),
        );
    }

    public function init() {
        if(Yii::app()->params['styles_type'] == 'new'){
            $this->layout = 'sidebar';
        }
    }

    public function actionBasicInformation() {

        $this->pageTitle = Yii::t("funds", "47_fund_services");
        $this->breadcrumbs = array(
            Yii::t("funds", "47_fund_services"));

        $registr = new Registration;
        $status = $registr->IsApprove();

        $account = new Account();
        $Info = $account->GetInfo();

        $isView = false;
        if ((($status == 3 || $status == 1) AND $Info->Type == '4') || $Info->Type == '6'){ // 'is ib not aprove' 
            $isView = true;
        }else{
            $_SESSION['message'][] = array("text" => Yii::t("main", "170_this_page_will_be_available_once_your_ib_partnersh"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
        }

        if($Info->Type == '6'){
            $Account=new Account();
            $model_live_account=$Account->GetAccount(array('live'));
            $allow = (count((array)$model_live_account) > 0) ? true : false;
        }else{
            $allow = true;
        }

        $this->render('basicInformation', array('isView' => $isView, 'allow' => $allow, 'info'=>$Info));
    }

    public function actionTransferBankDetails(){
        $this->pageTitle = Yii::t("funds", "50_bank_details");
        $this->breadcrumbs = array(
            Yii::t("funds", "47_fund_services") => array('/funds/basicInformation/'),
            Yii::t("funds", "50_bank_details"));

        $Funds = new FundServices('Fund');
        $adressWD = $Funds->GetAddressForWithdrawal();

        $registration = $registration = new Registration();
        $registration->initIndv();
        $reference = $registration->firstName.' '.$registration->lastName.', '.$_GET['account'];

        if (Yii::app()->request->isAjaxRequest){
            $staticBank = $Funds->getBankInfo($_POST['bankno'], $_POST['currency']);
            $staticBank->reference = $reference;
            $mail = new YiiMailer();
            $mail->setView('bankInfoSend');
            $mail->setData(array('name' => $staticBank->name, 'address' => $staticBank->address, 'swift' => $staticBank->swift, 'beneficiary' => $staticBank->beneficiary, 'iban' => $staticBank->iban, 'reference' => $staticBank->reference, 'amount' => $_GET['amount'], 'currency' => $_GET['currency']));
            $mail->setLayout('base');
            $mail->setFrom(Yii::app()->params['adminEmail'], Yii::app()->params['name_company']);
            $mail->setTo($_POST['mail']);
            $mail->setSubject(Yii::app()->params['name_company'].' - '.Yii::t("main","606_bank_account_details"));
            echo $mail->send();

            Yii::app()->end();
        }

        if (isset($_GET['bankno'])) {
            $staticBank = $Funds->getBankInfo(urldecode($_GET['bankno']), $_GET['currency']);
            $staticBank->reference = $reference;
        } else {
            $_SESSION['message'][] = array("text" => Yii::t("funds", "449_bank_data_transmission_error"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        }
        $this->render('transferBankDetails', array('Funds' => $Funds, 'staticBank' => $staticBank, 'adressWD' => $adressWD, 'amount' => $_GET['amount']));
    }

    public function actionDepositBonus() {
        $this->pageTitle = Yii::t("funds", "61_bonus_programm");
        $this->breadcrumbs = array(
            Yii::t("funds", "61_bonus_programm"));

        $Funds = new FundServices('Fund');
        $bonusSettings = $Funds->GetBonusSetting();
        $BonusName = $bonusSettings->name;
        $BonusPercent = $bonusSettings->percent;

        $Account = new Account();
        $Info = $Account->GetInfo();
        $parentCode = $Account->GetParentCode();
        $parInfo = $Account->getParentContacts();
        /* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
            var_dump($parentCode);die();
        } */

        if(($Info->Code == 596 || $Info->Code == 600 || $Info->Code == 601 || $Info->Code == 11734 || $parInfo['Code'] == 11734 || $parentCode == 601 || !wlParams::get('bonus')) && $Info->Login != '1000066729'){ die('access denied'); }

        $parrentInfo = $Account->getParentContacts();
        $model_live_account=$Account->GetAccount(array('live'));

        if (Yii::app()->request->isPostRequest) {
            $bl = (isset($_POST["bonusAgrmnt"])) ? 'true' : 'false';
            $Funds->ChangeUserAgreeBonusState($bl);

            /*  $how = ($Info->Type == '6')?'Trader':'IB';
             $agree = $bl=='true'?'has agreed':'has NOT agreed';
             mail(Yii::app()->params['operEmail'], 'BMFN Bonus', $how.'# '.$Info->ID.' '.$agree.' to Bonus Terms and Conditions in Private Cabinet.'); */

            /* $mail = new YiiMailer();
            $mail->setView('bonusActivation');

            $how = ($Info->Type == '6')?'Trader':'IB';
            $agree = $bl=='true'?'has agreed':'has NOT agreed';
            $mail->setData(array('userType' => $how, 'bonusState' => $agree, 'id' => $Info->ID));
            $mail->setLayout('base');
            $mail->setFrom(Yii::app()->params['adminEmail'], Yii::app()->params['name_company']);
            $mail->setTo(array(Yii::app()->params['operEmail']));
            $mail->setSubject('Bonus Program State Change');
            $rez = $mail->send(); */
        }

        if($Info->Type == '6'){ //trader
            $allow = (count((array)$model_live_account) > 0) ? true : false;
        }else{  //IB
            $allow = true;
        }

        $Registr = new Registration();
        $Registr->initIndv();

        $docid=0;
        $rez=$Account->GetDocumentsID();
        if(isset($rez)&& $rez>0){$docid=$rez;}


        if(Yii::app()->params['type'] == 'swissfs'){
            $url= wlParams::get('docsFolderServer')."/swissfs/".Yii::app()->language."/BonusTerms.pdf";
        }elseif(Yii::app()->params['type'] == 'SwissSA'){
            $url= wlParams::get('docsFolderServer')."/44/".Yii::app()->language."/BonusTerms.pdf";
        }else{
            $url= wlParams::get('docsFolderServer')."/".$docid."/".Yii::app()->language."/BonusTerms.pdf";
        }

        /*if(Yii::app()->params['type'] = 'swissfs'){
            $url= wlParams::get('docsFolderServer')."/ib6/".Yii::app()->language."/BonusTerms.pdf";
        }else{
            $url= wlParams::get('docsFolderServer')."/".$docid."/".Yii::app()->language."/BonusTerms.pdf";
        }*/

        /*$Headers = @get_headers($url);
        if(substr_count($Headers[0], '200')>0) { $BonusFile=$url;} else { $BonusFile= wlParams::get('docsFolderServer')."/".$docid."/en/BonusTerms.pdf";}*/


        $BonusFile=$url;

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump($url, $BonusFile);die();
        }*/

        $this->render('depositBonus', array('Funds' => $Funds, 'traderAccounts' => $Account->GetAccount(), 'agreeBonus' => $Registr->agreeBonus, 'BonusName'=>$BonusName, 'BonusPercent'=>$BonusPercent, 'allow'=>$allow, 'BonusFile'=>$BonusFile, 'parrentInfo'=>$parrentInfo));
    }

    public function actionDeposit(){

        if(in_array(wlParams::get('officeCode'), [60,65,69,70])){
            $Document = new Document();
            $signs = $Document->isExist('payment_policy');
            if(empty($signs)){
                $this->redirect('/paymentPolicy');
            }
        }

        if(Yii::app()->params['type'] == 'ftt'){
            $this->redirect(Yii::app()->params['deposit_link'].'/login.html?guid='.Yii::app()->user->id);
            //echo Yii::app()->params['deposit_link'].'/login.html?guid='.Yii::app()->user->id;
        }

        $this->pageTitle = Yii::t("funds", "48_fund_deposits");

        //$_SESSION['message'][] = array("text" => Yii::t("funds", "619_8000_dinpay_max"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");

        $Funds = new FundServices('Fund');
        $demoValues = $Funds->GetDemoDepositValues();
        //var_dump(uniqid());die();

        $BanksInfo = $Funds->getBanksInfo();

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($BanksInfo);die();
        }*/

        


        //$bonusSettings = $Funds->GetBonusSetting();
        //$BonusPercent = $bonusSettings->percent;
        $AvaliablesBanks = $Funds->getAvaliablesBanksForUser();

        if(wlParams::get('webmoney_allow')){
            if(wlParams::get('webmoney_acc') == ''){
                $WebMobeyAcc = $Funds->GetSetting('WebMoneyKey');
            }else{
                $WebMobeyAcc = wlParams::get('webmoney_acc');
            }
        }else{
            $WebMobeyAcc = '';
        }



        $Account = new Account();
        $getInfo = $Account->GetInfo();
        $traderAccounts = $Account->GetAccount();
        $traderLiveAccounts = $Account->GetAccount(array('live'));
        $officeShortCode=$Account->GetUserOfficeShortCode();
        if ($officeShortCode == 'BJI') {die();}

        $Registration = new Registration('Individual');
        $Registration->initIndv();

        if($getInfo->Type == 6 && $getInfo->GroupType == 2){
            $Registration2 = new RegistrationTrader('Corporate');
            $Registration2->initTrader();
            $isFullProfile = $Registration2->isFull();
        }else{
            $isFullProfile = $Registration->isFull();
        }

        $approve = $Registration->IsApprove();
        $countries = $Registration->GetCountry();
        //$agreeBonus = $Registration->agreeBonus;
        $countries_code_three = $Registration->GetCountry('three');
        $countries_code_two = $Registration->GetCountry('two');

        //$isFullProfile = $Registration->isFull();

        $Bank = new RegistrationBank('Funds');
        $Bank->initBank();

        if(count($traderLiveAccounts) > 0){
            $this->breadcrumbs = array(
                Yii::t("funds","47_fund_services") => ('/funds/index.html'),
                Yii::t("funds", "48_fund_deposits"));
        }else{
            $this->breadcrumbs = array(
                Yii::t("funds", "48_fund_deposits"));
        }

        if($getInfo->Type == 6){
            if($getInfo->GroupType==1){
                $Trader = new RegistrationTrader('Individual');
            }elseif($getInfo->GroupType==3){
                $Trader = new RegistrationTrader('Join');
            }elseif($getInfo->GroupType==2){
                $Trader = new RegistrationTrader('Corporate');
            }
            $Trader->initTrader();
        }

        $CreditCard = new CreditCard();
        $cardsTable = $CreditCard->getCardsTable();
        $userCardsNum = $CreditCard->userCardsNum();
        $CreditCard->unsetAttributes();

        $Document = new Document('CreditCard');

        $gets = "";
        $post_data['type'] = 'none';
        $noPost = true;
        $cardsShow = false;

        if (Yii::app()->request->getQuery('type') == 'failed') {
            $_SESSION['message'][] = array("text" => Yii::t("main", "419_1_inatec_failed"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
        } elseif (Yii::app()->request->getQuery('type') == 'success') {
            $_SESSION['message'][] = array("text" => Yii::t("main", "419_inatec_success"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
        }


        //if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
        if(Yii::app()->request->isPostRequest && isset($_POST["FundServices"]["ipsno"]) && ($_POST["FundServices"]["ipsno"] == 'zotapay' || $_POST["FundServices"]["ipsno"] == 'lionpay' || $_POST["FundServices"]["ipsno"] == 'awepay')){
            unset($_POST['add_new_card_sbmt']);
        }
        //}


        if (Yii::app()->request->isAjaxRequest){

            if(isset($_POST["getCards"])){
                $GateToPay = new GateToPay();
                echo json_encode($GateToPay->getCards());
                die();
            }


            if(isset($_POST['recalcAmount'])){

                /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(222, Yii::app()->request->isAjaxRequest, isset($_POST['recalcAmount']));die();
        }*/

                $FundsRecalc = new FundServices('recalcAmount');
                $FundsRecalc->attributes = $_POST;

                //var_dump($FundsRecalc->validate());die();

                if($FundsRecalc->validate()){
                    $sum = $FundsRecalc->RecalculateAmount();
                    if(is_numeric($sum)){
                        echo json_encode(['status'=>'success', 'amount'=> number_format($sum, 2, '.', ' ').' USD']);
                    }
                }else{
                    echo json_encode(['status'=>'error', 'errors'=> $FundsRecalc->getErrors()]);
                }
                die();

            }elseif(isset($_POST['createTrans'])){
                $paymentsArray = array('paytab'=>'PayTab','skrill'=>'Skrill', 'dinpay'=>'dinPay', 'dinpay2'=>'dinPay', 'dcpay'=>'dcPay', 'cashu'=>'cashU', 'neo'=>'Neo', 'bfopay'=>'BfoPay', 'neteller'=>'Neteller',  'neteller2'=>'Neteller2', 'emerpay'=>'EMerchantPay', 'zotapay'=>'ZotaPay', 'ewallet'=>'eWallet', 'homepay'=>'homePay', 'sandpay'=>'sandPay', 'sovvipay'=>'sovviPay', 'lionpay'=>'lionPay', 'nganluong'=>'nganLuong', 'awepay'=>'AwePay', 'awepayshp'=>'AwePay', 'knet'=>'kNet', 'knet2'=>'kNet2', 'globepay'=>'GlobePay', 'astropay'=>'AstroPay', 'neonew'=>'NeoNew', 'network'=>'Network', 'paymob'=>'PayMob', 'totalpay'=>'TotalPay', 'ikajo'=>'Ikajo', 'accentpay'=>'accentPay', 'myfatoorah'=>'myFatoorah', 'telr'=>'Telr', 'tap'=>'Tap', 'upay'=>'Upay', 'myfatoorah_acc2'=>'myFatoorah', 'myfatoorah_acc3'=>'myFatoorah', 'myfatoorah_acc4'=>'myFatoorah', 'ccavenue'=>'CCAvenue', 'nowpay'=>'Nowpay', 'upi_icici'=>'UPIicici', 'india_cash_deposit'=>'IndiaCashDeposit', 'cryptapi'=>'Crypto', 'finobyte'=>'FinoByte', 'stripe'=>'Stripe', 'gate_to_pay'=>'GateToPay');
                $Model = new $paymentsArray[$_POST['type']];

                if($_POST['type'] == 'myfatoorah_acc2' || $_POST['type'] == 'myfatoorah_acc3' || $_POST['type'] == 'myfatoorah_acc4'){
                    $Model->credentials = $_POST['type'];
                    $Model->initCredentials();
                }


                if($_POST['type']=='gate_to_pay'){
                    $Model->setScenario('gate_to_pay_otp');
                    $Model->attributes = $_POST;

                    if($Model->validate()){
                        $res = $Model->ConfirmGTPDeposit();

                        if(isset($res->State) && $res->State == 0){
                            $_SESSION['message'][] = array("text" => Yii::t("funds", "607_funds_accepted"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                        }else{
                            $_SESSION['message'][] = array("text" => $res, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                        }
                    }else{
                        echo json_encode($Model->getErrors());
                        Yii::app()->end();
                    }
                    $createTransaction = 'blanktransaction';
                    $returnArray['innerRedirect'] = '/funds/deposit.html';
                }elseif($_POST['type']=='skrill'){
                    $exp =  explode('=', $_POST['merchant_fields']);
                    /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                        var_dump($_POST);die();
                    }*/
                    $createTransaction = $Model->newTransaction($exp[1], $_POST['amount'], $_POST['transaction_id'], $_POST['currency']);
                    $returnArray = array();
                    if((wlParams::get('officeCode') == 53)){
                        $returnArray['trySecure'] = 'trySecureOk';
                    }else{
                        $returnArray['innerRedirect'] = 'https://my.bmfnvt.com/payment/skrillRedirect';
                    }
                }elseif($_POST['type']=='knet' || $_POST['type']=='knet2'){
                    //var_dump('1111', $_POST);die();
                    $createTransaction= $Model->newTransaction($_POST['transferTo'], $_POST['amount'], $_POST['tr'], $_POST['currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='myfatoorah' || $_POST['type']=='myfatoorah_acc2' || $_POST['type']=='myfatoorah_acc3' || $_POST['type']=='myfatoorah_acc4'){
                    //var_dump('1111', $_POST);die();
                    $createTransaction= $Model->newTransaction($_POST['CustomerReference'], $_POST['InvoiceValue'], $_POST['UserDefinedField'], $_POST['DisplayCurrencyIso']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='telr'){
                    $createTransaction= $Model->newTransaction($_POST['ivp_desc'], $_POST['real_amount'], $_POST['ivp_cart'], $_POST['real_currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='paytab'){
                    // for bond
                    //        createTrans	"1"
                    //        type	"paytab"
                    //        UserDefinedField	"64dcce6f5261e"
                    //        DisplayCurrencyIso	"AED"
                    //        InvoiceValue	"51"
                    //        CustomerReference	"777407297"
                    //        link	"https://secure.paytabs.com/payment/wr/5E2F0B7682E404B0457FAE2E62432EC4B6045ECFA908318359A51361"
                    $createTransaction= $Model->newTransaction($_POST['CustomerReference'], $_POST['InvoiceValue'], $_POST['UserDefinedField'], $_POST['DisplayCurrencyIso']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='tap'){
                    $createTransaction= $Model->newTransaction($_POST['description'], $_POST['amount'], $_POST['transaction'], $_POST['currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='upay'){
                    $createTransaction= $Model->newTransaction($_POST['reference'], $_POST['total_price'], $_POST['order_id'], $_POST['CurrencyCode']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='stripe'){
                    $createTransaction = 'done';//$Model->newTransaction($_POST['reference'], $_POST['total_price'], $_POST['order_id'], $_POST['CurrencyCode']);
                    //$returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='ccavenue'){
                    //var_dump('ccavenue', 'newTransaction', $_POST);die();
                    $createTransaction= $Model->newTransaction($_POST['account'], $_POST['real_amount'], $_POST['order_id'], $_POST['real_currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='nowpay'){

                    $createTransaction = $Model->newTransaction($_POST['account'], $_POST['amount'], $_POST['order_id'], 'USD');
                    $Model->checkStatus($_POST['payment_id']);
                    $returnArray = array();
                    $returnArray['status'] = $Model->payment_status;
                    $returnArray['changeStatus'] = true;
                }elseif($_POST['type']=='globepay'){
                    //var_dump($_POST);die();
                    $createTransaction= $Model->newTransaction($_POST['item_name'], $_POST['price'], $_POST['item_id'], $_POST['currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='totalpay'){
                    $createTransaction= $Model->newTransaction($_POST['description'], $_POST['transaction_amount'], $_POST['number'], $_POST['transaction_currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='astropay'){
                    //var_dump($_POST);die();
                    //var_dump($_POST);die();
                    $createTransaction= $Model->newTransaction($_POST['account'], $_POST['amount'], $_POST['transactionID'], $_POST['currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='cashu'){
                    $createTransaction= $Model->newTransaction($_POST['transferTo'], $_POST['amount'], $_POST['token'], $_POST['currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='dinpay' || $_POST['type']=='dinpay2'){
                    $createTransaction = $Model->newTransaction((int)$_POST['product_name'], $_POST['real_amount'], $_POST['order_no'], $_POST['real_currency']);

                    $returnArray['trySecure'] = 'trySecureOk';
                    $returnArray['real_amount'] = $_POST['real_amount'];
                    $returnArray['real_currency'] = $_POST['real_currency'];
                    if($_POST['real_currency'] != 'CNY'){
                        $returnArray['order_amount'] = round(stFunctions::currConv($_POST['real_currency'], 'CNH', $_POST['real_amount']), 2);
                    }else{
                        $returnArray['order_amount'] = $_POST['real_amount'];
                    }
                    $returnArray['product_desc'] = 'CNH';

                    /* echo json_encode($returnArray);
                    Yii::app()->end(); */

                }elseif($_POST['type']=='dcpay'){
                    $createTransaction = $Model->newTransaction((int)$_POST['merchant_product_desc'], $_POST['real_amount'], $_POST['merchant_order'], $_POST['real_currency']);


                    $returnArray['trySecure'] = 'trySecureOk';
                    $returnArray['real_amount'] = $_POST['real_amount'];
                    $returnArray['real_currency'] = $_POST['real_currency'];
                    if($_POST['real_currency'] != 'CNY'){
                        $returnArray['amount'] = round(stFunctions::currConv($_POST['real_currency'], 'CNH', $_POST['real_amount']), 2)*100;
                    }else{
                        $returnArray['amount'] = (float)$_POST['real_amount']*100;
                    }
                    $returnArray['currency'] = 'CNY';

                    /* echo json_encode($returnArray);
                    Yii::app()->end(); */

                }elseif($_POST['type']=='bfopay'){
                    $createTransaction = $Model->newTransaction((int)$_POST['ProductName'], $_POST['real_amount'], $_POST['TransID'], $_POST['real_currency']);
                    //var_dump($createTransaction);die();

                    $returnArray['trySecure'] = 'trySecureOk';
                    $returnArray['real_amount'] = $_POST['real_amount'];
                    $returnArray['real_currency'] = $_POST['real_currency'];
                    if($_POST['real_currency'] != 'CNY'){
                        $returnArray['amount'] = round(stFunctions::currConv($_POST['real_currency'], 'CNH', $_POST['real_amount']), 2);
                    }else{
                        $returnArray['amount'] = (float)$_POST['real_amount'];
                    }
                    $returnArray['currency'] = 'CNY';

                    /* echo json_encode($returnArray);
                    Yii::app()->end(); */

                }elseif($_POST['type']=='neo'){
                    $createTransaction = $Model->newTransaction((int)$_POST['account'], (int)$_POST['amount'], $_POST['order'], $_POST['currency']);

                    $reqPar = explode('|', $_POST['requestParameter']);
                    $deocdeResp = $Model->decodeResponse($reqPar[1]);
                    $deocdeRespArray = explode('|', $deocdeResp);
                    if($_POST['currency'] != 'AED'){
                        $deocdeRespArray[2] = round(stFunctions::currConv($_POST['currency'], 'AED', $_POST['amount']), 2);
                    }else{
                        $deocdeRespArray[2] = (int)$_POST['amount'];
                    }
                    $reqStr = implode('|', $deocdeRespArray);
                    $encodeResp = $Model->encodeResponse($reqStr);

                    $returnArray['trySecure'] = 'trySecureOk';
                    $returnArray['requestParameter'] = $encodeResp;


                    /* echo json_encode($returnArray);
                    Yii::app()->end(); */
                }elseif($_POST['type']=='neonew'){
                    $createTransaction = $Model->newTransaction((int)$_POST['account'], (float)$_POST['real_amount'], $_POST['transactionID'], $_POST['real_currency']);

                    //$createTransaction = $Model->newTransaction((int)$_POST['account'], (int)$_POST['amount'], $_POST['transactionID'], $_POST['currency']);

                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='network'){
                    //var_dump('newTransaction', $_POST);die();
                    $createTransaction = $Model->newTransaction((int)$_POST['account'], (float)$_POST['real_amount'], $_POST['merchantOrderReference'], $_POST['real_currency']);

                    //$createTransaction = $Model->newTransaction((int)$_POST['account'], (int)$_POST['amount'], $_POST['transactionID'], $_POST['currency']);

                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='paymob'){
                    $createTransaction = $Model->newTransaction((int)$_POST['account'], (float)$_POST['transaction_amount'], $_POST['transactionId'], $_POST['transaction_currency']);

                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='neteller2'){
                    $createTransaction = $Model->newTransaction((int)$_POST['account'], (float)$_POST['amount'], $_POST['merchantRefNum'], $_POST['currency']);

                    //$createTransaction = $Model->newTransaction((int)$_POST['account'], (int)$_POST['amount'], $_POST['transactionID'], $_POST['currency']);

                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='emerpay' || $_POST['type']=='zotapay'){
                    $createTransaction = $Model->newTransaction($_POST['account'], $_POST['amount'], $_POST['transaction_id'], $_POST['currency']);

                    $returnArray['trySecure'] = 'trySecureOk';
                    $returnArray['real_amount'] = $returnArray['amount'] = $_POST['amount'];
                    $returnArray['real_currency'] = $returnArray['currency'] = $_POST['currency'];
                }elseif($_POST['type']=='ewallet'){
                    if(!isset($_POST['real_amount'])){
                        $createTransaction = $Model->newTransaction($_POST['title'], $_POST['total_fee'], $_POST['order_no'], $_POST['body']);
                    }else{
                        $createTransaction = $Model->newTransaction($_POST['title'], $_POST['real_amount'], $_POST['order_no'], $_POST['real_currency']);

                        $returnArray['real_amount'] = $_POST['real_amount'];
                        $returnArray['real_currency'] = $_POST['real_currency'];
                    }

                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='homepay'){
                    $split = explode(',', $_POST["order_title"]);
                    $createTransaction = $Model->newTransaction($split[0], $_POST['real_amount'], $_POST['order_sn'], $_POST['real_currency']);

                    //$createTransaction = 'as12v31v1v31j3j13v13';

                    $returnArray['real_amount'] = $_POST['real_amount'];
                    $returnArray['real_currency'] = $_POST['real_currency'];

                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='sandpay'){
                    $createTransaction = $Model->newTransaction((int)$_POST['subject'], $_POST['real_amount'], $_POST['orderCode'], $_POST['real_currency']);

                    $returnArray['trySecure'] = 'trySecureOk';

                    $returnArray['real_amount'] = $_POST['real_amount'];
                    $returnArray['real_currency'] = $_POST['real_currency'];

                }elseif($_POST['type']=='sovvipay'){
                    $createTransaction = $Model->newTransaction($_POST['pay_product_name'], $_POST['pay_extend1'], $_POST['pay_order_id'], $_POST['pay_extend2']);

                    $returnArray['trySecure'] = 'trySecureOk';

                    $returnArray['real_amount'] = $_POST['pay_extend1'];
                    $returnArray['real_currency'] = $_POST['pay_extend2'];
                }elseif($_POST['type']=='_accentpay'){
                    $createTransaction= $Model->newTransaction($_POST['transferTo'], $_POST['amount'], $_POST['tr'], $_POST['currency']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='accentpay'){
                    $createTransaction= $Model->newTransaction($_POST['transferTo'], $_POST['amount'], $_POST['tr'], $_POST['currency'], $_POST['cardId']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='myfatoorah' || $_POST['type']=='myfatoorah_acc2' || $_POST['type']=='myfatoorah_acc3' || $_POST['type']=='myfatoorah_acc4'){
                    $createTransaction= $Model->newTransaction($_POST['CustomerReference'], $_POST['InvoiceValue'], $_POST['CustomerCivilId'], $_POST['DisplayCurrencyIso']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='telr' ){
                    //var_dump($_POST);die();
                    $createTransaction= $Model->newTransaction($_POST['CustomerReference'], $_POST['InvoiceValue'], $_POST['CustomerCivilId'], $_POST['DisplayCurrencyIso']);
                    $returnArray = array();
                    $returnArray['trySecure'] = 'trySecureOk';

                }elseif($_POST['type']=='lionpay' || $_POST['type']=='ikajo'){
                    $returnArray = array();

                    if($_POST['type']=='lionpay'){
                        $createTransaction = $Model->newTransaction($_POST['sinm1'], $_POST['amount'], $_POST['sod'], $_POST['currency'], $_POST['cardId']);

                        $Document = new $Document();
                        $rez = $Document->send('declaration.pdf', $fileType = 'declaration', $createTransaction, $_POST['link'], 'false');

                        if(isset($rez->State) && $rez->State == 0){
                            $returnArray['trySecure'] = 'trySecureOk';
                        }
                    }else{
                        $createTransaction = $Model->newTransaction($_POST['ext2'], $_POST['ext1'], $_POST['ext4'], $_POST['ext3'], $_POST['cardId']);
                        $returnArray['trySecure'] = 'trySecureOk';
                    }


                }elseif($_POST['type']=='nganluong'){
                    $createTransaction = $Model->newTransaction($_POST['transaction_info'], $_POST['price'], $_POST['order_code'], $_POST['currency']);

                    $returnArray['trySecure'] = 'trySecureOk';
                }elseif($_POST['type']=='awepayshp'){
                    $createTransaction = $Model->newTransaction($_POST['ref1'], $_POST['item_amount_unit'][0], $_POST['wid']);
                    //$createTransaction = 'q1k31k3134j12n3j1n23n123n13';

                    $returnArray['trySecure'] = 'trySecureOk';
                }

                if(is_string($createTransaction) && !empty($createTransaction) && $createTransaction != 'ErrorOccured' && $createTransaction != 'NoAccessRights' && $createTransaction != 'AmountGreaterThanMinAllowedAmount'){
                    echo json_encode($returnArray);
                    //echo 'ok';
                }else{
                    echo 'bad';
                    Yii::log(CVarDumper::dumpAsString(array('transaction has not created')), 'error', $_POST['type']);
                }
                Yii::app()->end();
            }


            if(isset($_POST['checkCC'])){
                $FundsCc = new FundServices('ccFull');
                $FundsCc->attributes = $_POST;

                $FundsCc->ccFullNumber = (strlen($_POST["ccFullNumber"]) == 4) ? '' : $_POST["ccFullNumber"];

                if($FundsCc->ccFullNumber == ''){
                    $validateFundsCc = CActiveForm::validate($FundsCc);
                    echo $validateFundsCc;
                }else{
                    $ccFullNumber = $rest = substr(str_replace(' ', '', $FundsCc->ccFullNumber), -4);
                    if($_POST["lastDigits"] == $ccFullNumber){
                        /* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
                             var_dump($FundsCc->attributes);die();
                         }*/
                        $validateFundsCc = CActiveForm::validate($FundsCc);
                        echo $validateFundsCc;
                    }else{
                        $ccError['FundServices_ccFullNumber'] = array(Yii::t("funds","495_cc_numbers_dont_match"));
                        echo json_encode($ccError);
                    }
                }
                Yii::app()->end();
            }


            $Document->attributes = $postDocs = Yii::app()->request->getPost('Document');
            // Document model in view must be call only "$Document"  ---  IMPORTANT!!!
            $docErrors = $Document->ajaxDocValidate($postDocs, $Document);




            if(!empty($docErrors)){
                //echo $docErrors;
                //Yii::app()->end();
            }

            if ((isset($_POST["add_new_card_sbmt"]) || isset($_POST['edit_card_submit'])) && $_POST["FundServices"]["deposit_type"]=='live'){

                //var_dump($_POST);die();
                $CreditCard->attributes = Yii::app()->request->getPost('CreditCard');
                $validateFunds = json_encode(array());
                $validateCards = CActiveForm::validate($CreditCard);
                $Document = new Document('CreditCard');
                $ccPhotos = $Document->isExist('credit_card', $CreditCard->Id);

                /* $isEditDoc = false;
                if(isset($_SESSION['Document']['credit_card'])){
                    foreach($_SESSION['Document']['credit_card'] as $ccses){
                        if(strstr($ccses, $CreditCard->Id)){
                            $isEditDoc = true;
                        }
                    }
                } */
                //var_dump(count($ccPhotos), $isEditDoc);die();
                $ccFilesCount = wlParams::get('officeCode') == 6 ? 2 : 3;
                //var_dump($ccFilesCount);die();
                if(count($ccPhotos) >= $ccFilesCount){
                    $docErrors = '[]';
                }



                if(isset($_POST["add_new_card_sbmt"])){
                    //cookieDoc::isExist('credit_card') && count(cookieDoc::get('credit_card'))

                    // todo COOKIE
                    if(cookieDoc::isExist('credit_card') && count(cookieDoc::get('credit_card'))!=$ccFilesCount){
                        $tmpDoc = json_decode($docErrors, true);
                        $tmpDoc['Document_credit_card'][] = (wlParams::get('officeCode') == 6) ? Yii::t("funds","610_min_2_files") : Yii::t("funds","527_min_2_files");
                        $docErrors = json_encode($tmpDoc);
                    }

                    /*if(isset($_SESSION['Document']['credit_card']) && count($_SESSION['Document']['credit_card'])!=$ccFilesCount && count($_SESSION['Document']['credit_card'])!=0){
                        $tmpDoc = json_decode($docErrors, true);
                        $tmpDoc['Document_credit_card'][] = (wlParams::get('officeCode') == 6) ? Yii::t("funds","610_min_2_files") : Yii::t("funds","527_min_2_files");
                        $docErrors = json_encode($tmpDoc);
                    }*/
                }

                if(isset($_POST["add_new_card_sbmt"]) && $userCardsNum == 0){

                    /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                        var_dump('111111111', $_POST["FundServices"]["cardno"]);die();
                    }*/

                    if(isset($_POST["FundServices"]["cardno"]) && !empty($_POST["FundServices"]["cardno"]) && ($_POST["FundServices"]["cardno"] == 'knet' || $_POST["FundServices"]["cardno"] == 'knet2'  || $_POST["FundServices"]["cardno"] == 'telr'  || $_POST["FundServices"]["cardno"] == 'tap'  || $_POST["FundServices"]["cardno"] == 'upay'  || $_POST["FundServices"]["cardno"] == 'ccavenue' || $_POST["FundServices"]["cardno"] == 'myfatoorah' || $_POST["FundServices"]["cardno"] == 'myfatoorah_acc2' ||  $_POST["FundServices"]["cardno"] == 'myfatoorah_acc3'  ||  $_POST["FundServices"]["cardno"] == 'myfatoorah_acc4' || $_POST["FundServices"]["cardno"] == '_accentpay')){
                        $Funds = new FundServices('Fund');
                        $Funds->attributes = $postF = Yii::app()->request->getPost('FundServices');
                        $Funds->currency = ['pMethodCur'];

                        echo json_encode($Funds->getErrors());
                        Yii::app()->end();
                        //var_dump($Funds->validate(), $Funds->getErrors());die();
                    }

                    $Funds = new FundServices('cardDeposit');
                    $Funds->attributes = $postF = Yii::app()->request->getPost('FundServices');



                    $arKeysPost = array_keys($postF);
                    if(isset($postF['transferTo']) && in_array((int)$postF['transferTo'], Yii::app()->params['testDepositTrAccs'])){
                        unset($arKeysPost[array_search('amount', $arKeysPost)]);
                    }
                    $validateFunds = CActiveForm::validate($Funds, $arKeysPost);

                    $tmpFundsErrors = array();
                    foreach(json_decode($validateFunds, true) as $ck => $ccError){
                        if($ck!='FundServices_cardId'){
                            $tmpFundsErrors[$ck] = $ccError;
                        }
                    }
                    $validateFunds = json_encode($tmpFundsErrors);
                    //var_dump($validateFunds);die();
                }
                //var_dump('-----',$validateFunds);die();

                /*$ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                if ($ipx == '77.222.143.18' || $ipx == '46.98.252.74') {
                    var_dump(json_decode($docErrors, true), json_decode($validateCards, true), json_decode($validateFunds, true));die();
                }*/

                echo json_encode(array_merge(json_decode($docErrors, true), json_decode($validateCards, true), json_decode($validateFunds, true)));
                Yii::app()->end();
            }



            if (isset($_POST["editCard"])) {
                $CreditCard->attributes = $_POST;
                $validateCards = CActiveForm::validate($CreditCard);
                if ($validateCards != '[]') {
                    echo $validateCards;
                }else{
                    $rez = $CreditCard->update();
                    $cardsTable = $CreditCard->getCardsTable();
                    $backData['data'] = $cardsTable;
                    if(isset($rez['State']) && $rez['State']==0){
                        $backData['result'] = 'ok';
                    }else{
                        $backData['result'] = 'no';
                    }
                    echo json_encode($backData);
                }
                Yii::app()->end();
            }

            if (isset($_POST["removeCard"])){
                $CreditCard->attributes = $_POST;
                $rez = $CreditCard->remove();
                $cardsTable = $CreditCard->getCardsTable();
                $backData['data'] = $cardsTable;
                if(isset($rez['State']) && $rez['State']==0){
                    $backData['result'] = 'ok';
                }elseif(isset($rez[0]) && $rez[0] == 'CantDeleteCreditCardWithPendingTr'){
                    $backData['result'] = $rez[0];
                }else{
                    $backData['result'] = 'no';
                }
                echo json_encode($backData);
                Yii::app()->end();
            }

            $validateFunds = $docErrors = '[]';
            $fundAttrs  = $postF = Yii::app()->request->getPost('FundServices');

            if($fundAttrs['deposit_type']=='live'){

                if($fundAttrs['ipsno']=='webmoney'){
                    echo $validateFunds;
                    Yii::app()->end();
                }


               /* $ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                if ($ipx == '77.222.143.18' || $ipx == '46.98.252.74') {
                    var_dump('$fundAttrs', $fundAttrs);die();
                }*/


                if (
                    !empty($fundAttrs["cardno"]) &&
                    $fundAttrs["cardno"]!='neo'  &&
                    $fundAttrs["cardno"]!='neonew' &&
                    $fundAttrs["cardno"]!='network' &&
                    $fundAttrs["cardno"]!='paytab' &&
                    $fundAttrs["cardno"]!='knet'  &&
                    $fundAttrs["cardno"]!='knet2' &&
                    $fundAttrs["cardno"]!='telr' &&
                    $fundAttrs["cardno"]!='tap' &&
                    $fundAttrs["cardno"]!='upay' &&
                    $fundAttrs["cardno"]!='ccavenue' &&
                    $fundAttrs["cardno"]!='myfatoorah' &&
                    $fundAttrs["cardno"]!='myfatoorah_acc2' &&
                    $fundAttrs["cardno"]!='myfatoorah_acc3' &&
                    $fundAttrs["cardno"]!='myfatoorah_acc4' &&
                    $fundAttrs["cardno"]!='_accentpay' &&
                    $fundAttrs["cardno"]!='zotapay' &&
                    !empty($Funds->cards) &&
                    (in_array($fundAttrs["transferFrom"], $Funds->noorcards[$fundAttrs["cardno"]]) || wlParams::get('only_cards'))
                ){
                    $Funds = new FundServices('cardDeposit');
                }elseif($fundAttrs['ipsno']=='neteller' || $fundAttrs['ipsno']=='neteller2' || $fundAttrs['ipsno']=='astropay'){
                    $Funds = new FundServices($fundAttrs['ipsno']);
                }elseif($fundAttrs['ipsno']=='sovvipay'){
                    $Funds = new FundServices($fundAttrs['ipsno']);
                }elseif($fundAttrs['ipsno']=='gate_to_pay'){
                    $Funds = new FundServices(isset($fundAttrs['gate_scenario']) ? $fundAttrs['gate_scenario'] : $fundAttrs['ipsno']);
                }elseif($fundAttrs['ipsno']=='lionpay' || $fundAttrs['ipsno']=='awepay' || $fundAttrs['ipsno']=='nganluong' || $fundAttrs['ipsno']=='awepayshp'){
                    $Funds = new FundServices('Fund');
                }elseif($fundAttrs['ipsno']=='ewallet'){
                    $eWallet = new eWallet();

                    $eWallet->defaultbank = Yii::app()->request->getPost('eWallet')["defaultbank"];
                    $eWallet->total_fee = Yii::app()->request->getPost('FundServices')["amount"];
                    $validateEWallet = CActiveForm::validate($eWallet);
                    //var_dump($validateEWallet);die();
                }else{
                    $Funds = new FundServices('Fund');
                }

                $Funds->attributes = $fundAttrs;

                if(isset($_POST['pMethodCur']) && !empty($_POST['pMethodCur'])){
                    $Funds->currency = $_POST['pMethodCur'];
                }

                /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                    var_dump($_POST);die();
                }*/

                /* if($_SERVER['REMOTE_ADDR'] == '46.98.175.227'){
                    var_dump($_POST['pMethodCur'], $Funds->attributes, $fundAttrs);die();
                }  */

                //var_dump($Funds->attributes, $Funds->getScenario());die();

                if($fundAttrs['ipsno']=='cashu' && empty($Funds->currency)){
                    $Funds->currency = 'USD';
                }elseif($fundAttrs['ipsno']=='dcpay' && empty($Funds->currency)){
                    if(isset($_POST['pMethodCur']) && !empty($_POST['pMethodCur'])){
                        $Funds->currency = $_POST['pMethodCur'];
                    }else{
                        $Funds->currency = 'CNY';
                    }
                }


                $arKeysPost = array_keys($postF);
                if(isset($postF['transferTo']) && in_array((int)$postF['transferTo'], Yii::app()->params['testDepositTrAccs'])){
                    unset($arKeysPost[array_search('amount', $arKeysPost)]);
                }

                $validateFunds = CActiveForm::validate($Funds, $arKeysPost);

                //echo $validateFunds;
                //Yii::app()->end();

            }elseif($fundAttrs['deposit_type']=='demo'){
                $Funds = new FundServices('demoDeposit');
                $Funds->attributes = $fundAttrs;
                $validateFunds = CActiveForm::validate($Funds, array('transferTo', 'amount'));
            }else{
                $Funds = new FundServices('Fund');
                $Funds->attributes = $fundAttrs;

                $arKeysPost = array_keys($postF);
                if(isset($postF['transferTo']) && in_array((int)$postF['transferTo'], Yii::app()->params['testDepositTrAccs'])){
                    unset($arKeysPost[array_search('amount', $arKeysPost)]);
                }
                $validateFunds = CActiveForm::validate($Funds, $arKeysPost);
            }

            $errors = array_merge(json_decode($validateFunds, true), json_decode($docErrors, true));

            if($fundAttrs['ipsno']=='ewallet'){
                $errors = array_merge($errors, json_decode($validateEWallet, true));
                //var_dump($errors);die();
            }

            echo json_encode($errors);

            Yii::app()->end();
        }
        // ------  end ajax

        if (Yii::app()->request->isPostRequest){

            $noPost = false;

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump($_POST);die();
            }*/


            if(isset($_POST['FundServices']['gate_scenario']) && $_POST['FundServices']['gate_scenario'] == 'gate_to_pay_deposit'){
                $GateToPay = new GateToPay($_POST['FundServices']['gate_scenario']);
                $GateToPay->attributes = $_POST["FundServices"];
                $GateToPay->currency = $_POST['pMethodCur'];
                $GateToPay->account = (int)$_POST["FundServices"]['transferTo'];
                $data = $GateToPay->MakeGTPDeposit();

                if($data){
                    $this->render('redirect', array('data'=>$data));
                    return;
                }else{
                    $this->redirect('/funds/deposit.html');
                    return;
                }


            }elseif(isset($_POST['FundServices']["ipsno"]) && $_POST['FundServices']["ipsno"] === 'gate_to_pay'){
                $GateToPay = new GateToPay('createCard');
                $GateToPay->attributes = $_POST["FundServices"];


                $res = $GateToPay->createGateToPayRequest();
                if(isset($res->State) && $res->State === 0){
                    $_SESSION['message'][] = array("text" => Yii::t("funds", "663_card_in_progress"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
                }elseif(isset($res->Message)){
                    $_SESSION['message'][] = array("text" => Yii::t("funds", "509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                }
                $this->redirect('/funds/deposit.html');
                return;
            }


            if(isset($_POST["pMethodCur"]) && !empty($_POST["pMethodCur"])){
                $_POST["FundServices"]["currency"] = $_POST["pMethodCur"];
            }

            $cardno = isset($_POST["FundServices"]["cardno"]) ? $_POST["FundServices"]["cardno"] : '';


            if ((isset($_POST["add_new_card_sbmt"]) || isset($_POST["edit_card_submit"])) && $_POST["FundServices"]["deposit_type"]=='live' && $cardno!='knet' && $cardno!='knet2' && $cardno!='myfatoorah'  && $cardno!='telr'  && $cardno!='tap'  && $cardno!='upay'  && $cardno!='ccavenue' && $cardno!='myfatoorah_acc2'  && $cardno!='myfatoorah_acc3' && $cardno!='myfatoorah_acc4' && $cardno!='_accentpay' && $cardno!='stripe'){

                $CreditCard->attributes = Yii::app()->request->getPost('CreditCard');
                $Document->attributes = $postDocument = Yii::app()->request->getPost('Document');
                if(isset($_POST['fromRedirectPage'])){
                    $CreditCard->attributes = Yii::app()->request->getPost('FundServices');
                }

                if(!isset($_POST["add_new_card_sbmt"])){
                    $uploader = CUploadedFile::getInstances($Document, 'credit_card');

                    // todo COOKIE
                    if(cookieDoc::isExist('credit_card')){
                        $docIsEmpty = false;
                    }else{
                        $docIsEmpty = true;
                    }

                    /*if(isset($_SESSION['Document']['credit_card']) && !empty($_SESSION['Document']['credit_card'])){
                        $docIsEmpty = false;
                    }else{
                        $docIsEmpty = true;
                    }*/
                }
                $check = $CreditCard->validate();
                //var_dump($check, $CreditCard->getErrors(), $_POST);die();

                if($check){
                    if(isset($_POST["add_new_card_sbmt"]) && !isset($_POST['fromRedirectPage'])){
                        $card = $CreditCard->add();
                    }elseif(isset($_POST["edit_card_submit"])){
                        //var_dump($CreditCard->attributes, Yii::app()->request->getPost('CreditCard'));
                        $CreditCard->update();
                        $new_cards = $CreditCard->init();
                        $card = (array)$new_cards[$CreditCard->Id];
                    }elseif(isset($_POST['fromRedirectPage'])){
                        $card = $CreditCard->attributes;
                    }


                    //var_dump((is_array($postDocument) && (isset($_POST["add_new_card_sbmt"]) || (isset($_POST["edit_card_submit"]) && !$docIsEmpty))), $postDocument, array('type'=>'credit_card', 'cardGuid'=>$card['Id']));die();
                    if (is_array($postDocument) && (isset($_POST["add_new_card_sbmt"]) || (isset($_POST["edit_card_submit"]) && !$docIsEmpty))) {
                        $Document->postDocSave($postDocument, array('type'=>'credit_card', 'cardGuid'=>$card['Id']));
                    }

                    if(isset($_POST["add_new_card_sbmt"]) && ($userCardsNum == 0 || (isset($_POST['fromRedirectPage']) && $userCardsNum == 1))){
                        $postFund = Yii::app()->request->getPost('FundServices');

                        $Funds = new FundServices('cardDeposit');
                        $Funds->attributes = $postFund;
                        //var_dump($card['Id'], $postFund);die();

                        // transfer from -> CARD
                        $trCode = Yii::app()->params['type'].'|'.(time() - mt_rand(0,10));

                        if ($postFund["cardno"] == 'inatec' || $postFund["cardno"] == 'ikajo' || $postFund["cardno"] == 'accentpay' || $postFund["cardno"] == 'lionpay' || $postFund["cardno"] == 'awepay' /*|| $postFund["cardno"] == 'neonew'*/) {
                            // Inatec payments
                            $cards = $CreditCard->init();

                            $ccardId = (isset($postFund['cardId']) && !empty($postFund['cardId'])) ? $postFund['cardId'] : $card['Id'];
                            //var_dump($card, $cards);die();
                            if(isset($cards[$ccardId]->cardStatus) && $cards[$ccardId]->cardStatus!=2){
                                $postRegistration = array_merge($postFund, (array)$cards[$ccardId]);

                                if($postFund["cardno"] == 'lionpay' || $postFund["cardno"] == 'ikajo' || $postFund["cardno"] == 'accentpay'){


                                    if($postFund["cardno"] == 'lionpay'){
                                        $Payment = new lionPay;
                                    }elseif($postFund["cardno"] == 'accentpay'){
                                        $Payment = new accentPay;
                                    }else{
                                        $Payment = new Ikajo;
                                    }
                                    //var_dump($cards, $postRegistration, $postFund);die();

                                    $post_data = $Payment->initData($postFund);
                                    $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                    if($postFund["cardno"] !== 'accentpay'){
                                        $post_data['action'] = $Payment->action;
                                    }
                                    $post_data['data']['cardId'] = $postRegistration['Id'];

                                    if($getInfo->Type == 6){
                                        if($getInfo->GroupType==1 || $getInfo->GroupType==3){
                                            $Trader = new RegistrationTrader('Individual');
                                            $Trader->initTrader();
                                            $idNum = 'passport='.$Trader->idNum;
                                            $name = $Trader->firstName.' '.$Trader->lastName;
                                        }elseif($getInfo->GroupType==2){
                                            $Trader = new RegistrationTrader('Corporate');
                                            $Trader->initTrader();
                                            $idNum = 'companyId='.$Trader->idNum;
                                            $name = $Trader->representativeFirstName.' '.$Trader->representativeLastName;
                                        }
                                        $country = $Trader->country;
                                    }elseif($getInfo->Type == 4){
                                        $name = $Registration->firstName.' '.$Registration->lastName;
                                        if($getInfo->GroupType==1){
                                            $idNum = 'passport='.$Registration->idNum;
                                        }elseif($getInfo->GroupType==2){
                                            $idNum = 'companyId='.$Registration->idNum;
                                        }
                                        $country = $Registration->country;
                                    }
                                    $fundsSourse = $Funds->getFundsSourse();
                                    $postRegistration['fundsSourse'] = $fundsSourse[$postRegistration['fundsSourse']];
                                    $serverName = ($_SERVER["SERVER_NAME"] == 'my.bmfn.cn') ? 'my.bmfn-solutions.com' : $_SERVER["SERVER_NAME"];
                                    $currency = isset($postRegistration['currency']) ? $postRegistration['currency'] : 'USD';
                                    $post_data['data']['link'] = base64_encode('http://'.$serverName.'/pdf/DeclarationOrigin.pdf?name='.rawurlencode($name).'&'.$idNum.'&address='.rawurlencode($postRegistration['address']).', '.$postRegistration['city'].', '.$postRegistration['country'].'&citizenship='.$country.'&currency='.rawurlencode($postRegistration['amount'].' '.$currency).'&describe='.rawurlencode($postRegistration['fundsSourse']));


                                    /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                                        var_dump('111', $post_data);die();
                                    }*/

                                    $this->render('redirect', array('data'=>$post_data));
                                    return true;
                                }/*elseif($postFund["cardno"] == 'neonew'){
                                    $NeoNew = new NeoNew();
                                    $post_data = $NeoNew->initData($postFund);

                                    $this->render('redirect', array('data'=>$post_data));
                                    return true;
                                }*/else{

                                    if(/*$postFund["cardno"] == 'ikajo' ||*/ $postFund["cardno"] == 'inatec' || $postFund["cardno"] == 'awepay'){


                                        if(Yii::app()->params['inatec_is_frame']){
                                            $postFund["ccFullNumber"] = 'frame';
                                            $postFund["cvc_code"] = $postFund["exp_month"] = $postFund["exp_year"] = '';
                                            $gets = $Funds->paymentInatec($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration, $trCode, $postFund["ccFullNumber"], $postFund["cvc_code"], $postFund["exp_month"], $postFund["exp_year"]);
                                            if(isset($gets) && isset($gets['frame_url']) && !empty($gets['frame_url'])){
                                                $this->redirect($gets['frame_url']);
                                            }
                                        }

                                        if(empty($postRegistration['cvc_code']) || empty($postRegistration['exp_month']) || empty($postRegistration['exp_year']) || empty($postRegistration['ccFullNumber'])){
                                            $Funds = new FundServices('ccFull');
                                            $this->render('cardRedirect', array('Funds'=>$Funds, 'data'=>$postRegistration, 'add_new_card_sbmt'=>'1'));
                                            die();
                                        }
                                    }

                                    if ($postFund["cardno"] == 'inatec' /*|| $postFund["cardno"] == 'ikajo'*/){
                                        $gets = $Funds->paymentInatec($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration, $trCode, $postFund["ccFullNumber"], $postFund["cvc_code"], $postFund["exp_month"], $postFund["exp_year"]);
                                        // Write to session for redirect window form
                                        if(!empty($gets)){
                                            $_SESSION['inatecPost'] = $postRegistration;
                                            $_SESSION['inatecGets'] = $gets;
                                        }

                                        if (isset($_POST["deposPdf"]) && $_POST["deposPdf"]=='1') {
                                            $postRegistration = Yii::app()->session['inatecPost'];
                                            $gets = Yii::app()->session['inatecGets'];
                                            if(!empty($gets)){
                                                unset(Yii::app()->session['inatecPost'], Yii::app()->session['inatecGets']);

                                                $cardId = (isset($postRegistration["cardId"]) && !empty($postRegistration["cardId"])) ? $postRegistration["cardId"] : $postRegistration["Id"];
                                                $currency = isset($postRegistration['currency']) ? $postRegistration['currency'] : 'USD';

                                                $additionalInfo = $CreditCard->NewCreditCardTransaction($gets["inatec_params"]["orderid"], $postRegistration['amount'], $currency, $cardId, (int)$postRegistration["transferTo"]);

                                                $Funds = new FundServices('cardDeposit');

                                                if($getInfo->Type == 6){
                                                    if($getInfo->GroupType==1 || $getInfo->GroupType==3){
                                                        $Trader = new RegistrationTrader('Individual');
                                                        $Trader->initTrader();
                                                        $idNum = 'passport='.$Trader->idNum;
                                                        $name = $Trader->firstName.' '.$Trader->lastName;
                                                    }elseif($getInfo->GroupType==2){
                                                        $Trader = new RegistrationTrader('Corporate');
                                                        $Trader->initTrader();
                                                        $idNum = 'companyId='.$Trader->idNum;
                                                        $name = $Trader->representativeFirstName.' '.$Trader->representativeLastName;
                                                    }
                                                    $country = $Trader->country;
                                                }elseif($getInfo->Type == 4){
                                                    $name = $Registration->firstName.' '.$Registration->lastName;
                                                    if($getInfo->GroupType==1){
                                                        $idNum = 'passport='.$Registration->idNum;
                                                    }elseif($getInfo->GroupType==2){
                                                        $idNum = 'companyId='.$Registration->idNum;
                                                    }
                                                    $country = $Registration->country;
                                                }
                                                $fundsSourse = $Funds->getFundsSourse();
                                                $postRegistration['fundsSourse'] = $fundsSourse[$postRegistration['fundsSourse']];
                                                $serverName = ($_SERVER["SERVER_NAME"] == 'my.bmfn.cn') ? 'my.bmfn-solutions.com' : $_SERVER["SERVER_NAME"];
                                                $link = base64_encode('http://'.$serverName.'/pdf/DeclarationOrigin.pdf?name='.rawurlencode($name).'&'.$idNum.'&address='.rawurlencode($postRegistration['address']).', '.$postRegistration['city'].', '.$postRegistration['country'].'&citizenship='.$country.'&currency='.rawurlencode($postRegistration['amount'].' '.$currency).'&describe='.rawurlencode($postRegistration['fundsSourse']));
                                                $rez = $Document->send('declaration.pdf', $fileType = 'declaration', $additionalInfo, $link, 'false');
                                                if(!isset($rez->State) || $rez->State!=0 || !is_string($additionalInfo) || !isset($gets["inatec_params"]["start_url"])){
                                                    $gets='';
                                                    $_SESSION['message'][] = array("text" => Yii::t("funds","509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
                                                }else{
                                                    Yii::app()->getController()->redirect($gets["inatec_params"]["start_url"]);
                                                }
                                            }
                                        }
                                    }elseif($postFund["cardno"] == 'awepay'){
                                        $awePay = new AwePay('cc');
                                        if($getInfo->Type == 6){
                                            if($getInfo->GroupType==1 || $getInfo->GroupType==3){
                                                $Trader = new RegistrationTrader('Individual');
                                                $Trader->initTrader();
                                                $postFund['firstName'] = $Trader->firstName;
                                                $postFund['lastName'] = $Trader->lastName;
                                                $postFund['phone'] = $Trader->phone;
                                                $postFund['email'] = $Trader->email;
                                                $postFund['address'] = $Trader->address;
                                                $postFund['city'] = $Trader->city;
                                            }elseif($getInfo->GroupType==2){
                                                $Trader = new RegistrationTrader('Corporate');
                                                $Trader->initTrader();
                                                $postFund['firstName'] = $Trader->representativeFirstName;
                                                $postFund['lastName'] = $Trader->representativeLastName;
                                                $postFund['phone'] = $Trader->phone;
                                                $postFund['email'] = $Trader->email;
                                                $postFund['address'] = $Trader->address;
                                                $postFund['city'] = $Trader->city;
                                            }
                                        }elseif($getInfo->Type == 4){
                                            $postFund['firstName'] = $Registration->firstName;
                                            $postFund['lastName'] = $Registration->lastName;
                                            $postFund['phone'] = $Registration->phone;
                                            $postFund['email'] = $Registration->email;
                                            $postFund['address'] = $Registration->address;
                                            $postFund['city'] = $Registration->city;
                                        }

                                        $gets = $awePay->initData($postFund);
                                        //var_dump($postFund);die();
                                        $cardId = (isset($postFund["cardId"]) && !empty($postFund["cardId"])) ? $postFund["cardId"] : $postFund["Id"];
                                        $res = $awePay->newTransaction($gets['paydetails']['account_no'], $gets['cart']['summary']['amount_purchase'], $gets['paydetails']['md'], $gets['cart']['summary']['currency_code'], $cardId);

                                        $response = $awePay->sendData($gets);
                                        if(isset($response->status) && $response->status == 'OK'){
                                            $_SESSION['message'][] = array("text" => Yii::t("funds", "607_funds_accepted"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                                        }else{
                                            $_SESSION['message'][] = array("text" => $response->error->msg, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                        }
                                    }
                                }
                            }else{
                                $_SESSION['message'][] = array("text" => Yii::t("funds", "519_deposit_error_card_must_be_approve"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                            }
                        }else{
                            // Safecharge payments
                            $gets = $Funds->paymentSafecharge($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration['country'], $trCode);
                        }
                    }
                }



                $tmpEr = $Document->getErrors();
                if(!empty($tmpEr) && isset($docErrorGuid)){
                    $docError[$docErrorGuid] = $tmpEr["credit_card"][0];
                    if(isset($_POST["edit_card_submit"])){
                        $Document->clearErrors();
                    }
                    $tmpCcAttrs = $CreditCard->attributes;
                }else{
                    $docError = array();
                }

                $cardsTable = $CreditCard->getCardsTable($docError);
                $userCardsNum = $CreditCard->userCardsNum();

                if(!empty($tmpEr) && isset($docErrorGuid)){
                    $CreditCard->attributes = $tmpCcAttrs;
                }else{
                    $CreditCard->lastDigits = '';
                }
                $cardsShow = true;

                $Funds = new FundServices('cardDeposit');
                $Funds->attributes = Yii::app()->request->getPost('FundServices');

            }else{
                $postFund = Yii::app()->request->getPost('FundServices');




                /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                    var_dump($postFund);die();
                }*/

                if($postFund['deposit_type']=='live'){



                    if (!empty($postFund["cardno"]) && $postFund["cardno"]!='neo' && $postFund["cardno"]!='_accentpay' && $postFund["cardno"]!='neonew' && $postFund["cardno"]!='network' && $postFund["cardno"]!='totalpay' && $postFund["cardno"]!='paytab' && $postFund["cardno"]!='zotapay'/* && $postFund["cardno"]!='lionpay'*/ && !empty($Funds->cards) && (in_array($postFund["transferFrom"], $Funds->noorcards[$postFund["cardno"]]) || wlParams::get('only_cards'))) {
                        $Funds = new FundServices('cardDeposit');
                    }else{

                        $Funds = new FundServices('Fund');
                    }
                    $Funds->attributes = $postFund;


                    //var_dump($postFund, $postFund["ipsno"] , $Funds->ips, $postFund["transferFrom"]);die();

                    /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                        var_dump($postFund["cardno"]);die();
                    }*/



                    if (isset($postFund)) {

                        if (!empty($postFund["cardno"]) && $postFund["cardno"]!='neo' && $postFund["cardno"]!='neonew' && $postFund["cardno"]!='network' && $postFund["cardno"]!='totalpay' && $postFund["cardno"]!='paytab'  && $postFund["cardno"]!='knet'  && $postFund["cardno"]!='_accentpay'  && $postFund["cardno"]!='knet2' && $postFund["cardno"]!='myfatoorah' && $postFund["cardno"]!='telr' && $postFund["cardno"]!='tap'  && $postFund["cardno"]!='upay' && $postFund["cardno"]!='ccavenue' && $postFund["cardno"]!='myfatoorah_acc2' && $postFund["cardno"]!='myfatoorah_acc3' && $postFund["cardno"]!='myfatoorah_acc4' && $postFund["cardno"]!='zotapay' && $postFund["cardno"]!='stripe' /*&& $postFund["cardno"]!='lionpay'*/ && !empty($Funds->cards) && (in_array($postFund["transferFrom"], $Funds->noorcards[$postFund["cardno"]]) || wlParams::get('only_cards'))) {

                            // transfer from -> CARD





                            $trCode = Yii::app()->params['type'].'|'.(time() - mt_rand(0,10));
                            if ($postFund["cardno"] == 'ikajo' || $postFund["cardno"] == 'accentpay' || $postFund["cardno"] == 'inatec' || $postFund["cardno"] == 'lionpay' || $postFund["cardno"] == 'awepay') {
                                // Inatec payments


                                $cards = $CreditCard->init();
                                //var_dump($postFund);die();

                                if(isset($postFund['cardId']) && isset($cards[$postFund['cardId']]->cardStatus) && $cards[$postFund['cardId']]->cardStatus!=2){
                                    $postRegistration = array_merge($postFund, (array)$cards[$postFund['cardId']]);



                                    //if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                                    // todo inatecframe
                                    if(Yii::app()->params['inatec_is_frame']){
                                        $postFund["ccFullNumber"] = 'frame';
                                        $postFund["cvc_code"] = $postFund["exp_month"] = $postFund["exp_year"] = '';
                                        $gets = $Funds->paymentInatec($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration, $trCode, $postFund["ccFullNumber"], $postFund["cvc_code"], $postFund["exp_month"], $postFund["exp_year"]);
                                        if(isset($gets) && isset($gets['frame_url']) && !empty($gets['frame_url'])){
                                            $this->redirect($gets['frame_url']);
                                        }
                                    }
                                    //}

                                    /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                                        var_dump('5555555555');die();
                                    }*/

                                    if($postFund["cardno"] == 'lionpay' || $postFund["cardno"] == 'ikajo' || $postFund["cardno"] == 'accentpay'){


                                        /*if ($_SERVER['REMOTE_ADDR'] == '91.243.198.104') {
                                            var_dump($postFund);die();
                                        }*/
                                        if($postFund["cardno"] == 'lionpay'){
                                            $Payment = new lionPay;
                                        }if($postFund["cardno"] == 'accentpay'){
                                            $Payment = new accentPay;
                                        }else{
                                            $Payment = new Ikajo;
                                        }

                                        $post_data = $Payment->initData($postFund);
                                        $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                        if($postFund["cardno"] !== 'accentpay'){
                                            $post_data['action'] = $Payment->action;
                                        }
                                        $post_data['data']['cardId'] = $postRegistration['cardId'];

                                        if($getInfo->Type == 6){
                                            if($getInfo->GroupType==1 || $getInfo->GroupType==3){
                                                $Trader = new RegistrationTrader('Individual');
                                                $Trader->initTrader();
                                                $idNum = 'passport='.$Trader->idNum;
                                                $name = $Trader->firstName.' '.$Trader->lastName;
                                            }elseif($getInfo->GroupType==2){
                                                $Trader = new RegistrationTrader('Corporate');
                                                $Trader->initTrader();
                                                $idNum = 'companyId='.$Trader->idNum;
                                                $name = $Trader->representativeFirstName.' '.$Trader->representativeLastName;
                                            }
                                            $country = $Trader->country;
                                        }elseif($getInfo->Type == 4){
                                            $name = $Registration->firstName.' '.$Registration->lastName;
                                            if($getInfo->GroupType==1){
                                                $idNum = 'passport='.$Registration->idNum;
                                            }elseif($getInfo->GroupType==2){
                                                $idNum = 'companyId='.$Registration->idNum;
                                            }
                                            $country = $Registration->country;
                                        }
                                        $fundsSourse = $Funds->getFundsSourse();
                                        $postRegistration['fundsSourse'] = $fundsSourse[$postRegistration['fundsSourse']];
                                        $serverName = ($_SERVER["SERVER_NAME"] == 'my.bmfn.cn') ? 'my.bmfn-solutions.com' : $_SERVER["SERVER_NAME"];
                                        $currency = isset($postRegistration['currency']) ? $postRegistration['currency'] : 'USD';
                                        $post_data['data']['link'] = base64_encode('http://'.$serverName.'/pdf/DeclarationOrigin.pdf?name='.rawurlencode($name).'&'.$idNum.'&address='.rawurlencode($postRegistration['address']).', '.$postRegistration['city'].', '.$postRegistration['country'].'&citizenship='.$country.'&currency='.rawurlencode($postRegistration['amount'].' '.$currency).'&describe='.rawurlencode($postRegistration['fundsSourse']));


                                        /*if ($_SERVER['REMOTE_ADDR'] == '91.243.198.104' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                                            var_dump('2222', $post_data);die();
                                        }*/

                                        $this->render('redirect', array('data'=>$post_data));
                                        return true;
                                    }else{
                                        if ($postFund["cardno"] == 'inatec' /*|| $postFund["cardno"] == 'ikajo'*/ || $postFund["cardno"] == 'awepay'){
                                            if(empty($postRegistration['cvc_code']) || empty($postRegistration['exp_month']) || empty($postRegistration['exp_year']) || empty($postRegistration['ccFullNumber'])){
                                                $Funds = new FundServices('ccFull');
                                                $this->render('cardRedirect', array('Funds'=>$Funds, 'data'=>$postRegistration));
                                                die();
                                            }
                                        }

                                        // cvc_code exp_month exp_year ccFullNumber
                                        //var_dump($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration, $trCode, $postFund["ccFullNumber"]);

                                        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                                            var_dump($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration, $trCode, $postFund["ccFullNumber"], $postFund["cvc_code"], $postFund["exp_month"], $postFund["exp_year"]);die();
                                        }*/

                                        if ($postFund["cardno"] == 'inatec'){
                                            $gets = $Funds->paymentInatec($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration, $trCode, $postFund["ccFullNumber"], $postFund["cvc_code"], $postFund["exp_month"], $postFund["exp_year"]);

                                            // Write to session for redirect window form
                                            if(!empty($gets)){
                                                $_SESSION['inatecPost'] = $postRegistration;
                                                $_SESSION['inatecGets'] = $gets;
                                            }

                                            if (isset($_POST["deposPdf"]) && $_POST["deposPdf"]=='1') {
                                                $postRegistration = Yii::app()->session['inatecPost'];
                                                $gets = Yii::app()->session['inatecGets'];
                                                if(!empty($gets)){
                                                    unset(Yii::app()->session['inatecPost'], Yii::app()->session['inatecGets']);

                                                    $cardId = (isset($postRegistration["cardId"]) && !empty($postRegistration["cardId"])) ? $postRegistration["cardId"] : $postRegistration["Id"];
                                                    $currency = isset($postRegistration['currency']) ? $postRegistration['currency'] : 'USD';
                                                    $additionalInfo = $CreditCard->NewCreditCardTransaction($gets["inatec_params"]["orderid"], $postRegistration['amount'], $currency, $cardId, (int)$postRegistration["transferTo"]);
                                                    //var_dump($additionalInfo);die();
                                                    $Funds = new FundServices('cardDeposit');

                                                    if($getInfo->Type == 6){
                                                        if($getInfo->GroupType==1 || $getInfo->GroupType==3){
                                                            $Trader = new RegistrationTrader('Individual');
                                                            $Trader->initTrader();
                                                            $idNum = 'passport='.$Trader->idNum;
                                                            $name = $Trader->firstName.' '.$Trader->lastName;
                                                        }elseif($getInfo->GroupType==2){
                                                            $Trader = new RegistrationTrader('Corporate');
                                                            $Trader->initTrader();
                                                            $idNum = 'companyId='.$Trader->idNum;
                                                            $name = $Trader->representativeFirstName.' '.$Trader->representativeLastName;
                                                        }
                                                        $country = $Trader->country;
                                                    }elseif($getInfo->Type == 4){
                                                        $name = $Registration->firstName.' '.$Registration->lastName;
                                                        if($getInfo->GroupType==1){
                                                            $idNum = 'passport='.$Registration->idNum;
                                                        }elseif($getInfo->GroupType==2){
                                                            $idNum = 'companyId='.$Registration->idNum;
                                                        }
                                                        $country = $Registration->country;
                                                    }
                                                    $fundsSourse = $Funds->getFundsSourse();
                                                    $postRegistration['fundsSourse'] = $fundsSourse[$postRegistration['fundsSourse']];
                                                    $serverName = ($_SERVER["SERVER_NAME"] == 'my.bmfn.cn') ? 'my.bmfn-solutions.com' : $_SERVER["SERVER_NAME"];
                                                    $link = base64_encode('http://'.$serverName.'/pdf/DeclarationOrigin.pdf?name='.rawurlencode($name).'&'.$idNum.'&address='.rawurlencode($postRegistration['address']).', '.$postRegistration['city'].', '.$postRegistration['country'].'&citizenship='.$country.'&currency='.rawurlencode($postRegistration['amount'].' '.$currency).'&describe='.rawurlencode($postRegistration['fundsSourse']));
                                                    //var_dump($link);die();
                                                    $rez = $Document->send('declaration.pdf', $fileType = 'declaration', $additionalInfo, $link, 'false');
                                                    if(!isset($rez->State) || $rez->State!=0 || !is_string($additionalInfo) || !isset($gets["inatec_params"]["start_url"])){
                                                        $gets='';
                                                        $_SESSION['message'][] = array("text" => Yii::t("funds","509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
                                                    }else{
                                                        Yii::app()->getController()->redirect($gets["inatec_params"]["start_url"]);
                                                    }
                                                }
                                            }
                                        }elseif($postFund["cardno"] == 'awepay'){
                                            $awePay = new AwePay('cc');
                                            if($getInfo->Type == 6){
                                                if($getInfo->GroupType==1 || $getInfo->GroupType==3){
                                                    $Trader = new RegistrationTrader('Individual');
                                                    $Trader->initTrader();
                                                    $postFund['firstName'] = $Trader->firstName;
                                                    $postFund['lastName'] = $Trader->lastName;
                                                    $postFund['phone'] = $Trader->phone;
                                                    $postFund['email'] = $Trader->email;
                                                    $postFund['address'] = $Trader->address;
                                                    $postFund['city'] = $Trader->city;
                                                }elseif($getInfo->GroupType==2){
                                                    $Trader = new RegistrationTrader('Corporate');
                                                    $Trader->initTrader();
                                                    $postFund['firstName'] = $Trader->representativeFirstName;
                                                    $postFund['lastName'] = $Trader->representativeLastName;
                                                    $postFund['phone'] = $Trader->phone;
                                                    $postFund['email'] = $Trader->email;
                                                    $postFund['address'] = $Trader->address;
                                                    $postFund['city'] = $Trader->city;
                                                }
                                            }elseif($getInfo->Type == 4){
                                                $postFund['firstName'] = $Registration->firstName;
                                                $postFund['lastName'] = $Registration->lastName;
                                                $postFund['phone'] = $Registration->phone;
                                                $postFund['email'] = $Registration->email;
                                                $postFund['address'] = $Registration->address;
                                                $postFund['city'] = $Registration->city;
                                            }

                                            $gets = $awePay->initData($postFund);
                                            $cardId = (isset($postFund["cardId"]) && !empty($postFund["cardId"])) ? $postFund["cardId"] : $postFund["Id"];
                                            $res = $awePay->newTransaction($gets['paydetails']['account_no'], $gets['cart']['summary']['amount_purchase'], $gets['paydetails']['md'], $gets['cart']['summary']['currency_code'], $cardId);

                                            $response = $awePay->sendData($gets);
                                            if(isset($response->status) && $response->status == 'OK'){
                                                $_SESSION['message'][] = array("text" => Yii::t("funds", "607_funds_accepted"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                                            }else{
                                                //var_dump('111');die();
                                                $_SESSION['message'][] = array("text" => $response->error->msg, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                            }

                                        }
                                    }


                                }else{
                                    $_SESSION['message'][] = array("text" => Yii::t("funds", "519_deposit_error_card_must_be_approve"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                }
                            } else {
                                // Safecharge payments
                                $gets = $Funds->paymentSafecharge($postFund['transferTo'], $postFund['amount'], $postFund["cardno"], $postRegistration['country'], $trCode);
                            }

                        } elseif (
                                    (!empty($postFund["ipsno"]) && ((!empty($Funds->ips) && in_array($postFund["transferFrom"], $Funds->ips)) || $postFund["ipsno"] == 'neo' || $postFund["ipsno"] == 'neonew' || $postFund["ipsno"] == 'paymob' || $postFund["ipsno"] == 'network' || $postFund["ipsno"] == 'totalpay' || $postFund["ipsno"] == 'paytab' || $postFund["ipsno"] == 'emerpay' || $postFund["ipsno"] == 'zotapay' || $postFund["ipsno"] == 'lionpay' || $postFund["ipsno"] == 'awepay' || $postFund["ipsno"] == 'ccavenue' || $postFund["ipsno"] == 'stripe'))
                                    || (isset($postFund["cardno"]) && ($postFund["cardno"]=='knet' || $postFund["cardno"]=='knet2' || $postFund["cardno"]=='myfatoorah' || $postFund["cardno"]=='telr' || $postFund["cardno"]=='paytab'  || $postFund["cardno"]=='tap'  || $postFund["cardno"]=='upay' || $postFund["cardno"]=='ccavenue' || $postFund["cardno"]=='myfatoorah_acc2'  || $postFund["cardno"]=='myfatoorah_acc3' || $postFund["cardno"]=='myfatoorah_acc4' || $postFund["cardno"]=='_accentpay' || $postFund["cardno"]=='stripe'))
                                ) {

                            if ($postFund["ipsno"] == 'neo') {
                                // Neo payments
                                $Neo = new Neo();
                                $post_data['data'] = $Neo->sendRequestWithParams($postFund);
                                if(isset($post_data['data']['error'])){
                                    $firstError = array_shift($post_data['data']['error']);
                                    $_SESSION['message'][] = array("text" => Yii::t("funds", "576_please_contact_tech_support", array('{error}'=>$firstError[0])), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                    $this->redirect(array('/funds/deposit.html'));
                                }
                                $post_data['data']['amount'] = $postFund['amount'];
                                $post_data['data']['currency'] = $postFund['currency'];
                                $post_data['data']['account'] = (int)$postFund['transferTo'];
                                $post_data['type'] = $Neo->type;
                                $post_data['target'] = '_blank';
                                $post_data['action'] = $Neo->action;
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");

                            }elseif($postFund["ipsno"] == 'skrill') {
                                // Skrill payments

                                $Skrill = new Skrill();
                                $post_data = $Skrill->getSkrillParams((int)$postFund['transferTo'], $postFund['amount'], $postFund['currency']);
                                /* if(!empty($tmp)){
                                    $createTransaction = $Skrill->newTransaction((int)$postFund['transferTo'], $postFund['amount'], $tmp['data']['transaction_id']);
                                    if(is_string($createTransaction) && !empty($createTransaction) && $createTransaction != 'ErrorOccured'){
                                        $post_data = $tmp;
                                    }else{
                                        Yii::log(CVarDumper::dumpAsString(array('transaction has not created')), 'error', 'DcPay');
                                    }
                                } */
                            }elseif($postFund["ipsno"] == 'globepay') {
                                $GlobePay = new GlobePay();
                                $post_data = $GlobePay->initData($postFund);
                                /* if(!empty($tmp)){
                                    $createTransaction = $Skrill->newTransaction((int)$postFund['transferTo'], $postFund['amount'], $tmp['data']['transaction_id']);
                                    if(is_string($createTransaction) && !empty($createTransaction) && $createTransaction != 'ErrorOccured'){
                                        $post_data = $tmp;
                                    }else{
                                        Yii::log(CVarDumper::dumpAsString(array('transaction has not created')), 'error', 'DcPay');
                                    }
                                } */
                            }elseif($postFund["ipsno"] == 'totalpay') {
                                $TotalPay = new TotalPay();
                                $post_data = $TotalPay->initData($postFund);
                            }elseif($postFund["ipsno"] == 'paytab' || (isset($postFund["cardno"]) && $postFund["cardno"] == 'paytab')) {


                                $payTab = new PayTab();
                                $post_data = $payTab->initData($postFund);
                            }elseif($postFund["ipsno"] == 'astropay') {
                                $AstroPay = new AstroPay();
                                $post_data = $AstroPay->initData($postFund);


                                //$post_data = $GlobePay->initData($postFund);
                                /* if(!empty($tmp)){
                                    $createTransaction = $Skrill->newTransaction((int)$postFund['transferTo'], $postFund['amount'], $tmp['data']['transaction_id']);
                                    if(is_string($createTransaction) && !empty($createTransaction) && $createTransaction != 'ErrorOccured'){
                                        $post_data = $tmp;
                                    }else{
                                        Yii::log(CVarDumper::dumpAsString(array('transaction has not created')), 'error', 'DcPay');
                                    }
                                } */
                            }elseif($postFund["ipsno"] == 'neonew') {
                                $NeoNew = new NeoNew();
                                $post_data = $NeoNew->initData($postFund);
                            }elseif($postFund["ipsno"] == 'network') {
                                $Network = new Network();
                                $post_data = $Network->initData($postFund);
                                /*$ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                                if ($ipx == '77.222.143.18' || $ipx == '46.98.252.74') {
var_dump($post_data);die();
                                }*/
                            }elseif($postFund["ipsno"] == 'paymob') {
                                $PayMob = new PayMob();
                                $post_data = $PayMob->initData($postFund);
                                /*$ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                                if ($ipx == '77.222.143.18' || $ipx == '46.98.252.74') {
                                    var_dump($post_data);die();
                                }*/
                            }elseif($postFund["ipsno"] == 'knet' || (isset($postFund["cardno"]) && $postFund["cardno"] == 'knet')) {
                                // Skrill payments

                                //var_dump('2222', $postFund);die();

                                $kNet = new kNet();
                                $post_data = $kNet->initData($postFund);
                                /* if(!empty($tmp)){
                                    $createTransaction = $Skrill->newTransaction((int)$postFund['transferTo'], $postFund['amount'], $tmp['data']['transaction_id']);
                                    if(is_string($createTransaction) && !empty($createTransaction) && $createTransaction != 'ErrorOccured'){
                                        $post_data = $tmp;
                                    }else{
                                        Yii::log(CVarDumper::dumpAsString(array('transaction has not created')), 'error', 'DcPay');
                                    }
                                } */
                            }elseif($postFund["ipsno"] == '_accentpay' || (isset($postFund["cardno"]) && $postFund["cardno"] == '_accentpay')) {


                                $accentPay = new accentPay();
                                $post_data = $accentPay->initData($postFund);
                                //var_dump('_accentpay' , $postFund, $post_data);die();
                            }elseif($postFund["ipsno"] == 'knet2' || (isset($postFund["cardno"]) && $postFund["cardno"] == 'knet2')) {
                                $kNet2 = new kNet2();
                                $post_data = $kNet2->initData($postFund);
                            }elseif($postFund["ipsno"] == 'stripe' || (isset($postFund["cardno"]) && $postFund["cardno"] == 'stripe')) {


                                $Stripe = new Stripe();
                                $post_data = $Stripe->initData($postFund);
                            }elseif(isset($postFund["cardno"]) && ($postFund["cardno"] == 'myfatoorah' || $postFund["cardno"] == 'myfatoorah' || $postFund["cardno"] == 'myfatoorah_acc2'  || $postFund["cardno"] == 'myfatoorah_acc3' || $postFund["cardno"] == 'myfatoorah_acc4' ) ) {
                                $myFatoorah = new myFatoorah('|'.$postFund["cardno"]);
                                $post_data = $myFatoorah->initData($postFund);
                            }elseif(isset($postFund["cardno"]) && ($postFund["cardno"] == 'telr') ) {
                                $myTelr = new Telr();
                                $post_data = $myTelr->initData($postFund);
                            }elseif(isset($postFund["cardno"]) && ($postFund["cardno"] == 'tap') ) {
                                $Tap = new Tap();
                                $post_data = $Tap->initData($postFund);
                            }elseif(isset($postFund["cardno"]) && ($postFund["cardno"] == 'upay') ) {
                                $Upay = new Upay();
                                $post_data = $Upay->initData($postFund);
                            }elseif((isset($postFund["cardno"]) && ($postFund["cardno"] == 'ccavenue')) || $postFund["ipsno"] === 'ccavenue' ) {
                                $CCAvenue = new CCAvenue();
                                $post_data = $CCAvenue->initData($postFund);
                            }elseif($postFund["ipsno"] == 'cashu'){
                                $cashU = new cashU();
                                $cashParams = $cashU->getCashuParams((int)$postFund['transferTo'], $postFund['amount'], 'USD');
                                if($cashParams){
                                    $post_data = $cashU->getStep2Params();
                                    $post_data['data']['transferTo'] = (int)$postFund['transferTo'];
                                    $post_data['data']['amount'] = $postFund['amount'];
                                    $post_data['data']['currency'] = 'USD';
                                }
                            }elseif($postFund["ipsno"] == 'neteller2'){
                                $Neteller = new Neteller2();
                                $post_data = $Neteller->initData($postFund);
                            }elseif($postFund["ipsno"] == 'upi_icici'){
                                $UPIicici = new UPIicici();
                                $post_data = $UPIicici->initData($postFund);
                            }elseif($postFund["ipsno"] == 'india_cash_deposit'){
                                $indiaCashDeposit = new IndiaCashDeposit();
                                $post_data = $indiaCashDeposit->initData($postFund);
                            }elseif($postFund["ipsno"] == 'cryptapi'){
                                $CryptApi = new CryptApi();
                                $post_data = $CryptApi->initData($postFund);
                            }elseif($postFund["ipsno"] == 'finobyte'){
                                $FinoByte = new FinoByte();
                                $post_data = $FinoByte->initData($postFund);
                            }elseif($postFund["ipsno"] == 'nowpay'){
                                $Nowpay = new Nowpay('deposit');
                                $post_data = $Nowpay->initData($postFund);
                            }elseif($postFund["ipsno"] == 'neteller'){
                                $Neteller = new Neteller();

                                $Neteller->transactionAmount = $postFund['amount'];
                                $Neteller->paymentMethodValue = $postFund['ntlrAccId'];
                                $Neteller->verificationCode = $postFund['ntlrSecId'];
                                $Neteller->transactionCurrency = $postFund['currency'];
                                $Neteller->transactionMerchantRefId = Yii::app()->params['type'].uniqid();

                                if($Neteller->validate()){
                                    $trCreateResult = $Neteller->newTransaction((int)$postFund['transferTo'], $postFund['amount'], $Neteller->transactionMerchantRefId, $Neteller->transactionCurrency);

                                    if(is_string($trCreateResult) && !empty($trCreateResult) && $trCreateResult != 'ErrorOccured'){
                                        $result = $Neteller->sendRequest();

                                        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/neteller.txt',"a");
                                        fwrite($f, 'NewTransaction result  -  '.json_encode($result).' <br/>\n
		');
                                        if(isset($result['status']) && isset($result['status']) == 'ok'){
                                            $_SESSION['message'][] = array("text" => Yii::t("funds", "607_funds_accepted"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                                        }elseif(isset($result['api_error_message'])){
                                            $_SESSION['message'][] = array("text" => $result['api_error_message'], "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                        }elseif(is_string($result)){
                                            $_SESSION['message'][] = array("text" => $result, "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                        }
                                    }else{
                                        $_SESSION['message'][] = array("text" => Yii::t("funds", "605_transaction_didnt_create"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                    }
                                }else{
                                    foreach($Neteller->getErrors() as $error){
                                        $_SESSION['message'][] = array("text" => Yii::t("funds", "606_deposit_error", array('{error}'=>$error[0])), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                        break;
                                    }
                                }

                            }elseif($postFund["ipsno"] == 'dcpay'){
                                // Dcpay payments

                                $dcPay = new dcPay();
                                $realAmount = $postFund['amount'];
                                if($postFund["currency"] == 'USD'){
                                    $postFund['amount'] = round(stFunctions::currConv($postFund["currency"], 'CNH', $postFund['amount']), 2);
                                }
                                $post_data = $dcPay->getDcpayParams($postFund['transferTo'], $postFund['amount']);
                                $post_data['data']['real_amount'] = $realAmount;
                                $post_data['data']['real_currency'] = $postFund["currency"];

                            }elseif($postFund["ipsno"] == 'bfopay'){
                                // BfoPay payments

                                $bfopay = new BfoPay('deposit');
                                $realAmount = $postFund['amount'];
                                if($postFund["currency"] == 'USD'){
                                    $postFund['amount'] = round(stFunctions::currConv($postFund["currency"], 'CNH', $postFund['amount']), 2);
                                }
                                $post_data = $bfopay->sendRequest(array('account'=>$postFund['transferTo'], 'amount'=>$postFund['amount'], 'real_amount'=>$realAmount, 'real_currency'=>$postFund["currency"]));
                                $post_data['data']['real_amount'] = $realAmount;
                                $post_data['data']['real_currency'] = $postFund["currency"];

                            }elseif($postFund["ipsno"] == 'dinpay' || $postFund["ipsno"] == 'dinpay2'){
                                // Dinpay payments

                                if($postFund["ipsno"] == 'dinpay'){
                                    $dinPay = new dinPay('deposit');
                                }else{
                                    $dinPay = new dinPay('deposit', ['subSystem' => 'huayinpay']);
                                }

                                $realAmount = $postFund['amount'];
                                if($postFund["currency"] == 'USD'){
                                    $postFund['amount'] = round(stFunctions::currConv($postFund["currency"], 'CNH', $postFund['amount']), 2);
                                }
                                $post_data = $dinPay->getDinpayParams($postFund['transferTo'], $postFund['amount']);
                                $post_data['data']['real_amount'] = $realAmount;
                                $post_data['data']['real_currency'] = $postFund["currency"];

                            }elseif($postFund["ipsno"] == 'webmoney'){
                                // WebMoney payments

                                $post_data = $Funds->paymentWebmoney();

                            }elseif($postFund["ipsno"] == 'chinaunion'){
                                // ChinaUnion payments

                                $gets = $Funds->paymentChinaUnion($postFund['transferTo'], $postFund['amount']);
                            }elseif($postFund["ipsno"] == 'emerpay'){
                                $EMerchantPay = new EMerchantPay;
                                $link = $EMerchantPay->initData($postFund);

                                //$transaction_id = md5($_POST['account'].$_POST['amount'].$_POST['currency'].$EMerchantPay->client_id);
                                $post_data['type'] = $EMerchantPay->type;
                                $post_data['action'] = $link;
                                $post_data['data']['account'] = explode(',', $EMerchantPay->order_reference)[0];
                                $post_data['data']['amount'] = $EMerchantPay->item_1_unit_price_USD;
                                $post_data['data']['currency'] = $EMerchantPay->order_currency;
                                $post_data['data']['transaction_id'] = explode(',', $EMerchantPay->order_reference)[1];
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                            }elseif($postFund["ipsno"] == 'zotapay'){
                                $zdata = [
                                    'amount' => $postFund['amount'],
                                    'currency' => $postFund['currency'],
                                    'account' => (int)$postFund['transferTo'],
                                ];

                                $ZotaPay = new ZotaPay();

                                /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                                    var_dump($zdata);die();
                                }*/

                                $gets = $ZotaPay->makeDeposit($zdata);

                                //var_dump($gets);die();
                                $post_data = array();

                                if(isset($gets["code"]) && $gets["code"] == '200'){
                                    $post_data['type'] = $ZotaPay->type;
                                    $post_data['action'] = $gets["data"]['depositUrl'];
                                    $post_data['data']['account'] = (int)$postFund['transferTo'];
                                    $post_data['data']['amount'] = $postFund['amount'];
                                    $post_data['data']['currency'] = $postFund['currency'];
                                    $post_data['data']['transaction_id'] = $gets["data"]['merchantOrderID'];
                                    $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                }elseif($gets['message']){
                                    $_SESSION['message'][] = array("text" => $gets['message'], "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                }
                            }elseif($postFund["ipsno"] == 'ewallet'){
                                $eWallet = new eWallet();

                                $post_data = $eWallet->initData(array_merge($postFund, Yii::app()->request->getPost('eWallet')));
                            }elseif($postFund["ipsno"] == 'homepay'){
                                $homePay = new homePay();
                                $homePay->currency = $postFund['currency'];
                                $username = (isset($Registration->firstName) && isset($Registration->lastName)) ? $Registration->firstName.' '.$Registration->lastName : '';
                                $post_data = $homePay->wgCreateOrder(['pay_money' => $postFund['amount'], 'order_title' => (int)$postFund['transferTo']]);

                                //var_dump('333333', $post_data);die();
                            }elseif($postFund['ipsno']=='sandpay'){
                                $sandPay = new sandPay;

                                if($postFund['currency'] == 'USD'){
                                    $postFund['convertAmount'] = round(stFunctions::currConv($postFund['currency'], 'CNH', $postFund['amount']), 2);
                                    $postFund['convertCurrency'] = 'CNY';
                                }

                                $post_data = $sandPay->initData($postFund);
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                $post_data['action'] = '';
                                if(!isset($post_data['error'])){
                                    //var_dump($post_data);
                                }else{
                                    //$_SESSION['message'][] = array("text" => 'sandPay error', "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                                }
                            }elseif($postFund['ipsno']=='lionpay'){
                                $lionPay = new lionPay;

                                $post_data = $lionPay->initData($postFund);
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                $post_data['action'] = $lionPay->action;

                            }elseif($postFund['ipsno']=='awepay'){
                                $awePay = new AwePay('cc');

                                $post_data = $awePay->initData($postFund);
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                $post_data['action'] = $awePay->action;

                            }elseif($postFund['ipsno']=='nganluong'){
                                $nganLuong = new nganLuong;

                                /*if($postFund['currency'] == 'USD'){
                                    $postFund['convertAmount'] = round(stFunctions::currConv($postFund['currency'], 'CNH', $postFund['amount']), 2);
                                    $postFund['convertCurrency'] = 'CNY';
                                }*/

                                $post_data = $nganLuong->initData($postFund);
                                $post_data['type'] = 'nganluong';
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                            }elseif($postFund['ipsno']=='sovvipay'){
                                $sovviPay = new sovviPay;

                                if($postFund['currency'] == 'USD'){
                                    $postFund['convertAmount'] = round(stFunctions::currConv($postFund['currency'], 'CNH', $postFund['amount']), 2);
                                    $postFund['convertCurrency'] = 'CNY';
                                }

                                $post_data = $sovviPay->initData($postFund);
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                $post_data['action'] = $sovviPay->action;

                                //var_dump($post_data);die();

                            }elseif($postFund['ipsno']=='awepayshp'){
                                $AwePay = new AwePay('shp');

                                /*if($postFund['currency'] == 'USD'){
                                    $postFund['convertAmount'] = round(stFunctions::currConv($postFund['currency'], 'CNH', $postFund['amount']), 2);
                                    $postFund['convertCurrency'] = 'CNY';
                                }*/

                                //var_dump($Registration->attributes);die();
                                $post_data = $AwePay->initData(array_merge($postFund, $Registration->attributes));
                                $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
                                $post_data['action'] = $AwePay->action;

                                //var_dump($post_data);die();
                                //var_dump($post_data);die();

                            }

                            //transfer from -> IPS
                        } else {

                            // transfer from -> BANK
                            // your static bank info (from Sonin) with print or send button
                            if(isset($postFund["transferFrom"]) && isset($postFund["amount"]) && isset($postFund["currency"]) && isset($postFund["transferTo"])){
                                Yii::app()->getController()->redirect("/funds/transferBankDetails?bankno=".urlencode($postFund["transferFrom"])."&amount=".$postFund["amount"]."&currency=".$postFund["currency"]."&account=".$postFund["transferTo"]);
                            }
                        }
                    }
                }elseif($postFund['deposit_type']=='demo'){
                    $Funds = new FundServices('demoDeposit');
                    $Funds->attributes = $postFund;

                    /* $Funds = new FundServices('demoDeposit');
                    $Funds->attributes = $fundAttrs; */
                    $validateFunds = CActiveForm::validate($Funds, array('transferTo', 'amount'));

                    if($validateFunds=='[]'){
                        preg_match('/(\d+).*\((.*)\)/', $postFund["transferTo"], $account);

                        $accTmp = (isset($account[1]) ? $account[1] : $postFund["transferTo"]);

                        $deposit_rez = $Funds->makeDemoDeposit($accTmp, $postFund["amount"]);

                        if($deposit_rez=='ok' || (isset($deposit_rez->State) && $deposit_rez->State == 0)){
                            foreach($traderAccounts as &$platform){
                                foreach($platform as &$acc){
                                    if($acc->AccountNum === $accTmp){
                                        $acc->Balance += (float)$postFund["amount"];
                                    }
                                }
                            }

                            $_SESSION['message'][] = array("text" => Yii::t("funds", "456_successfuy_deposit", array('{amount}'=>$postFund["amount"])), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                        }elseif($deposit_rez=='UnlegalDeposit'){
                            $_SESSION['message'][] = array("text" => Yii::t("funds", "455_enough_demo_funds"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
                        }
                    }
                }
                $Funds->transferTo = $Funds->transferFrom = $Funds->amount = '';
            }

            if( isset($_POST["transactionid"]) && $_POST["transactionid"]!=''){
                $signature='';
                $params=$_POST;
                ksort($params);
                foreach( $params as $key => $val ) {
                    if( $key != "security" ){$signature .= $val;}
                }
                $signature .= Yii::app()->params['inatec_signature'];
                $mysecure  = strtolower( sha1( $signature ) );
                if($_POST["security"]==$mysecure){
                    if($params["errorcode"]==0){
                        $_SESSION['message'][] = array("text" => Yii::t("main", "960_inatec_success"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                    }
                    elseif($params["errorcode"]==2000){
                        $_SESSION['message'][] = array("text" => Yii::t("funds", "536_inotec_panding"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
                    }
                    else{
                        $_SESSION['message'][] = array("text" => Yii::t("main", "419_1_inatec_failed"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                    }
                }else{
                    $_SESSION['message'][] = array("text" => Yii::t("main", "419_1_inatec_failed"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                }
            }


        }

        if($noPost && !isset($_GET['acc']) && !isset($_GET['type'])){
            if($getInfo->Type == 6 && $getInfo->GroupType==2){
                $CreditCard->attributes = $Trader->attributes;
                $name = $Trader->representativeFirstName.' '.$Trader->representativeLastName;
            }else{
                $CreditCard->attributes = $Registration->attributes;
                $CreditCard->userName = $Registration->firstName.' '.$Registration->lastName;
            }
        }

        $funds_source = array('0'=>Yii::t("funds","464_select_source_of_funds"));
        $funds_source = array_merge($funds_source, $Funds->getFundsSourse());

        if(count($Document->getErrors('credit_card'))>0){$cardsShow = true;}

        if($getInfo->Type == '6'){
            $allow = (count((array)$traderAccounts) > 0) ? true : false;
        }else{
            $allow = true;
        }
        $docid=0;
        $rez=$Account->GetDocumentsID();
        if(isset($rez)&& $rez>0){$docid=$rez;}

        $url = wlParams::get('docsFolderServer')."/".$docid."/".Yii::app()->language."/CreditCardTerms.pdf";
        $Headers = @get_headers($url);
        if(substr_count($Headers[0], '200')>0) { $CCardFile=$url;} else { $CCardFile = wlParams::get('docsFolderServer')."/".$docid."/en/CreditCardTerms.pdf";}

        //var_dump($post_data);die();





        if(isset($post_data) && !empty($post_data) && isset($post_data['type']) && $post_data['type'] != 'none'){
            $rData = (isset($post_data) && !empty($post_data)) ? $post_data : $gets;

            /*if ($_SERVER['REMOTE_ADDR'] == '91.243.198.104' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump($rData);die();
            }*/

            /*if ($_SERVER['REMOTE_ADDR'] == '46.98.64.234' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump('333', $rData);die();
            }*/

            $this->render('redirect', array('data'=>$rData));
            die();
        }

        $pMethod['knet'] = new kNet();
        $pMethod['knet2'] = new kNet2();
        $pMethod['_accentpay'] = new accentPay();
        $pMethod['myfatoorah'] = new myFatoorah();
        $pMethod['telr'] = new Telr();
        $pMethod['tap'] = new Tap();
        $pMethod['upay'] = new Upay();
        $pMethod['myfatoorah_acc2'] = new myFatoorah();
        $pMethod['myfatoorah_acc3'] = new myFatoorah();
        $pMethod['myfatoorah_acc4'] = new myFatoorah();
        $pMethod['skrill'] = new Skrill();
        $pMethod['globepay'] = new GlobePay();
        $pMethod['cashu'] = new cashU();
        $pMethod['dcpay'] = new dcPay();
        $pMethod['sandpay'] = new sandPay();
        $pMethod['sovvipay'] = new sovviPay();
        $pMethod['lionpay'] = new lionPay();
        $pMethod['awepay'] = new AwePay('cc');
        $pMethod['awepayshp'] = new AwePay('shp');
        $pMethod['nganluong'] = new nganLuong();
        $pMethod['astropay'] = new AstroPay();
        $pMethod['neonew'] = new NeoNew();
        $pMethod['network'] = new Network();
        $pMethod['paymob'] = new PayMob();
        $pMethod['totalpay'] = new TotalPay();
        $pMethod['zotapay'] = new ZotaPay();
        $pMethod['dinpay2'] = new dinPay('deposit', ['subSystem' => 'huayinpay']);
        $pMethod['dinpay'] = new dinPay('deposit');
        $pMethod['bfopay'] = new BfoPay('deposit');
        $pMethod['neteller'] = new Neteller('neteller');
        $pMethod['neteller2'] = new Neteller2('neteller2');
        $pMethod['ccavenue'] = new CCAvenue();
        $pMethod['nowpay'] = new Nowpay();
        $pMethod['paytab'] = new PayTab();
        $pMethod['upi_icici'] = new UPIicici();
        $pMethod['india_cash_deposit'] = new IndiaCashDeposit();
        $pMethod['cryptapi'] = new CryptApi();
        $pMethod['finobyte'] = new FinoByte();
        $pMethod['gate_to_pay'] = new GateToPay();

        if(wlParams::get('CardDepositSystem') == 'neo'){
            $pMethod['neo'] = new Neo();
        }
        if(wlParams::get('emerpay')){
            $pMethod['emerpay'] = new EMerchantPay();
        }
        if(wlParams::get('zotapay')){
            $pMethod['zotapay'] = new ZotaPay();
        }
        if(wlParams::get('ewallet')){
            $pMethod['ewallet'] = new eWallet();
        }
        if(wlParams::get('homepay')){
            $pMethod['homepay'] = new homePay();
        }

        $view = Yii::app()->params['styles_type'] === 'new' ? 'deposit_dashboard' : 'deposit';

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($BanksInfo);die();
        }*/

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($pMethod);die();
        }*/

        $this->render($view, array('Funds'=>$Funds, 'Bank'=>$Bank, 'Registration'=>$Registration, 'BanksInfo'=>$BanksInfo, 'AvaliablesBanks'=>$AvaliablesBanks, 'WebMobeyAcc'=>$WebMobeyAcc, 'traderAccounts' => $traderAccounts, 'ibAccounts' => $Account->GetSysAccount(), 'Type' => $getInfo->Type, 'approve'=>$approve, 'countries' => $countries, /*'agreeBonus'=>$agreeBonus,*/ 'countries_code_three'=>$countries_code_three, 'countries_code_two'=>$countries_code_two, /*'BonusPercent' =>$BonusPercent,*/ 'gets'=>$gets, 'post_data'=>$post_data, 'funds_source'=>$funds_source, 'CreditCard'=>$CreditCard, 'Document'=>$Document, 'cardsTable'=>$cardsTable, 'userCardsNum'=>$userCardsNum, 'countries'=>$Registration->GetCountry(), 'cardCurrencies'=>$Funds->getCardCurrencies(), 'cardsShow'=>$cardsShow, 'demoValues'=>$demoValues, 'allow'=>$allow, 'CCardFile'=>$CCardFile, 'pMethod'=>$pMethod, 'isFullProfile'=>$isFullProfile, 'Login' => $getInfo->Login));
    }

    public function actionCredirect() {
        $Funds = new FundServices('ccFull');
        $this->render('cardRedirect', array('Funds'=>$Funds));
    }

    public function actionWithdrawal(){
        $this->pageTitle = Yii::t("funds", "49_fund_withdrawals");
        $this->breadcrumbs = array(
            Yii::t("funds","47_fund_services") => ('/funds/index.html'),
            Yii::t("funds", "49_fund_withdrawals"));



        $Funds = new FundServices('Withdrawal');

        $Account = new Account();
        $getInfo = $Account->GetInfo();

        if (/*$getInfo->Login == '1000207844' ||*/
            // disable withdrawal option, block withdrawal
            $getInfo->Login == '1000225347'  ||
            $getInfo->Login == '1000225127'  ||
            $getInfo->Login == '1000232664'  ||
            $getInfo->Login == '1000225366'  ||
            $getInfo->Login == '1000226300'  ||
            $getInfo->Login == '1000230924'  ||
            $getInfo->Login == '1000225780'  ||
            $getInfo->Login == '1000224616'  ||
            $getInfo->Login == '1000227794'  ||
            $getInfo->Login == '1000228889'  ||
            $getInfo->Login == '1000199491'  ||
            $getInfo->Login == '1000199489'  ||
            $getInfo->Login == '1000201334'  ||
            $getInfo->Login == '1000226823' ) {
            die(' '); //access denied
        }

        $traderAccounts = $Account->GetAccount();
        $traderLiveAccounts = $Account->GetAccount(array('live'));
        $officeShortCode=$Account->GetUserOfficeShortCode();
        /* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
            var_dump($officeShortCode);die();
        } */
        if ($officeShortCode == 'BJI') {die('no access to this page');}

        $showWithdrawal = false;

        $parInfo = $Account->getParentContacts();
        /* if($parInfo['Code'] == 8057){
            die('no access');
        } */

        $Registration = new Registration('Individual');
        $Registration->initIndv();
        $country = $Registration->GetCountry();

        //$Document = new Document('withdrawal');
        if(wlParams::get('officeCode') == 3 || wlParams::get('officeCode') == 30){
            $Document = new Document('with_docs');


            $with_docs = $Document->isExist('with_docs', 'with_docs');
            if(!empty($with_docs) && count($with_docs) > 0){
                $showWithdrawal = true;
            }
        }else{
            $Document = new Document('proof_address');
        }

        $Bank = new RegistrationBank('Funds');
        $Bank->initBank();

        if (Yii::app()->request->isAjaxRequest){

            if(isset($_POST['docDownload']) || isset($_POST['proof_adress_save'])){

                $Document->attributes = $postDocs = Yii::app()->request->getPost('Document');
                // Document model in view must be call only "$Document"  ---  IMPORTANT!!!

                /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                    var_dump($postDocs, $_POST['with_docs']);die();
                }*/
                $params['addInfo'] = (isset($_POST['with_docs'])) ? 'with_docs' : '';

                $docErrors = $Document->ajaxDocValidate($postDocs, $Document, $params);


                if(!empty($docErrors)){
                    echo $docErrors;
                    Yii::app()->end();
                }
            }else{

                $Funds->attributes = $fundAttrs = Yii::app()->request->getPost('FundServices');
                $Bank->attributes = $bankAttrs = Yii::app()->request->getPost('RegistrationBank');
                $fundsEr = array();
                $BanksEr = array();
                $fundsEr = (array)json_decode(CActiveForm::validate($Funds));
                $BanksEr = (array)json_decode(CActiveForm::validate($Bank));

                $errors = array_merge($fundsEr, $BanksEr);
                echo json_encode($errors);
            }

            Yii::app()->end();
        }


        if (Yii::app()->request->isPostRequest){
            if(isset($_POST['docDownload'])){
                $Document->attributes = $post = Yii::app()->request->getPost('Document');
                if($post && is_array($post)){
                    $Document->postDocSave($post, array('type'=>'withdrawal'));
                }else{
                    $_SESSION['message'][] = array("text" => Yii::t("funds", "509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                }
            }elseif(isset($_POST['proof_adress_save'])){
                $Document->attributes = $post = Yii::app()->request->getPost('Document');
                if($post){
                    if (is_array($post)){
                        if(isset($post['with_docs'])){
                            $params['addInfo'] = 'with_docs';
                            $with_docs = $Document->isExist('with_docs', 'with_docs');

                            // todo COOKIE
                            $withCount = count(cookieDoc::get('with_docs')) + count($with_docs);
                            //$withCount = count(Yii::app()->session['Document']['with_docs']) + count($with_docs);

                            $isWithDoc = true;

                        }else{
                            $params = array();
                        }



                        $out = $Document->postDocSave($post, $params);




                        if(isset($isWithDoc)){
                            if($withCount > 0){
                                $showWithdrawal = true;

                            }else{
                                $Document->addError('with_docs', Yii::t("funds", "624_min_4_files"));
                            }
                        }else{
                            $showWithdrawal = true;

                        }
                    }
                }
            }else{
                // generate pdf
                $Funds->attributes = $postFund = Yii::app()->request->getPost('FundServices');
                $Bank->attributes = $postBank = Yii::app()->request->getPost('RegistrationBank');

                if($Bank->validate() && $Funds->validate()){
                    $Bank->update();
                    $adressWD = $Funds->GetAddressForWithdrawal();
                    $params = array('userName' => $Registration->firstName . ' ' . $Registration->lastName, 'currency'=>$postFund['currency'], 'amount' => $postFund['amount'], 'transferFrom' => $postFund['transferFrom'], 'beneficiary' => $postBank['beneficiary'], 'BankName' => $postBank['name'], 'swift_code' => $postBank['swift_code'], 'country' => $postBank['country'], 'city' => $postBank['city'], 'address' => $postBank['address'], 'account' => $postBank['account'], 'support_mail' => $adressWD[0], 'support_fax' => $adressWD[1]);

                    if (isset($postFund['currency']) && !empty($postFund['currency'])) {
                        $params['int_bank'] = $postFund['currency'];
                    }

                    if (isset($postBank['int_bank']) && !empty($postBank['int_bank'])) {
                        $params['int_bank'] = $postBank['int_bank'];
                    }
                    if (isset($postBank['reference']) && !empty($postBank['reference'])) {
                        $params['reference'] = $postBank['reference'];
                    }

                    $trnsction = $Funds->IBWithdrawalRequest((int)$postFund['transferFrom'], $postFund['amount'], $postFund['currency']);


                    Yii::app()->Pdf->render(wlParams::get('wthdrwl_pdf'), $params);
                }
            }
        }

        if($getInfo->Type == '6'){
            $allow = (count((array)$traderLiveAccounts) > 0) ? true : false;
        }else{
            $allow = true;
        }


        $this->render('withdrawal', array('Type' => $getInfo->Type, 'GroupType' => $getInfo->GroupType, 'country'=>$country, 'Bank'=>$Bank, 'Funds'=>$Funds, 'Document'=>$Document, 'cardCurrencies'=>$Funds->getCardCurrencies(), 'traderAccounts'=>$traderAccounts, 'ibAccounts' => $Account->GetSysAccount(), 'allow'=>$allow, 'showWithdrawal'=>$showWithdrawal));
    }

    public function actionInternalTransfer(){
        $this->pageTitle = Yii::t("funds", "49_internal_transfers");
        $this->breadcrumbs = array(
            Yii::t("funds","47_fund_services") => ('/funds/index.html'),
            Yii::t("funds", "49_internal_transfers"));

        $Funds = new FundServices('IntTrnsfr');

        $Account = new Account();
        $getInfo = $Account->GetInfo();
        $traderLiveAccounts=$Account->GetAccount(array('live'));
        $isWL = $Account->IsWhiteLabel();
        $Document = new Document();

        $wlTradersAccsTable = $paltforms = '';
        if($getInfo->Type == '4' && ($isWL)){
            /* 	$Platform = new Platform();
                $paltforms = $Platform->GetList(); */
            $Registration = new Registration();
            $paltformsTmp = $Registration->GetSchedule('-1', 'true', '1');
            $paltforms = array();
            foreach($paltformsTmp as $pl){
                $paltforms[$pl->PlatformID] = $pl->Name;
            }

            $Report = new Report(3);
            $Report->SetCountRowsTable(10);
            $Report->attributes = $_REQUEST;
            /* if(isset($_POST['current'])){
                $Report->page = $_POST['current'];
            } */
            //var_dump($Report->page, $_REQUEST);die();
            $Report->accountType = 1;
            //$Report->needGroups = 2;
            $Report->SendRequest();
            if(!in_array(2, $getInfo->InternalTransferProhibitions)){
                $sysAccs = $Account->GetSysAccount();
                //$yourAccs = (is_numeric($sysAccs) && $sysAccs == 0) ? $traderLiveAccounts : array_merge($sysAccs, $traderLiveAccounts);
                if(is_numeric($sysAccs) && $sysAccs == 0){
                    $yourAccs = $traderLiveAccounts;
                }else{
                    $yourAccs = array_merge($sysAccs, $traderLiveAccounts);
                }
            }else{
                $yourAccs = $traderLiveAccounts;
            }

            $youLiveAccs = array();
            foreach($traderLiveAccounts as $trAcc){
                $youLiveAccs[] = $trAcc->AccountNum;
            }
            //var_dump($youLiveAccs);die();
            //var_dump($Report->listReport);die();

            $wlTradersAccsTable = $Report->getUsersTrAccsTable($yourAccs, $youLiveAccs);

        }
        //var_dump($yourAccs);die();

        if (Yii::app()->request->isAjaxRequest){
            if(isset($_POST['GetUserAccs'])){
                echo $wlTradersAccsTable;
                Yii::app()->end();
            }

            $Funds->attributes = $fundAttrs = Yii::app()->request->getPost('FundServices');
            $validateFunds = CActiveForm::validate($Funds, array_keys($fundAttrs));
            if ($validateFunds != '[]') {
                echo $validateFunds;
                Yii::app()->end();
            }

            Yii::app()->end();
        }

        if (Yii::app()->request->isPostRequest) {
            $Funds->attributes = $fundAttrs = Yii::app()->request->getPost('FundServices');
            $validateFunds = CActiveForm::validate($Funds, array_keys($fundAttrs));
            if ($validateFunds != '[]') {
                echo $validateFunds;
            }else{
                if((int)$fundAttrs['transferFrom'] != (int)$fundAttrs['transferTo']){
                    //var_dump($_POST['accType']);die();
                    $Funds->fromAccToAcc($fundAttrs['transferFrom'], $fundAttrs['transferTo'], $fundAttrs['amount'], isset($_POST['accType']) ? $_POST['accType'] : 'tradingAcc', (isset($_POST['debitedAccountType']) && $_POST['debitedAccountType']!= '') ? $_POST['debitedAccountType'] : '1');
                    $Funds->transferFrom = '';
                    $Funds->transferTo = '';
                    $Funds->amount = '';
                }else{
                    $_SESSION['message'][] = array("text" => Yii::t("funds", "522_int_tr_accs_the_same"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                }
            }
        }

        if($getInfo->Type == '6'){
            $allow = (count((array)$traderLiveAccounts) > 0) ? true : false;
        }else{
            $allow = true;
        }

        $this->render('internalTransfer', array('Funds'=>$Funds, 'traderAccounts' => $Account->GetAccount(), 'Type' => $getInfo->Type, 'ibAccounts' => $Account->GetSysAccount(), 'allow'=>$allow, 'wlTradersAccsTable'=>$wlTradersAccsTable, 'paltforms'=>$paltforms, 'info' => $getInfo, 'Document'=>$Document));
    }

    public function actionSetBonus(){
        $this->pageTitle=Yii::t("sp","184_set_bonus");

        $this->breadcrumbs=array(
            Yii::t("sp","184_set_bonus"));

        $Account = new Account();
        $info = $Account->GetInfo();
        $FundServices = new FundServices('setBonus');

        if(Yii::app()->request->isAjaxRequest){
            $FundServices->attributes = (array)Yii::app()->request->getPost('FundServices');
            echo CActiveForm::validate($FundServices);
            Yii::app()->end();
        }

        if(Yii::app()->request->isPostRequest){
            $FundServices->attributes = (array)Yii::app()->request->getPost('FundServices');
            if($FundServices->validate()){
                $tmprez = stFunctions::sendMail('setBonus', array('trAccount' => $FundServices->trAccount, 'bonus' => $FundServices->bonus, 'lotsAmount'=>$FundServices->lotsAmount, 'adminEmail'=>Yii::app()->params['adminEmail'], 'name_company'=>Yii::app()->params['name_company'], 'operEmail'=>Yii::app()->params['operEmail']));
                if($tmprez[1]=='OK'){
                    $_SESSION['message'][] = array("text" => Yii::t("sp", "188_request_send"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                }else{
                    $_SESSION['message'][] = array("text" => Yii::t("main", "376_request_sending_error"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                }
            }
        }


        $this->render('setBonus',array('FundServices'=>$FundServices, 'info'=>$info));
    }

    public function actionWithdrawalStatuses(){
        $Funds = new FundServices('IntTrnsfr');
        $withTrs = $Funds->GetClientTransactions();
        //var_dump($withTrs);die();

        $this->render('withdrawalStatuses', array('withTrs'=>$withTrs));
    }

    public function actionAltDeposit(){
        $this->pageTitle = Yii::t("funds", "48_fund_deposits");

        //if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
        $Account = new Account();
        $traderAccounts = $Account->GetAccount();


        $trAccs = [''=>''];
        foreach($traderAccounts as $platforms){
            foreach($platforms as $pl){
                $trAccs[$pl->AccountNum] = $pl->Platform.' '.$pl->AccountNum;
            }
        }

        // }

        $this->breadcrumbs = array(
            Yii::t("funds","47_fund_services") => ('/funds/index.html'),
            Yii::t("funds", "48_fund_deposits"));

        $this->render('altDeposit', array('trAccs' => $trAccs));
    }

    public function actionHmDeposit()
    {
        $this->pageTitle = Yii::t("funds", "48_fund_deposits");

        $this->breadcrumbs = array(
            Yii::t("funds","47_fund_services") => ('/funds/index.html'),
            Yii::t("funds", "48_fund_deposits"));

        $homePay = new homePay();

        $Account = new Account();
        $traderAccounts = $Account->GetAccount();


        $trAccs = [''=>''];
        foreach($traderAccounts as $platforms){
            foreach($platforms as $pl){
                $trAccs[$pl->AccountNum] = $pl->Platform.' '.$pl->AccountNum;
            }
        }

        if (Yii::app()->request->isAjaxRequest){
            die('');
        }

        if(Yii::app()->request->isPostRequest){


            $post = Yii::app()->request->getPost('homePay');

            echo $homePay->wgCreateOrder($post);
        }


        $this->render('pwDeposit', array('homePay' => $homePay, 'trAccs' => $trAccs));
    }

    public function actionPaymentCards()
    {
        $this->layout = 'empty';
        $cardsShow = false;

        $Funds = new FundServices('cardDeposit');
        $Registration = new Registration('Individual');

        $CreditCard = new CreditCard();
        $Document = new Document('CreditCard');

        if (Yii::app()->request->isPostRequest) {
            $CreditCard->attributes = Yii::app()->request->getPost('CreditCard');
            $Document->attributes = $postDocument = Yii::app()->request->getPost('Document');
            // Document model in view must be call only "$Document"  ---  IMPORTANT!!!
            $docErrors = json_decode($Document->ajaxDocValidate($postDocument, $Document), true);
            $validateCards = json_decode(CActiveForm::validate($CreditCard), true);
        }

        if (Yii::app()->request->isAjaxRequest){

            echo json_encode(array_merge($docErrors, $validateCards));
            Yii::app()->end();
        }

        if (Yii::app()->request->isPostRequest) {
            if(isset($_POST["add_new_card_sbmt"]) || isset($_POST["edit_card_submit"])){
                /*$CreditCard->attributes = Yii::app()->request->getPost('CreditCard');
                $Document->attributes = $postDocument = Yii::app()->request->getPost('Document');*/


                if(isset($_POST["edit_card_submit"])){
                    $uploader = CUploadedFile::getInstances($Document, 'credit_card');

                    // todo COOKIE
                    $docIsEmpty = cookieDoc::isExist('credit_card') ? false : true;
                }

                if(empty($validateCards)){
                    if(isset($_POST["add_new_card_sbmt"]) && !isset($_POST['fromRedirectPage'])){
                        $card = $CreditCard->add();
                    }elseif(isset($_POST["edit_card_submit"])){
                        $CreditCard->update();
                        $new_cards = $CreditCard->init();
                        $card = (array)$new_cards[$CreditCard->Id];
                    }

                    if (is_array($postDocument) && (isset($_POST["add_new_card_sbmt"]) || (isset($_POST["edit_card_submit"]) && !$docIsEmpty))) {
                        $Document->postDocSave($postDocument, array('type'=>'credit_card', 'cardGuid'=>$card['Id']));
                    }
                }
            }
        }

        $cardsTable = $CreditCard->getCardsTable();
        $userCardsNum = $CreditCard->userCardsNum();
        $CreditCard->unsetAttributes();

        $countries = $Registration->GetCountry();


        $this->render('paymentCards', array('Funds'=>$Funds, 'CreditCard'=>$CreditCard, 'userCardsNum'=>$userCardsNum, 'cardsTable'=>$cardsTable, 'countries'=>$countries, 'Document'=>$Document, 'cardsShow'=>$cardsShow));
    }

    public function actionCryptoDeposit() {

        $this->render('cryptoDeposit', array('wallet'=>''));
    }
}


