<?php

class TraderController extends Controller {

    public $layout = 'column2';
    public $countRows = 25;
    public $mas_numb = array("25", "50", "100", "200");

    public function accessRules() {
        return array(
            array('allow', // allow trader user to perform actions
                'actions' => array('SetupInformation', 'SupportCenter','Documents', 'TraderAgreement', 'Platforms', 'Index', 'AccountList', 'Trade', 'ClosedSum', 'ClosedSumTrade', 'DeposWithdrawal', 'Summary', 'DwnlCsv', 'AccountRegistration', 'OpenLiveAccount', 'AgreementsWithBMFN', 'manual', 'OpenDemoAccount', 
				'Education', 'EducBooks', 'EducStrategies', 'EducTutorials', 'EducBeginner','EducTools'),
                'roles' => array('user6'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actions() {
        return array(
            // page action renders "static" pages stored under 'protected/views/trader/pages'
            // They can be accessed via: index.php?r=trader/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

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

    public function actionSetupInformation(){        
        $renders = array();
        $nextWindow = '';


        $account = new Account();
		$model_account = $account->GetAccount(array('live'));
        $info = $account->GetInfo();

        if($info->GroupType == 1){$GroupTypeStr = 'indv';
        }elseif($info->GroupType == 2){$GroupTypeStr = 'corp';
        }elseif($info->GroupType == 3){$GroupTypeStr = 'joint';  }
		
        if(count((array)$model_account)==0){
            $page_name = Yii::t("main", "181_open_live_account");
        }else{
            $page_name = Yii::t("trader", "29_trader_profile");
        }
        $this->pageTitle = $page_name;
        $this->breadcrumbs = array($page_name);
		
        //----------------------------------------------------------------------
        
        $Trader = new RegistrationTrader();//1-indiv 2-corp 3-join $info->GroupType
		
        $Partner_array = array();
        if($info->GroupType == 3){
            foreach ($Trader->initPartner() as $key => $partner) {
                $Partner_array[$key] = new RegistrationTrader('Join');
                $Partner_array[$key]->attributes = (array)$partner;
            }
            $renders['Partners'] = $Partner_array;
        }else{
            $Trader->initTrader();
        }
		//var_dump($Trader->attributes);die();
		$isQuestionnaire = false;
        /*if (($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') && isset($_GET['q'])) {
            $modelQuestionnairePep = new Questionnaire('pep');
            $Document = new Document($account->getTraderType($info->GroupType));
            $isQuestionnaire = false;
        }else*/if(wlParams::get('officeCode') == 22 && $isQuestionnaire == false){
			$modelQuestionnaire = new Questionnaire('setupInformation');
			$Document = new Document('noor_'.$account->getTraderType($info->GroupType));
			$isQuestionnaire = count($Document->isExist('QuestionnaireSetupInformation','QuestionnaireSetupInformation-1'))>0?true:false;
		}elseif((wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56) && $isQuestionnaire == false){
		    if($info->GroupType == 2){
		        $q_scenario = 'profile_au_corp';
            }else{
		        $q_scenario = 'profile_au_indv';
            }

			$modelQuestionnaire = new Questionnaire($q_scenario);

			$Document = new Document('au_'.$account->getTraderType($info->GroupType));
			$isQuestionnaire = count($Document->isExist('profileAdditionalInfo','profileAdditionalInfo-1'))>0?true:false;
		}elseif(wlParams::get('officeCode') == 14 || wlParams::get('officeCode') == 57){
			$Document = new Document('eu_'.$account->getTraderType($info->GroupType));
			/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
				var_dump('eu_'.$account->getTraderType($info->GroupType));die();
			} */
		}else{
			$Document = new Document($account->getTraderType($info->GroupType));
		} 
        
        $Registration = new Registration();
        $country = $Registration->GetCountry('none', true);
        $approve = $Registration->IsApprove();
		$renders['trader_agreement'] = $trader_agreement = wlParams::get('trader_agreement');
		
		$LoginForm = new LoginForm('password_set');




		$trader_agreement_file = $renders['trader_agreement_file'] = array();
		$isExist = $Document->isExist('trader_agreement');
		if(count($isExist) > 0 ){
			$trader_agreement_file = $renders['trader_agreement_file'] = $Document->isExist('trader_agreement');
		}
		
        if (Yii::app()->request->isAjaxRequest){
           
            
            if (isset($_POST['sendRequest'])) {
                    $res = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Mail/ChangeInfoMail?guid=' . Yii::app()->user->id . '&userID=' . $info->ID . '&fieldName=' . $_POST['name']. '&fieldValue=' . $_POST['value']);
                    //var_dump($res, Yii::app()->params['json_server'] . '/API/Mail/ChangeInfoMail?guid=' . Yii::app()->user->id . '&userID=' . $info->ID . '&fieldName=' . $_POST['name']. '&fieldValue=' . $_POST['value']);
                    if($res === 'OK') {echo '1';}
                    Yii::app()->end();
            }
            if (isset($_POST['RemovePartner'])) {
                if (isset($_POST['partnerId']) && count($Partner_array)>1){
                    $t = $Trader->remove($_POST['partnerId']);
                    if(isset($t->State) && $t->State == 0){
                            echo 'removed';
                    }
                    Yii::app()->end();
                }
            }
            if (isset($_POST['checkLastPartner'])){
                $tradersTmp = Yii::app()->request->getPost('RegistrationTrader');
                $traders = array();
                foreach($tradersTmp as $key=>$trader){
                    if(is_array($trader)){
                            $traders[$key] = $trader;
                    }
                }
                $last = array_pop($traders);
                $lastPartner = new RegistrationTrader('lastPartner');
                $lastPartner->attributes = $last;
                $lastPartnerValidate = CActiveForm::validate($lastPartner);
                if ($lastPartnerValidate != '[]') {
                    echo $lastPartnerValidate;
                    Yii::app()->end();
                }
                Yii::app()->end();
            }
			
            if (isset($_POST['addPartner'])){				
				$TraderJ = new RegistrationTrader('Partner');
				//var_dump($TraderJ->getScenario());die();
                preg_match('/.*\[(.*)\]$/', $_POST['name'], $name);
                if ($name[1]){
                    $tmp[$name[1]] = $_POST['value'];
                    $TraderJ->attributes = $tmp;
				//	$TraderJ->validate(array_keys($tmp));
				//	var_dump($TraderJ->getErrors()); 
				//		var_dump($TraderJ->getScenario(), array_keys($tmp), $TraderJ->rules());die();
                    $partnerFieldValidate = CActiveForm::validate($TraderJ, array_keys($tmp));
					//	var_dump(array_keys($tmp), $partnerFieldValidate);die();
                    if ($partnerFieldValidate != '[]') {
                        echo $partnerFieldValidate;
                        Yii::app()->end();
                    } else {
                        echo json_encode($_POST['name']);
                        Yii::app()->end();
                    }
                }
                Yii::app()->end();
            }
            
			
            $newValidatePartner = $validatePartner = $validateTrader = $docErrors = $validateQuestionnaire = $validateLoginForm = array();
            
			if($approve == 0){
				$pass_post = Yii::app()->request->getPost('LoginForm');
				$LoginForm->attributes = $pass_post;
				$validateLoginForm = json_decode(CActiveForm::validate($LoginForm));
			}
            
            if((wlParams::get('officeCode') == 22 || wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56 /*|| (($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') && isset($_GET['q']))*/) && $isQuestionnaire == false){
                $questErrorsTmp = array();
                if(isset($modelQuestionnaire)){
                    $modelQuestionnaire->attributes = Yii::app()->request->getPost('Questionnaire');
                    $questErrorsTmp = json_decode(CActiveForm::validate($modelQuestionnaire), true);
                }

                /*if (($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') && isset($_GET['q'])) {
                    $modelQuestionnairePep->attributes = Yii::app()->request->getPost('Questionnaire');
                    $questErrorsTmpPep = json_decode(CActiveForm::validate($modelQuestionnairePep), true);
                    $questErrorsTmp = array_merge($questErrorsTmp, $questErrorsTmpPep);
                }*/
                $validateQuestionnaire = $questErrorsTmp;
            }
            
            if($info->GroupType == 3){
                $par_post = Yii::app()->request->getPost('RegistrationTrader');
				$agreeKey = '';

                foreach ($par_post as $key => $par_model){
					if(is_array($par_model)){
						if(!strstr($key, '+')){
							$Partner_array[$key]['id'] = $key;
							$Partner_array[$key]->attributes = (array)$par_post[$key];
							//var_dump($Partner_array[$key]->attributes);
							$validatePartnerEr = CActiveForm::validate($Partner_array[$key]);
							//var_dump($validatePartner);
							if ($validatePartnerEr != '[]'){
								$tempary = json_decode($validatePartnerEr, true);
								$rez = array();
								foreach ($tempary as $k => $tmp) {
									$tmpnames = explode('_', $k);
									$name = $tmpnames[0] . '_' . $key . '_' . $tmpnames[1];
									$rez[$name] = $tmp;
								}
								//var_dump($validatePartnerEr);die();
								$validatePartner = array_merge($validatePartner, $rez);
								
								//$validatePartner = json_encode($rez);
								//echo $validatePartner;
								//Yii::app()->end();
							}/* else{
								Yii::app()->end();
							} */ 
						}else{
							$newTrader = new RegistrationTrader();
							$newTrader->attributes = $par_model;
							$newTrader->agree = '1';
							$validatePartnerEr = CActiveForm::validate($newTrader);
							if ($validatePartnerEr != '[]'){
								$newValidatePartner = array();
								foreach(json_decode($validatePartnerEr) as $errkey=>$error){
									$errkey = str_replace('_','_'.str_replace('+','',$key).'_',$errkey);
									$newValidatePartner[$errkey] = $error;
								}
								$newValidatePartner['new_user_error']=1;
								//echo json_encode($newValidatePartner); 
								//Yii::app()->end();
							}
						}
					}
                }
				
				$Trader->attributes = $_REQUEST;
				$Trader->agree = (empty($trader_agreement_file)) ? '0' : $Trader->agree;
				$validateTrader = CActiveForm::validate($Trader, array('agree', 'additionalInfo'));
				//var_dump($Trader->attributes, $validateTrader, $Trader->getValidators('additionalInfo'));die();
				//$validateTrader = json_decode($validateTrader);
            }else{
				$Trader->attributes = $_REQUEST;
				$validateTrader = CActiveForm::validate($Trader);
				//$validateTrader = json_decode($validateTrader);
			}
			$validateTrader = json_decode($validateTrader);
			
			//var_dump($Document->isExist('trader_agreement'), $Trader->agree==1, $trader_agreement_file, $validateTrader);die();
			
			$trAgree = $Document->isExist('trader_agreement');
			if(empty($trader_agreement) && in_array($GroupTypeStr,  wlParams::get('trader_agreement_show')) && $Trader->agree==0 && (!empty($trader_agreement_file) || ($info->GroupType == 3 && isset($_SESSION['signs']) && !empty($_SESSION['signs'])) || (is_string($trAgree) && $trAgree == 'FileIsInProgress'))){
				$Trader->agree = 1;
				//$Trader->agree($Trader->id, $Trader->agree);
				unset($validateTrader->RegistrationTrader_agree);
			}elseif($Trader->agree==1 && (!empty($trader_agreement_file) || ($info->GroupType == 3 && isset($_SESSION['signs']) && !empty($_SESSION['signs'])))){
				unset($validateTrader->RegistrationTrader_agree); 
			}
			
			
			$Document->attributes = $postDocs = Yii::app()->request->getPost('Document');


            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if (wlParams::get('officeCode') === 28) { // eforex hot doc fix

            }else{*/
                // Document model in view must be call only "$Document"  ---  IMPORTANT!!!
                $docErrors = $Document->ajaxDocValidate($postDocs, $Document);
                if(!empty($docErrors)){
                    //echo $docErrors;
                    //Yii::app()->end();
                }
                //var_dump($docErrors);die();
                if(is_string($docErrors)){
                    $docErrors = json_decode($docErrors);
                }
            //}

			$errors = json_encode(array_merge((array)$newValidatePartner, (array)$validatePartner, (array)$validateTrader, (array)$docErrors, (array)$validateQuestionnaire, (array)$validateLoginForm));
			//var_dump($errors);die();

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

			echo $errors; 
			
				
            Yii::app()->end();
        }

        if (Yii::app()->request->isPostRequest){ 
            $validateTraderErrors = $Trader->getErrors();

            if(empty($trader_agreement) && in_array($GroupTypeStr,  wlParams::get('trader_agreement_show')) && !empty($trader_agreement_file) && $Trader->agree==0){
                    $Trader->agree = 1;
                    $Trader->agree($Trader->id, $Trader->agree);
                    unset($validateTraderErrors['agree']);
            }elseif($Trader->agree==1 && !empty($trader_agreement_file)){
                    unset($validateTraderErrors['agree']);
            }

           /*  if (empty($validateTraderErrors)){
				$Trader->update();
            } */


            $Document->attributes = $post = Yii::app()->request->getPost('Document');
            
			if($post){
				$name_for_op = '';
				if (is_array($post)){
					$params = ($approve==3) ?  array('nameForOp'=>true) : array();
					$out = $Document->postDocSave($post, $params);
					if(!empty($out) && isset($out['name_for_op'])){
						$name_for_op = implode(', ',$out['name_for_op']);
					}				
				}
			}
			

            if (($approve == 3) && !empty($name_for_op)){
                Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Mail/ChangeFileMail?guid=' . Yii::app()->user->id . '&userID=' . $info->ID . '&fileName=' . $name_for_op);
            }
            
            $post = Yii::app()->request->getPost('RegistrationTrader');
			$trAgree = $Document->isExist('trader_agreement');
			if($info->GroupType != 3){
				$Trader->attributes = $post;
				$traderValidate = $Trader->validate();
				
				$validateTraderErrors = $Trader->getErrors();
				/* var_dump(empty($trader_agreement), in_array($GroupTypeStr,  wlParams::get('trader_agreement_show')), !empty($trader_agreement_file), $Trader->agree==0,  $files);die(); */
				// || (is_string($trAgree) && $trAgree == 'FileIsInProgress')
				
				/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
						var_dump(empty($trader_agreement), in_array($GroupTypeStr,  wlParams::get('trader_agreement_show')), (!empty($trader_agreement_file) || (is_string($trAgree) && $trAgree == 'FileIsInProgress')), $Trader->agree==0);die();
					} */
				
				
				if(empty($trader_agreement) && in_array($GroupTypeStr,  wlParams::get('trader_agreement_show')) && (!empty($trader_agreement_file) || (is_string($trAgree) && $trAgree == 'FileIsInProgress')) && $Trader->agree==0){
					$Trader->agree = 1;
					$Trader->agree($Trader->id, $Trader->agree);
					unset($validateTraderErrors['agree']);
				}elseif(!empty($trader_agreement) && empty($Trader->agree)){
					$Trader->agree = 1;
					$Trader->agree($Trader->id, $Trader->agree);
					unset($validateTraderErrors['agree']);
				}elseif($Trader->agree==1 && !empty($trader_agreement_file)){
					unset($validateTraderErrors['agree']);
				}
				
				if (empty($validateTraderErrors)){
					$Trader->update();
				}
			}else{
				if(is_array($post)){
					$c = 0;
					$DocumentSign = new Document();				
					foreach($post as $key=>$partner){
						if(is_array($partner)){
							$partner['id'] = $key;
							$Trader->attributes = $partner;	
						//	$Trader->id = $key;
							$Trader->validate(array_keys($partner));
							
							//var_dump($Trader->validate(array_keys($partner)));die();
							
							
							$validateTraderErrors = $Trader->getErrors();
							//var_dump(empty($trader_agreement), in_array($GroupTypeStr,  wlParams::get('trader_agreement_show')), !empty($trader_agreement_file));die();
							if(empty($trader_agreement) && in_array($GroupTypeStr,  wlParams::get('trader_agreement_show'))&& $Trader->agree==0 && (!empty($trader_agreement_file) || (wlParams::get('jointTraderAgreeMultyEchoSign') && isset($_SESSION['signs'])) || (is_string($trAgree) && $trAgree == 'FileIsInProgress'))){
								if(wlParams::get('jointTraderAgreeMultyEchoSign')){
									$Trader->agree = 0;
									if(isset($_SESSION['signs'][$c]) && !empty($_SESSION['signs'][$c])){
										$Trader->sign = $_SESSION['signs'][$c]["sign"];
										$Trader->date = $_SESSION['signs'][$c]["date"];
										$Trader->signName = $_SESSION['signs'][$c]["name"];
									}
								}else{
									$Trader->agree = 1;
									$Trader->agree($Trader->id, $Trader->agree);
									unset($validateTraderErrors['agree']);
								}
							}elseif($Trader->agree==1 && !empty($trader_agreement_file)){
								unset($validateTraderErrors['agree']);
							}
							
							if(empty($validateTraderErrors) || strstr($partner['id'], '+')){
								//var_dump($Trader->attributes, $_POST);die();
								$answr = $Trader->update();
								$isExistJointSign = $DocumentSign->isExist('jointSigns', 'jointSigns_'.$answr[0]);
								if(is_array($answr) && isset($answr[0]) && is_int($answr[0]) && isset($_SESSION['signs'][$c]["es_img"]) && !empty($_SESSION['signs'][$c]["es_img"]) && empty($isExistJointSign)){							
									if(wlParams::get('jointTraderAgreeMultyEchoSign')){
										$ownerId = $answr[0];
										//var_dump($_SESSION['signs'][$c]["es_img"]);die();
										$img = file_get_contents($_SESSION['signs'][$c]["es_img"]);
										$fileName = 'jointSigns_'.$ownerId.'.png';
										file_put_contents($_SERVER["DOCUMENT_ROOT"] . '/protected/runtime/documents/' . $fileName, $img);
										$DocumentSign->send($fileName, 'jointSigns', $ownerId);
									}
								}
							}
							$c++;
						}
					}
				}
				foreach ($Trader->initPartner() as $key => $partner) {
					$Partner_array[$key] = new RegistrationTrader();
					$Partner_array[$key]->attributes = (array) $partner;
				}
				$renders['Partners'] = $Partner_array;
			}
			if($info->GroupType == 3){
				$tmpPartners = $Trader->initPartner();	
				$partnersCount = count($tmpPartners);
				$tragree = current($tmpPartners);
				if($Trader->checkJointSigns()){
					/********* for old echoSign scheme *********/
					/* 

					$post['name'] = 'trader_agreement';
					$post['formData'] = $_SESSION['formData'];
					$post['html'] = 'joint';
					$post['curl'] = '1';
					$post['sign'] = '<img class="echo_sign_img eSign_result" style="" src="pc.bostonunisoft.com/img/logo.png">';
					$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
					$signResult = Yii::app()->curl->post_self($http.'//'.$_SERVER['SERVER_NAME'].'/pdf/echoSign.pdf', $post);
					if($signResult == 'docSaved'){
						foreach($tmpPartners as $key=>$tmpP){
							$Trader->agree($tmpP->id, 1);
						}
						$tragree->agree = 1;
					}
					*/
					/*****************************************/
					
					
					/***** for new echoSign sheme ******/			
					$echoSignM = new echoSignM();
					$http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
					$host = $http.'//'.$_SERVER['HTTP_HOST'];
					$url = $host.'/pdf/syncPdfGenerator.pdf';
					
					if(isset($_SESSION['formData'])){   // mb remove
						$formData = array();
						foreach($_SESSION['formData'] as $k=>$data){
							preg_match('/^.+\[(.+)\].*$/', $data['name'], $matches);
							if(isset($matches[1]) && $matches[1] == 'es_img'){continue;}
							$attributeKey = isset($matches[1]) ? $matches[1] : $data['name'];
							$formData[$attributeKey] = $data['value'];
						}
					}
					
					if(wlParams::get('jointTraderAgreeMultyEchoSign')){
						if(isset($_SESSION['signs'])){
							$formData = array();
							foreach($_SESSION['signs'] as $k=>$data){
                                $formDataTmp  = array('name'=>$data['name'], 'sign'=>$data['sign']);
                                if(isset($data['pep'])){
                                    $formDataTmp['pep'] = $data['pep'];
                                }
                                if(isset($data["sourceOfFunds"])){
                                    if($data["sourceOfFunds"] == 'Other' && (isset($data["sourceOfFundsOther"]))){
                                        $formDataTmp['sourceOfFunds'] = $data["sourceOfFundsOther"];
                                    }else{
                                        $formDataTmp['sourceOfFunds'] = $data['sourceOfFunds'];
                                    }
                                }
								$formData[] = $formDataTmp;
							}
						}
					}
					
					
					$string4request = array('fileName'=>'trader_agreement', 'host'=>$host, 'partnerCount'=>$partnersCount, 'formData'=>$formData);
					
					$tmpRez = $echoSignM->sendEchoRequest($DocumentSign->getFileType('trader_agreement'), json_encode($string4request), $url);
					if(isset($tmpRez->State) && $tmpRez->State == 0){
						foreach($tmpPartners as $key=>$tmpP){
							$Trader->agree($tmpP->id, 1);
						}
						$tragree->agree = 1;
						
					}
					/***********************************/
				} 
				$tragree = $tragree->agree;		
			}else{
				$Trader->initTrader();	
				$tragree = $Trader->agree;
			}
			$tragree = (!empty($trader_agreement)) ? 1 : $tragree;
			
			if($approve == 0){
				$pass_post = Yii::app()->request->getPost('LoginForm');
				$LoginForm->attributes = $pass_post;
				if($LoginForm->validate() && $LoginForm->password != ''){
					$change = $LoginForm->changePassword($info->ID, $LoginForm->password);
					/* if($change){
						$_SESSION['message'][] = array("text" => Yii::t("main", "512_password_changed_and_send"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
					} */
				}
			}

            if(
                // eforex hot doc fix - add office code if
                (((count($Document->isExist('passport')) > 0 /*|| wlParams::get('officeCode') === 28*/) && $info->GroupType != 2) || ($info->GroupType == 2 && count($Document->isExist('passportCorp')) > 0 && count($Document->isExist('passportUser')) > 0))
                && ($approve == 0)
                && ($tragree == 1 || ($info->GroupType == 3 && (wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56)))
            ) {
                if((wlParams::get('officeCode') == 22 || wlParams::get('officeCode') == 13  || wlParams::get('officeCode') == 56 /*|| (($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') && isset($_GET['q']))*/) && $isQuestionnaire == false){
                    if(isset($modelQuestionnaire)){
                        $modelQuestionnaire->attributes = Yii::app()->request->getPost('Questionnaire');

                        if ($modelQuestionnaire->validate()){
                            $modelQuestionnaire->save();
                        }
                    }
                }
				
				//update
            
                $Registration->sendApprove();
                $approve = $Registration->IsApprove();
				//var_dump($approve);die();
                $this->redirect('/trader/openLiveAccount.html');
            }elseif(count((array)$model_account)==0 && ($approve == 1 || $approve == 3)){
                $this->redirect('/trader/openLiveAccount.html');
            }

            if ($approve == 2) {
                $Registration->sendApprove();
            }
        }

        if(!isset($_SESSION['isApp']) || $_SESSION['isApp'] === false) {
            if ($approve == 3) {
                //$_SESSION['message'][] = array("text" => Yii::t("main", "165_your_application_was_approved_youve_filled_all_n"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
            } elseif ($approve == 1) {
                //$_SESSION['message'][] = array("text" => Yii::t("main", "575_you_can_edit_info_after"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
                //$_SESSION['message'][] = array("text" => Yii::t("main", "56_you_have_already_filled_in_all_fields_and_uploaded"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
            } elseif ($approve == 0 && count($Document->isExist('passport')) > 0 && $Trader->agree == 0) { // заполнили все поля, подпишите агримент
                $_SESSION['message'][] = array("text" => Yii::t("main", "440_filed_all_fields_please_seign_in_agreement"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
            } elseif ($approve == 0) {
                $_SESSION['message'][] = array("text" => Yii::t("main", "572_openliveacc_step1_warning"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
            }
        }
		
		$renders['trader_agreement_file'] = array();
		if(count($Document->isExist('trader_agreement')) > 0 ){
			$renders['trader_agreement_file'] = $Document->isExist('trader_agreement');
		}
		$showSetPass = ($approve == 0) ? true : false;

		$Trader->initTrader();

        $renders['country'] = $country;
        $renders['Trader'] = $Trader;
        $renders['showSetPass'] = Yii::app()->params['pass_on_reg'] ? false : $showSetPass;
        $renders['LoginForm'] = ($approve == 0) ? $LoginForm : '';
        $renders['Document'] = $Document;
        $renders['approve'] = $approve;
        $renders['model_account'] = $model_account;

        if((wlParams::get('officeCode') == 32 || Yii::app()->params['type'] == 'eforex') && $renders['Trader']->country != 'Pakistan'){
            unset($renders['country']['Pakistan']);
        }

        if(in_array(wlParams::get('officeCode'), [19,30,32,53,54,5])){
            unset($renders['country']['Russia']);
        }

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

		$profileDocs=array();
		foreach(wlParams::get('profile_docs') as $docname){
            $url= wlParams::get('docsFolderServer')."/".$docid."/".Yii::app()->language."/".$docname.'.pdf';
            /*if ($_SERVER['REMOTE_ADDR'] == '91.243.198.104') {
                var_dump('999', $url);die();
            }*/
            $Headers = @get_headers($url);
            if(substr_count($Headers[0], '200')>0) { $profileDocs[$docname]= $url;} else { $profileDocs[$docname] = wlParams::get('docsFolderServer')."/".$docid."/en/".$docname.'.pdf';}
		}
		$renders['docsUrl'] = wlParams::get('docsFolderServer')."/".$docid."/en/";
		if((wlParams::get('officeCode') == 22 || wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56) && $isQuestionnaire == false){
			$renders['modelQuestionnaire'] = $modelQuestionnaire;
			//$renders['questionare'] = $url = wlParams::get('docsFolderServer')."/".$docid."/".Yii::app()->language."/ClientQuestionare.pdf";
		}

		if(isset($modelQuestionnairePep)){
            $renders['modelQuestionnairePep'] = $modelQuestionnairePep;
        }
        
		$renders['isQuestionnaire']=$isQuestionnaire;
		$renders['profileDocs']=$profileDocs;
		$renders['Login']=$info->Login;

        $this->render('setupInformation'.$account->getTraderType($info->GroupType), $renders);
    }

    public function actionTraderAgreement() {
        $this->pageTitle = Yii::t("trader", "41_trader_agreement");
        $this->breadcrumbs = array(Yii::t("trader", "41_trader_agreement"));

        $status = array();
        $status['approve'] = 0;

        $registration = new Registration();
        $status['approve'] = $registration->IsApprove();

        $this->render('traderAgreement', array('status' => $status));
    }

    
    
    public function actionSupportCenter() {
        $this->pageTitle = Yii::t("trader", "65_Support_Center");
        $this->breadcrumbs = array(Yii::t("trader", "65_Support_Center"));

        $this->render('platforms', array());
    }
    
    public function actionPlatforms() {
        $this->pageTitle = Yii::t("trader", "17_trader_platforms");
        $this->breadcrumbs = array(Yii::t("trader", "17_trader_platforms"));

        $this->render('platforms', array());
    }

    public function actionIndex() {
        $this->pageTitle = Yii::t("trader", "16_traders_report");
        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report"));
		
		$view=new Account();
		$model_live_account=$view->GetAccount(array('live')); 
		$parInfo = $view->getParentContacts();
		$officeCode = $view->GetUserOfficeShortCode();
		$allow = (count((array)$model_live_account) > 0) ? true : false;
		
		
        $this->render('index', array('allow'=>$allow, 'parentCode'=>$parInfo['Code'], 'officeCode'=>$officeCode));
    }

    public function actionAccountList() {

        $this->pageTitle = Yii::t("main", Yii::t("main", "91_account_list_report"));

        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report") => array('/trader/'),
            Yii::t("main", "91_account_list_report"));

        $link_error = null;

        $repor = new Report(3);
        $repor->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
        $repor->accountType = isset($_REQUEST['accountType'])?$_REQUEST['accountType']:0;
        $table = $repor->GetDataTable();
        $pagination = $repor->GetPagination();
        $count = $repor->GetCount();
        //$link_error = $repor->GetLinkCsvError();
        $itemsOnPage = $repor->GetRowsTable(); ###



        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$Account=new Account();
		$model_live_account=$Account->GetAccount(array('live')); 
		$allow = (count((array)$model_live_account) > 0) ? true : false;

        $this->render('accountList', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'allow'=>$allow));
    }

//Trade report
    public function actionTrade() {

        $this->pageTitle = Yii::t("trader","48_trade_report");

        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report") => array('/trader/'),
            Yii::t("trader","48_trade_report"));
        $link_error = null;



        if (Yii::app()->request->getPost('group') || Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report')) {
            $repor = new Report(1);
            $repor->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $itemsOnPage = $repor->GetRowsTable(); ### 
            $table = $repor->GetDataTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            $link_error = $repor->GetLinkCsvError();
        } else {
            $accaunt = new Account();
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableUsers();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }
        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count)));
        }
        $view = new Platform();

		$Account=new Account();
		$model_live_account=$Account->GetAccount(array('live')); 
		$allow = (count((array)$model_live_account) > 0) ? true : false;

        $this->render('trade', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'allow'=>$allow));
    }

    //Close Trader report
//Closed Trades Report
    public function actionClosedSum() {

        $this->pageTitle = Yii::t("main", "95_closed_trades_report");

        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report") => array('/trader/'),
            Yii::t("main", "95_closed_trades_report"));
        $link_error = null;



        if (Yii::app()->request->getPost('group') || Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report')) {
            $repor = new Report(2);
            $repor->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $itemsOnPage = $repor->GetRowsTable(); ###
            $table = $repor->GetDataTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            $link_error = $repor->GetLinkCsvError();
        } else {
            $accaunt = new Account();
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableUsers();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }

        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$Account=new Account();
		$model_live_account=$Account->GetAccount(array('live')); 
		$allow = (count((array)$model_live_account) > 0) ? true : false;

        $date_utc = new DateTime(null, new DateTimeZone("UTC"));
        date_add($date_utc, date_interval_create_from_date_string('2 hours'));
        $now = date_format($date_utc, 'm/d/Y');

        $this->render('closedSum', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'allow'=>$allow, 'now'=>$now));
    }

    #-------------------------------------------------		// Close trade summary report

    public function actionClosedSumTrade() {

        $this->pageTitle = Yii::t("main", "97_close_trade_summary_report");

        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report") => array('/trader/'),
            Yii::t("main", "97_close_trade_summary_report"));
        $link_error = null;

        if (Yii::app()->request->getPost('group') || Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report')) {
            $repor = new Report(7);
            $repor->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $itemsOnPage = $repor->GetRowsTable(); ###
            $table = $repor->GetDataTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            $link_error = $repor->GetLinkCsvError();
        } else {
            $accaunt = new Account();
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableUsers();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }
        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$Account=new Account();
		$model_live_account=$Account->GetAccount(array('live')); 
		$allow = (count((array)$model_live_account) > 0) ? true : false;

        $date_utc = new DateTime(null, new DateTimeZone("UTC"));
        date_add($date_utc, date_interval_create_from_date_string('2 hours'));
        $now = date_format($date_utc, 'm/d/Y');

        $this->render('closed-trade-sum', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'allow'=>$allow, 'now'=>$now));
    }

    public function actionDeposWithdrawal() {
        $this->pageTitle = Yii::t("main", "99_depositwithdrawal_report");

        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report") => array('/trader/'),
            Yii::t("main", "99_depositwithdrawal_report"));
        $link_error = null;
        $transaction_type = '';
        if (isset($_POST["transaction_type"])) {
            $transaction_type = $_POST["transaction_type"];
        }

        if (Yii::app()->request->getPost('group') || Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report')) {
            $repor = new Report(4);
            $repor->attributes = $_REQUEST;   //if($repor->validate()){ //  запись отловить ошибки и в логи//  }
            $itemsOnPage = $repor->GetRowsTable(); ###
            $table = $repor->GetDataTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            $link_error = $repor->GetLinkCsvError();
        } else {
            $accaunt = new Account();
            $accaunt->attributes = $_REQUEST; //if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableUsers();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }

        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$Account=new Account();
		$model_live_account=$Account->GetAccount(array('live')); 
		$allow = (count((array)$model_live_account) > 0) ? true : false;

        $date_utc = new DateTime(null, new DateTimeZone("UTC"));
        date_add($date_utc, date_interval_create_from_date_string('2 hours'));
        $now = date_format($date_utc, 'm/d/Y');

        $this->render('deposWithdrawal', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'transaction_type' => $transaction_type, 'allow'=>$allow, 'now'=>$now));
    }

    public function actionSummary() {
        $this->pageTitle = Yii::t("main", "101_summary_report");

        $this->breadcrumbs = array(
            Yii::t("trader", "16_traders_report") => array('/trader/'),
            Yii::t("main", "101_summary_report"));
        $link_error = null;

        if (Yii::app()->request->getPost('group') || Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report')) {
            $repor = new Report(5);
            $repor->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $itemsOnPage = $repor->GetRowsTable(); ###
            $table = $repor->GetDataTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            $link_error = $repor->GetLinkCsvError();
        } else {
            $accaunt = new Account();
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableUsers();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }

        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();

		$Account=new Account();
		$model_live_account=$Account->GetAccount(array('live')); 
		$allow = (count((array)$model_live_account) > 0) ? true : false;

        $date_utc = new DateTime(null, new DateTimeZone("UTC"));
        date_add($date_utc, date_interval_create_from_date_string('2 hours'));
        $now = date_format($date_utc, 'm/d/Y');

        $this->render('summary', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'allow'=>$allow, 'now'=>$now));
    }

    /*
     * ***csv
     */

    public function actionDwnlCsv() {
        $repor = new Report($_GET['rp']);
        $repor->attributes = $_REQUEST;
        $link = $repor->GetLinkCsv();

        /* if ($repor->GetLinkCsvError() == "ReportIsEmpty" || is_array($repor->GetLinkCsvError()))
            exit('ReportIsEmpty'); */

		if($repor->GetLinkCsvError() != "ReportIsEmpty"){
			Yii::app()->getController()->redirect($link);
		}else{
            exit('ReportIsEmpty');		
		}
			
		
       // $this->render('dwnl_csv', array('link' => $link));
    }

    public function actionAccountRegistration() {
        $this->pageTitle = Yii::t("main", "182_account_registration");
        $this->breadcrumbs = array(Yii::t("main", "182_account_registration"));
        $account = new Account();
        $info = $account->GetInfo();

        $status = array();
        $status['approve'] = 0;
        $registr = new Registration;
        $status['approve'] = $registr->IsApprove();


        $ScheduleIs = $registr->GetSchedule('-1', 'true');

        if ($status != 3) {
            $_SESSION['message'][] = array("text" => Yii::t("main", "161_this_page_will_be_available_after_activating_your_"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
        }

        $this->render('accountRegistration', array('info' => $info, 'ScheduleIs' => $ScheduleIs, 'status' => $status));
    }

    public function actionOpenLiveAccount(){
        
        $this->pageTitle = Yii::t("main", "181_open_live_account");
        $this->breadcrumbs = array(
            // 'Account Registration' => ('/trader/account-registration.html'),
            Yii::t("main", "181_open_live_account"));

        $Platform = new Platform();

        $account = new Account();
        $info = $account->GetAccount(array('live'));
        $acc_info = $user_info = $account->GetInfo();

        ///////////
        $Reg = new Registration();
        $demo_user_attrs = array();
        if ($user_info->Type == 6) {
            $Trader = new RegistrationTrader();
            $Trader->initTrader();
            $demo_user_attrs = $Trader->attributes;
        } elseif ($user_info->Type == 4) {
            $Reg->initIndv();
            $demo_user_attrs = $Reg->attributes;
        }
        $country = $Reg->GetCountry('three');
        $demo_user_attrs['phone'] = str_replace(array('+', ')', '(', ' ', '-'), '', $demo_user_attrs['phone']);
        $demo_user_attrs['country3code'] = $country[$demo_user_attrs['country']];
        $demo_user_attrs['city'] = (empty($demo_user_attrs['city'])) ? 'city' : $demo_user_attrs['city'];
        $demo_user_attrs['address'] = (empty($demo_user_attrs['address'])) ? 'address' : $demo_user_attrs['address'];
        $demo_user_attrs['gender'] = (empty($demo_user_attrs['gender'])) ? '2' : $demo_user_attrs['gender'];

        ///////////

        $platfAmount = array();

        foreach ($info as $key => $value) {
            $platfAmount[$key] = count($value);
        }
        $isEmailSend = false;
        $mas = array();
        $status = array();
        $status['approve'] = 0;
        $reg = new Registration;
        $status['approve'] = $reg->IsApprove();

        /*if(Yii::app()->params['styles_type'] === 'new' && $status['approve'] === 0){
            $this->redirect('/trader/setupInformation.html');
        }*/

        $reg->initIndv();

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

        $ScheduleIs = $reg->GetSchedule('-1', 'true', '1');
        $Schedule = $reg->GetSchedule('-1', 'false', '1');

        /*$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($ScheduleIs);die();
        }*/
		
		/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
			var_dump($ScheduleIs);die();
		} */

        if (Yii::app()->request->isAjaxRequest){
			$reg->parentId = Yii::app()->request->getPost('parentId');
			
			if($reg->validate()){
				
				if (isset($_POST['platform'])){
					$post = Yii::app()->request->getPost('platform');
					$post = substr($post, 0, (strlen($post) - 1));
					$pl = explode(",", $post);
					$id_pltfrms = $session_id = '';
					foreach ($pl as $elem) {
						if (strstr($elem, '_')) {
							$tmp = explode('_', $elem);
							$id_pltfrms .= '/' . $tmp[0];
							$session_id = $tmp[1];
						}
					}


					foreach ($pl as $k => $v) {
						if (!strstr($v, '_') || strstr($v, '|')) { // mt live - Sonin
							if (!empty($v)) {
								$platon = new Platform();
								$plaformLinckArr = $platon->GetLinksForUser();
								$platformList = !empty($ScheduleIs) ? $ScheduleIs : $Schedule;

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

                                $v_id = $v;


								if (is_array($platformList)) {
									foreach ($platformList as $value) {
                                            if(strstr($v, '|')){
                                                $tmp = explode('|', $v);
                                                $platformLinck = $plaformLinckArr->$tmp[0];
                                                $reg->accountGroup = $tmp[1];
                                                $v_id = $tmp[0];
                                            }else{
                                                $platformLinck = $plaformLinckArr->$v;
                                            }

											$platform = $value->Name;

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


                                            if (isset($_POST['MobileDevice']) && $_POST['MobileDevice'] == 'Android') {
                                                $platformLinck = (string)$platformLinck[1]->link;
                                            } elseif (isset($_POST['MobileDevice']) && $_POST['MobileDevice'] == 'iOS') {
                                                $platformLinck = (string)$platformLinck[2]->link;
                                            } else {
                                                $platformLinck = (string)$platformLinck[0]->link;
                                            }
                                        }
										//}
									}
								}



								$tmp = $reg->regNewAccount($v_id);
								//$tmp = 'BrokerForUserDoesntExist';
								//ScheduleForUserDoesntExist
								if($tmp == 'BrokerForUserDoesntExist'){ 
									echo json_encode(array('errorIBcode'=>Yii::t("main","923_ib_with_code_doesnt_exist", array('{code}'=>$reg->parentId))));
									Yii::app()->end();
								}elseif($tmp == 'ScheduleForUserDoesntExist'){ 
									echo json_encode(array('errorIBcode'=>Yii::t("main","932_platform_doesnt_exist")));
									Yii::app()->end();
								}else{
                                    $ipx = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];


									$mas[] = $tmp . '|' . $platform . '|' . $platformLinck;
									$pieces = explode("|", $mas[0]);
									$acc_info = $account->GetInfo(true);
								}
							}
						}
					}
					if (!empty($mas)){
						if (is_array($mas) && is_string($mas[0]) && strstr($mas[0], 'WrongScheduleNameForUser') || (is_string($mas) && strstr($mas, 'WrongScheduleNameForUser'))) {
							$_SESSION['message'][] = array("text" => Yii::t("main", "447_open_live_acc_erro"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
							echo 'error';
							Yii::app()->end();
						}
					}
					
					$mas = json_encode(array('mas' => $mas));
					
					$account->SendOpenAccMail($reg->email, $mas, $pieces[0]);
					//Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Mail/SendOpenAccMail?guid=' . Yii::app()->user->id . '&email=' . $reg->email . '&json=' . $mas);
				}
				exit($mas);
			}else{
				//var_dump($reg->attributes, $reg->getErrors());die();
				$parErrors = $reg->getErrors('parentId');
				echo json_encode(array('parentIdError'=>$parErrors[0]));
			}
            Yii::app()->end();
        }

        $Platform = new Platform();
        $samePlatfromsArray = $Platform->samePlatfromsArray;  
        $demo_accounts = $Platform->getAvlblDemoAccs('schedule');



        foreach ($ScheduleIs as $key => $schedule) {

            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump($ScheduleIs);die();
            }*/
            if(isset($schedule->info)){
                $ScheduleIs[$key]->info = $schedule->info;
                $ScheduleIs[$key]->class = 'mt';
            }elseif (in_array($schedule->Name, $samePlatfromsArray['dma'])) {
                $ScheduleIs[$key]->info = Yii::t("main", "532_dma_info");
				$ScheduleIs[$key]->class = 'mt';
            } elseif (in_array($schedule->Name, $samePlatfromsArray['cfd'])) {
                $ScheduleIs[$key]->info = Yii::t("main", "533_cfd_info");
				$ScheduleIs[$key]->class = 'mt';
            } elseif (in_array($schedule->Name, $samePlatfromsArray['fx'])) {
                if(Yii::app()->params['type'] != 'swissfs' && Yii::app()->params['type'] != 'SwissSA'){
					$ScheduleIs[$key]->info = Yii::t("main", "534_fx_info");					
				}else{
					$ScheduleIs[$key]->info = Yii::t("main", "1025_mt_fx_description");					
				}
				$ScheduleIs[$key]->class = 'mt';
            }elseif(in_array($schedule->Name, $samePlatfromsArray['plus'])){
				$ScheduleIs[$key]->class = 'mt';
				$ScheduleIs[$key]->info = Yii::t("main", "1036_mt_plus_description");
				//unset($ScheduleIs[$key]);
			}elseif(in_array($schedule->Name, $samePlatfromsArray['eforex'])){
                $ScheduleIs[$key]->class = 'eforex';
                $ScheduleIs[$key]->info = ''; // Yii::t("trader", "73_eforex_pl_descr");
                //unset($ScheduleIs[$key]);
            }elseif(in_array($schedule->Name, $samePlatfromsArray['platinum'])){
                $ScheduleIs[$key]->class = 'platinum';
                $ScheduleIs[$key]->info = '';
                //unset($ScheduleIs[$key]);
            }else{
				$ScheduleIs[$key]->class = '';
				$ScheduleIs[$key]->info = '';
			}
        }
		
		//var_dump($ScheduleIs);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($ScheduleIs);die();
        }*/



        $this->render('openLiveAccount', array('info' => $info, 'mas' => $mas, 'ScheduleIs' => $ScheduleIs, 'platfAmount' => $platfAmount, 'isEmailSend' => $isEmailSend, 'status' => $status, 'acc_info' => $acc_info, 'Schedule' => $Schedule, 'demo_accounts' => $demo_accounts, 'demo_user_attrs' => $demo_user_attrs, 'Registration'=>$reg));
    }

    public function actionOpenDemoAccount(){
        $this->pageTitle = Yii::t("main", "488_open_demo_acc");
        $this->breadcrumbs = array(
            Yii::t("main", "488_open_demo_acc"));

        $Platform = new Platform();
        $status = array();
        $mas = array();
        $status['approve'] = 0;
        $reg = new Registration('openTrAcc');
        $status['approve'] = $reg->IsApprove();
        $reg->initIndv();
        //$email = $reg->email;
		
		$Funds = new FundServices('openDemo');
		$demoValues = $Funds->GetDemoDepositValues();

		
		$leverages = $reg->GetDemoLeverageValues();
		/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
			var_dump($info);die();
		} */
		
        ///////////
        $account = new Account();
        $user_info = $account->GetInfo();
        $Reg = new Registration();
        //$demo_user_attrs = array();
        if ($user_info->Type == 6) {
            $Trader = new RegistrationTrader();
            $Trader->initTrader();
            //$demo_user_attrs = $Trader->attributes;
        } elseif ($user_info->Type == 4) {
            $Reg->initIndv();
            //$demo_user_attrs = $Reg->attributes;
        }
        $country = $Reg->GetCountry('three');

        //$demo_user_attrs['phone'] = str_replace(array('+', ')', '(', ' ', '-'), '', $demo_user_attrs['phone']);
        //$demo_user_attrs['country3code'] = $country[str_replace('+', ' ', $demo_user_attrs['country'])];
        ///////////

        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['platform'])) {
                $reg->leverage = Yii::app()->request->getPost('leverage');
				/* if($user_info->Login == 1000063758){
					var_dump('2222',$reg->validate(), $reg->getErrors());die();
				} */
				if($reg->validate()){
					$post = Yii::app()->request->getPost('platform');
					$post = substr($post, 0, (strlen($post) - 1));
					$pl = explode(",", $post);
					$id_pltfrms = $session_id = '';
					foreach ($pl as $elem) {
						if (strstr($elem, '_')) {
							$tmp = explode('_', $elem);
							$id_pltfrms .= '/' . $tmp[0];
							$session_id = $tmp[1];
						}
					}
					
				   foreach ($pl as $k => $v) {
						$Funds = new FundServices('openDemo');
						if (isset($_POST['amount'])){
							$Funds->amount = $_POST['amount'];
							$validateFunds = CActiveForm::validate($Funds);
							if($validateFunds=='[]'){
								$platon = new Platform();
								$plaformLinckArr = $platon->GetLinksForUser();
								$ScheduleIs = $reg->GetSchedule('-1', 'true', '2');

                                /*$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($plaformLinckArr, $v);die();
                                }*/

                                 $v_id = $v;

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

                                if(strstr($v, '|')){
                                    $tmp = explode('|', $v);
                                    $links_tmp = $plaformLinckArr->$tmp[0];
                                    $reg->accountGroup = $tmp[1];

                                    $v_id = $tmp[0];

                                }else{
                                    $links_tmp = $plaformLinckArr->$v;
                                }

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

								//$links = $plaformLinckArr->$v;
                                $links = array();
                                foreach($links_tmp as $l){
                                    $links[$l->type] = $l;
                                }

								$tmp = $reg->regNewAccount($v_id, -1, $Funds->amount, $leverages[$reg->leverage]);

                                if(isset($_SESSION['isApp'])){
                                    $platformLinck = '';
                                }else{


                                    if(isset($_POST['MobileDevice']) && $_POST['MobileDevice'] == 'Android'){
                                        $platformLinck = (string) $links[2]->link;
                                    }elseif(isset($_POST['MobileDevice']) && $_POST['MobileDevice'] == 'iOS'){
                                        $platformLinck = (string) $links[3]->link;
                                    }else{
                                        $platformLinck = (string) $links[0]->link;
                                    }
                                }

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

								$mas[] = $tmp . '|' . $ScheduleIs[$v_id]->Name . '|' . $platformLinck;
								$pieces = explode("|", $mas[0]);

								if($v_id != 1 && $v_id != 13 && $v_id != 14 && $v_id != 15){
									$Funds->makeDemoDeposit($pieces[0],$Funds->amount);
								}
                                // $user_info
								$acc_info = $account->GetInfo(true);
							}else{
								echo $validateFunds;
								Yii::app()->end();
							}
						}
					}
				}else{
					
				}
            }
           $mas=json_encode(array('mas' => $mas));
		   
		   
		   
		   $account->SendOpenAccMail($reg->email, $mas, $pieces[0]);
		   //Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Mail/SendOpenAccMail?guid=' . Yii::app()->user->id . '&email=' . $reg->email . '&json=' . $mas);
			//exit(json_encode(array('mas' => $v))); 
			exit($mas);
            Yii::app()->end();
        }


        $demo_accounts = array();		
		$pl_param = 'schedule';//all



		$demo_accounts = $Platform->getAvlblDemoAccs($pl_param);


//if(isset($_GET['deb'])){echo '<pre>'; print_r(array('status' => $status, 'demo_accounts' => $demo_accounts, 'isMainOffice' => $user_info->isMainOffice, 'Funds' => $Funds, 'demoValues' => $demoValues, 'leverages' => $leverages, 'Registration' => $reg));exit();}
             $this->render('openDemoAccount', array('status' => $status, 'demo_accounts' => $demo_accounts, 'isMainOffice' => $user_info->isMainOffice, 'Funds' => $Funds, 'demoValues' => $demoValues, 'leverages' => $leverages, 'Registration' => $reg));
    }

    public function actionAgreementsWithBMFN() {
        $this->pageTitle = Yii::t("main", "79_my_agreements_with_bmfn");
        $this->breadcrumbs = array(Yii::t("main", "79_my_agreements_with_bmfn"));
        $Trader = new RegistrationTrader();
        $Trader->initTrader();
        $nextWindow = '';

        if (Yii::app()->request->isPostRequest) {
            $post = Yii::app()->request->getPost('RegistrationTrader');
            $Trader->agree($Trader->id, $post['agree']);

            $Document = new Document('Trader');
            $Registration = new Registration();
            $Trader->initTrader();
            $approve = $Registration->IsApprove();
            if (count($Document->isExist('passport')) > 0 && $approve == 0 && $Trader->agree == 1) {
                $Registration->sendApprove();
                $nextWindow = 'wait';
            }
        }


        $this->render('agreementsWithBMFN', array('Trader' => $Trader, 'nextWindow' => $nextWindow));
    }

}
