<?php

class IbController extends Controller {

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

    public function accessRules() {

        return array(
            array('allow', // allow ib user to perform actions
                'actions' => array('Index','PromoCenter','PromoBanner','PromoVideo', 'SetupInformation', 'SupportCenter', 'SetupConditions', 'AccountList','reportBrokerInfo', 'Trade', 'Payment', 'ClosedSum', 'DeposWithdrawal', 'Summary', 'ClosedSumTrade', 'DwnlCsv', 'Segregated', 'History', 'AccountRegistration', 'WhiteLabel', 'WhiteLabel_full', 'SignIbAgreement', 'TradersAgreementTerms', 'MoneyManager', 'OpenLiveAccount', 'Omnibus', 'Omnibus_full', 'Manual', 'MySite', 'OpenDemoAccount', 'ClientRegistration', 'LetterExample', 'WhiteLabelDocs', 'TradingRules', 'Schedule'),
                'roles' => array('user4'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

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

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

    public function actionIndex(){
        $this->pageTitle = Yii::t("main", "81_ib_report");
        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report"));
		
		$Account = new Account();		
		$parentcode=5;
		$rez=$Account->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
        $this->render('index', array('parentcode' => $parentcode));
    }
    public function actionPromoCenter() {
            $this->pageTitle = Yii::t("trader", "66_PromoCenter");
            $this->breadcrumbs = array(Yii::t("trader", "66_PromoCenter"));
			$view=new Account();
			$ParentCode=$view->GetParentCode();
			
            $this->render('promoCenter', array('ParentCode'=>$ParentCode));
    }
    public function actionPromoBanner() {
            if(Yii::app()->browser->isBrowser('Internet Explorer') && (Yii::app()->browser->getVersion() == '8.0')){							
                Yii::app()->getController()->redirect("/errorIE7");
            }
            $this->pageTitle = Yii::t("trader", "67_PromoBanner");
            $this->breadcrumbs = array(
                Yii::t("trader", "66_PromoCenter") => array('/ib/promoCenter.html'),
                Yii::t("trader", "67_PromoBanner"));

            
            $account = new Account();
            $info = $account->GetInfo();
            
            $limit = 5;
            $model = new MyBanner();
            if(Yii::app()->request->isAjaxRequest){
               if(isset($_REQUEST['type'])){ 
                 if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'new'){
                    echo 'new'.$_REQUEST['settings'];
                    $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/newBanner', array('limit'=>$limit, 'code'=>$info->Code, 'server'=>Yii::app()->params['server'],'settings'=>$_REQUEST['settings'] ),80);
                    print_r($ib_site_info);
                }
                
                if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'update'){
                    echo 'update'.$_REQUEST['settings'];
                    $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/updateBanner', array('code'=>$info->Code, 'server'=>Yii::app()->params['server'],'settings'=>$_REQUEST['settings'],'hashtag'=>$_REQUEST['hashtag'] ),80);
                    print_r($ib_site_info);
                }
                
                if($_REQUEST['type'] == 'delete'){
                    echo 'delete'.$_REQUEST['hashtag'];
                    $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/delBanner', array('code'=>$info->Code, 'server'=>Yii::app()->params['server'],'hashtag'=>$_REQUEST['hashtag'] ),80);
                    print_r($ib_site_info);
                }
              }else{
                    $model->attributes = $post = Yii::app()->request->getPost('MyBanner');
                    echo CActiveForm::validate($model);	
                }
                Yii::app()->end();
            }
             if(Yii::app()->request->getPost('canvasImg')){
                   $img = $_REQUEST['canvasImg'];
                   $img = str_replace('data:image/png;base64,', '', $img);
                   $img = str_replace(' ', '+', $img);
                   $fileData = base64_decode($img);
                   $filename = "banner.png"; 
                   header('Content-Description: File Transfer');
                    
                    if($msie = !strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false)      
                      header("Content-type: application/force-download");
                    else       
                      header("Content-type: application/octet-stream"); 
                    
                    header("Content-Disposition: attachment; filename=\"$filename\"");   
                    header("Content-Transfer-Encoding: binary"); 
                    header("Expires: 0"); header("Cache-Control: must-revalidate"); 
                    header("Pragma: public");

                    echo ($fileData);
                    exit();
             }
            
            
            $Banners = (array)Yii::app()->curl->post('http://ib.bmfn.com/getBanner', array('code'=>$info->Code),80);

            $this->render('promoBanner', array('model' => $model,'Banners'=>$Banners,'limit'=>$limit));
        }
    public function actionPromoVideo() {
            $this->pageTitle = Yii::t("trader", "68_PromoVideo");
            $this->breadcrumbs = array(Yii::t("trader", "66_PromoCenter") => array('/ib/promoCenter.html'),Yii::t("trader", "68_PromoVideo"));

            $this->render('promoVideo', array());
    }
    /*
      public const int OpenTrades=1;
      public const int CloseTrades = 2;
      public const int AccountList = 3;
      public const int DWA = 4;
      public const int SummaryReport = 5;
      public const int FindByEmail = 6;
      public const int CloseTradesSummaryReport = 7;
     */
     public function actionSupportCenter() {
        $this->pageTitle = Yii::t("trader", "65_Support_Center");
        $this->breadcrumbs = array(Yii::t("trader", "65_Support_Center"));
        
        $ViewFolder= wlParams::get('docsFolderServer').'/support';
        $json = file_get_contents($ViewFolder);
        $files = json_decode($json,true);

        $this->render('supportCenter', array('files'=>$files,'path'=>$ViewFolder));
        
    }
    public function actionSetupInformation() {

        $this->pageTitle = Yii::t("main", "73_my_profile_and_documents");

        $this->breadcrumbs = array(
            Yii::t("main", "73_my_profile_and_documents"));

        $Acount = new Account();
        $user_start_info = $Acount->GetInfo();
		$parentCode = $Acount->GetParentCode();
		

        $Document = new Document('Profile');
        //	$Document->isExist();

        $Individual = new Registration('Individual');
        $country = $Individual->GetCountry('none', true);
		$ind_approve = $Individual->IsApprove();

        $Bank = new RegistrationBank();
		
		$LoginForm = new LoginForm('password_set');
		
		$nextWindow = '';
		
        if ($user_start_info->GroupType != 1) {
            $Company = new RegistrationCompany();

            $Partner = new RegistrationPartner();
            $par_model_array = array();
            $partner_array = $Partner->initPartner();
            foreach ($partner_array as $key => $partnr) {
                $par_model_array[$key] = new RegistrationPartner();
                $par_model_array[$key]->attributes = (array) $partnr;
            }
        }

        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['RemovePartner'])) {
                if (isset($_POST['partnerId'])) {
                    $removeRez = $Partner->remove($user_start_info->ID, $_POST['partnerId']);
                    Yii::app()->end();
                }
            }
            if (isset($_POST['checkLastPartner'])) {
                $last = array_pop($_POST["RegistrationPartner"]);
                $lastPartner = new RegistrationPartner('lastPartner');
                $lastPartner->attributes = $last;
                $lastPartnerValidate = CActiveForm::validate($lastPartner);
                if ($lastPartnerValidate != '[]') {
                    echo $lastPartnerValidate;
                    Yii::app()->end();
                }
                Yii::app()->end();
            }
			if (isset($_POST['addPartner'])) {
				$Partner = new RegistrationPartner('addPartner');
                preg_match('/.*\[(.*)\]$/', $_POST['name'], $name);
                if ($name[1]) {
                    $tmp[$name[1]] = $_POST['value'];
                    $Partner->attributes = $tmp;
					//var_dump($name, $_POST);die();
                    $partnerFieldValidate = CActiveForm::validate($Partner, array($name[1]));
                    if ($partnerFieldValidate != '[]') {
                        echo $partnerFieldValidate;
                        Yii::app()->end();
                    } else {
                        echo json_encode($_POST['name']);
                        Yii::app()->end();
                    }
                }
                Yii::app()->end();
            }
            /*if (isset($_POST['sendRequest'])) {
                $view= new Account();
				$model_info=$view->GetInfo();

                $mail = new YiiMailer();
                $mail->setView('changeRequest');
                $mail->setData(array('userID' => $Acount->GetLogin(), 'fieldName' => $_POST['name'], 'fieldValue' => $_POST['value'], 'user_type'=>Yii::t("main","1_ib")));
                $mail->setLayout('base');
                $mail->setFrom(Yii::app()->params['adminEmail'], Yii::app()->params['name_company']);
                $mail->setTo(array(Yii::app()->params['operEmail']));
                $mail->setSubject(Yii::app()->params['name_company'] . ' - ' . Yii::t("main", "435_change_field_request"));               
				if($mail->send()){
					echo '1';
				}
                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();
			} 
			$validateLoginForm = array();
			
			if($ind_approve == 0){
				$pass_post = Yii::app()->request->getPost('LoginForm');
				$LoginForm->attributes = $pass_post;
				$validateLoginForm = json_decode(CActiveForm::validate($LoginForm), true);
			}
			//$validateIndv = $validateCompany = $errorPartnr = $errorComp = $docErrors = '[]';
            if ($user_start_info->GroupType == 1 || ($user_start_info->GroupType == 0 && $_REQUEST["broker_type"] == 'individual')) {
                $Individual->attributes = $_REQUEST;
                $validateIndv = CActiveForm::validate($Individual);
                if ($validateIndv != '[]') {
                   // echo $validateIndv;
                    //Yii::app()->end();
                }
				//var_dump('11111111');die();
				echo json_encode(array_merge(json_decode($validateIndv, true), json_decode($docErrors, true), $validateLoginForm)); 
				Yii::app()->end();
            }

            if ($user_start_info->GroupType == 2 || ($user_start_info->GroupType == 0 && $_REQUEST["broker_type"] == 'corporate')) {
                $Company->attributes = Yii::app()->request->getPost('RegistrationCompany');
                $validateCompany = CActiveForm::validate($Company);
				$errorComp = array();
				$errorPartnr = array();
                if ($validateCompany != '[]') {
                    $errorComp =  json_decode($validateCompany, true);
                }

                $par_post = Yii::app()->request->getPost('RegistrationPartner');
				//var_dump($par_post, $par_model_array);die();
                foreach ($par_model_array as $key => $par_model) {				
							$par_model_array[$key]['id'] = $key;
							//var_dump($par_post[$key]);die();
							$par_model_array[$key]->attributes = $par_post[$key];
							$validatePartner = CActiveForm::validate($par_model_array[$key]);
							if ($validatePartner != '[]') {
								$tempary = json_decode($validatePartner, true);
								$rez = array();
								foreach ($tempary as $k => $tmp) {
									$tmpnames = explode('_', $k);
									$name = $tmpnames[0] . '_' . $key . '_' . $tmpnames[1];
									$rez[$name] = $tmp;
								}
								$errorPartnr[$key] = $rez;								
							}
                }
				//var_dump($errorPartnr);die();
				if(!empty($errorPartnr)){
					foreach($errorPartnr as $er){
						$errorComp = array_merge((array)$errorComp, (array)$er);
					}				
				}
				echo json_encode(array_merge($errorComp, json_decode($docErrors, true), $validateLoginForm));
				Yii::app()->end();				
				/* if(!empty($errorComp)){
					echo json_encode($errorComp);
					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();
			} 
			
			
            Yii::app()->end();
        }

        if (Yii::app()->request->isPostRequest){
            if($_POST["broker_type"] == 'individual'){
				if(wlParams::get('officeCode') == 22){
					$Document = new Document('Profile_Individual_noor');					
				}elseif(wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56){
					$Document = new Document('Profile_Individual_au');
				}else{
					$Document = new Document('Profile_Individual');
				}
            }else{
                if(wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56){
                    $Document = new Document('Profile_Corporate_au');
                }else{
                    $Document = new Document('Profile_Corporate');
                }
            }

            $Document->attributes = $post = Yii::app()->request->getPost('Document');
			$name_for_op = '';
            if (is_array($post)) {
				$params = ($ind_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($ind_approve==3 && !empty($name_for_op)){
				
				$Individual->initIndv();				
				
				Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Mail/ChangeFileMail?guid=' . Yii::app()->user->id . '&userID=' . $user_start_info->ID . '&fileName=' . $name_for_op);

				/*$mail = new YiiMailer();
                $mail->setView('changeRequest');
                $mail->setData(array('userID' => $Acount->GetLogin(), 'new_file' => $name_for_op, 'user_type'=>Yii::t("main","1_ib")));
                $mail->setLayout('base');
                $mail->setFrom(Yii::app()->params['adminEmail'], Yii::app()->params['name_company']); 
                $mail->setTo(array(Yii::app()->params['operEmail']));
                $mail->setSubject(Yii::app()->params['name_company'] . ' - ' . Yii::t("main", "502_new_uploded_files"));
                $mail->send();	*/		
			}
			
            //	var_dump($Document);die();
			//var_dump($user_start_info->GroupType, $_REQUEST["broker_type"]);
            if ($user_start_info->GroupType == 1 || ($user_start_info->GroupType == 0 && $_REQUEST["broker_type"] == 'individual')) {
				$Individual->attributes = Yii::app()->request->getPost('Registration');
                $answr = $Individual->update();
            }

            if ($user_start_info->GroupType == 2 || ($user_start_info->GroupType == 0 && $_REQUEST["broker_type"] == 'corporate')) {
                $Company->attributes = Yii::app()->request->getPost('RegistrationCompany');
                if ($Company->validate()) {
                    $answr = $Company->update();
                }
                $par_post = Yii::app()->request->getPost('RegistrationPartner');
                foreach ($par_post as $key => $par_model) {
					if(is_array($par_model)){
						$empty_partner = false;
						if (strstr($key, '+')) {
							$empty_partner = true;
							if (is_array($par_model)) {
								foreach ($par_model as $pm) {
									if ($pm != '') {
										$empty_partner = false;
									}
								}
							}                      
						}

						$par_model['id'] = $key;
						$Partner->attributes = $par_model;
						//var_dump($Partner->validate());die();
						if ($Partner->validate() || strstr($par_model['id'], '+')) {
							//var_dump('111');die();
							$answr = $Partner->update();
						}
					}
				}
            }
			
			if($ind_approve == 0){
				$pass_post = Yii::app()->request->getPost('LoginForm');
				$LoginForm->attributes = $pass_post;
				if($LoginForm->validate() && $LoginForm->password != ''){
					$change = $LoginForm->changePassword($user_start_info->Login, $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($ind_approve == 2){
				$isRedject = 1;
				$Individual->sendApprove();
			}		
			
            $user_start_info = $Acount->GetInfo(true);
        }

		//echo $user_start_info->GroupType;
        if (isset($user_start_info->GroupType) && $user_start_info->GroupType != 2) {
            $Individual->initIndv();
        }


        if (isset($user_start_info->GroupType) && $user_start_info->GroupType != 1) {
            $Company->initCompany();
            $partner_array = $Partner->initPartner();
            foreach ($partner_array as $key => $partnr) {
                $par_model_array[$key] = new RegistrationPartner();
                $par_model_array[$key]->attributes = (array) $partnr;
            }
        }

        $renders = array();
        $Registration = new Registration();
        $renders['approve'] = 0;
		$pltforms = $Registration->GetSchedule('-1', 'true');
        if (isset($user_start_info->GroupType) && $user_start_info->GroupType != 2) {
            if ($Individual->isFull() && $Document->isExist('identification') && (!empty($pltforms) || wlParams::get('officeCode') == 22 || $parentCode == 43)) {
                //	$rez = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/SendIBRequestToOperations/'.Yii::app()->user->id);
                if ($Registration->IsApprove() == 0) {
                    $Registration->sendApprove();
                }
                $renders['approve'] = $Registration->IsApprove();
            }
            $renders['Individual'] = $Individual;
        }
        if (isset($user_start_info->GroupType) && $user_start_info->GroupType != 1) {
            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump(current($par_model_array)->isFull(), $Company->isFull(), $Document->isExist('certificate'), (!empty($pltforms) || wlParams::get('officeCode') == 22 || $parentCode == 43));die();
            }*/

            if (current($par_model_array)->isFull() && $Company->isFull() && $Document->isExist('certificate') && (!empty($pltforms) || wlParams::get('officeCode') == 22 || $parentCode == 43)) {
                //$rez = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Registration/SendIBRequestToOperations/'.Yii::app()->user->id);
                if ($Registration->IsApprove() == 0) {
                    $Registration->sendApprove();
                }
                $renders['approve'] = $Registration->IsApprove();
            }
            $renders['Partners'] = $par_model_array;
            $renders['Company'] = $Company;
        }
        $renders['Bank'] = $Bank;

        // messages
        Yii::app()->session['message'] = array();

		if(isset($isRedject) && $isRedject==1){
			$nextWindow = '';
		}
		
		if ($renders['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 ($renders['approve'] == 1) {
			$_SESSION['message'][] = array("text" => Yii::t("main", "166_you_have_already_filled_out_all_the_required_field"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
		} elseif ($renders['approve'] == 0) {
			if($Individual->isFull() && $Document->isExist('identification')){
				$_SESSION['message'][] = array("text" => Yii::t("trader", "8_you_have_already_filled_in_all_fields_and_uploaded").'. '.Yii::t("main", "519_pls_fill_in_ib_cond"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
			}else{
				$_SESSION['message'][] = array("text" => Yii::t("main", "167_you_need_to_fill_out_all_the_required_fiel"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
			}
		}
		
		
		if (Yii::app()->request->isPostRequest) {



			if(
			    ($ind_approve==1 || $ind_approve==0) &&
                (
                    (isset($user_start_info->GroupType) && $user_start_info->GroupType != 2 && $Individual->isFull() && $Document->isExist('identification')) ||
                    (isset($user_start_info->GroupType) && $user_start_info->GroupType != 1 && current($par_model_array)->isFull() && $Company->isFull() && $Document->isExist('certificate') && $Document->isExist('articles') && $Document->isExist('bresolution') && $Document->isExist('owner_passport')) ||
                    ((wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56) && isset($user_start_info->GroupType) && $user_start_info->GroupType != 1 && current($par_model_array)->isFull() && $Company->isFull() && $Document->isExist('certificate') && $Document->isExist('owner_passport') && $Document->isExist('proof_address'))
                ) &&
                !isset($_POST['saddPartner']) && !isset($_POST['sremovePartner'])

                ){
				$nextWindow = 'next';



				
				if(wlParams::get('officeCode') == 44){ /* Swiss Saudi */
					$Registration->ApplySchedule('',43,3);
					$Registration->sendApprove();						
				}elseif(wlParams::get('officeCode') == 50){ /* GNT */
					$Registration->ApplySchedule('',57,5);
					$Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 60){ /* Swiss Prime */
                    $Registration->ApplySchedule('',77,3);
                    $Registration->sendApprove();
				}elseif(wlParams::get('officeCode') == 45){ /* TKFX */
					$Registration->ApplySchedule('',44,2);
					$Registration->sendApprove();						
				}elseif(wlParams::get('officeCode') == 22){ /* Noor */
					$Registration->ApplySchedule('',33,5);
					$Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 30){ /* eforex */
					$Registration->ApplySchedule('',39,2);
					$Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 63){ /* Paramount */
                    $Registration->ApplySchedule('',81,5);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 64){ /* T2Trade */
                    $Registration->ApplySchedule('',41,2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 65){ /* SIMarkets Albania */
                    $Registration->ApplySchedule('',77,3);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 69){ /* SIMarkets Dubai */
                    $Registration->ApplySchedule('',77,3);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 70){ /* SIMarkets India */
                    $Registration->ApplySchedule('',77,3);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 72) { /* TradeDu */
                    $Registration->ApplySchedule('', 83, 5);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 67) { /* TradingMarket */
                    $Registration->ApplySchedule('', 42, 2);
                    $Registration->sendApprove();
				}elseif(wlParams::get('officeCode') == 68) { /* Swiss Capital */
                    $Registration->ApplySchedule('', 77, 3);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 74) { /* Global Trading */
                    $Registration->ApplySchedule('', 43, 2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 76) { /* Go World Trading */
				    $Registration->ApplySchedule('', 43, 2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 77) { /* EFX CPI Dubai */
                    $Registration->ApplySchedule('', 85, 5);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 78) { /* EFX CPI Vietnam */
                    $Registration->ApplySchedule('', 45, 2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 79) { /* Trade Online Market */
                    $Registration->ApplySchedule('', 47, 2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 81) { /* EFX CPI Dubai Call Center 1 */
                    $Registration->ApplySchedule('', 89, 5);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 82) { /* EFX CPI Dubai Call Center 2 */
                    $Registration->ApplySchedule('', 91, 5);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 80) { /* Platinum FX */
                    $Registration->ApplySchedule('', 93, 1);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 83) { /* Swiss Capital UniTrader */
                    $Registration->ApplySchedule('', 101, 14);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 86) { /* BMF PRO */
                    $Registration->ApplySchedule('', 48, 2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 32) { /* BMFN Default Schedule 2024 */
                    $Registration->ApplySchedule('', 105, 5);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 88) { /* LimitlessFX Default Schedule */
                    $Registration->ApplySchedule('', 50, 2);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 89) { /* Marketis Default Schedule */
                    $Registration->ApplySchedule('', 109, 1);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 90) { /* BladeMarkets Default Schedule*/
                    $Registration->ApplySchedule('', 111, 16);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 91) { /* SwissFS Academy */
                    $Registration->ApplySchedule('', 115, 3);
                    $Registration->sendApprove();
                }elseif(wlParams::get('officeCode') == 92) { /* BladeMarkets KW Default Schedule*/
                    $Registration->ApplySchedule('', 118, 16);
                    $Registration->sendApprove();
                }else{
					if($parentCode == 43){
						$Registration->ApplySchedule('',39,5);	
						$Registration->sendApprove();						
					}
				} 
			}
		}
		$showSetPass = true;
		if(($ind_approve==1 || $ind_approve==0) && ((isset($user_start_info->GroupType) && $user_start_info->GroupType != 2 && $Individual->isFull() && $Document->isExist('identification')) || (isset($user_start_info->GroupType) && $user_start_info->GroupType != 1 && current($par_model_array)->isFull() && $Company->isFull() && $Document->isExist('certificate') && $Document->isExist('articles') && $Document->isExist('bresolution') && $Document->isExist('owner_passport'))) && !isset($_POST['saddPartner']) && !isset($_POST['sremovePartner'])){
			$showSetPass = false;
		}
		
		$renders['showSetPass'] = $showSetPass;
        $renders['LoginForm'] = ($renders['approve'] == 0) ? $LoginForm : '';
		
		$renders['parentCode'] = $parentCode;
		$renders['nextWindow'] = $nextWindow;
        $renders['Document'] = $Document;
		//unset($country['United Kingdom']);
        $renders['country'] = $country;
        $renders['GroupType'] = $user_start_info->GroupType;

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

        $this->render('setupInformation', $renders);
    }
    public function actionSetupConditions(){
        $this->pageTitle = Yii::t("main", "251_setup_ib_conditions");


		
        $this->breadcrumbs = array(
            Yii::t("main", "251_setup_ib_conditions"));

		$nextWindow = '';
		$accesss = 'deny';
        $registration = new Registration();
		
		
		$Acount = new Account();
		$user_start_info = $Acount->GetInfo();	
		
		if(/* $user_start_info->Code == 10476 &&  */in_array($user_start_info->Code, [10476, 11899, 11938, 11942, 11943, 11944, 14284, 14204, 14511, 14745])){
			die('access denies');
		}
		
		$Document = new Document('Profile');
		$Individual = new Registration('Individual');
		$Individual->initIndv();
		$Bank = new RegistrationBank();
		$Bank->initBank();
		$pltforms = $registration->GetSchedule('-1', 'true');
		$status = $registration->IsApprove();
		if ($user_start_info->GroupType != 1) {
			$Company = new RegistrationCompany();
			$Company->initCompany();
			$Partner = new RegistrationPartner();
			$par_model_array = array();
			$partner_array = $Partner->initPartner();
			foreach ($partner_array as $key => $partnr) {
				$par_model_array[$key] = new RegistrationPartner();
				$par_model_array[$key]->attributes = (array) $partnr;
			}
		}
        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump((isset($user_start_info->GroupType) && $user_start_info->GroupType != 1));die();
            //var_dump(( && (current($par_model_array)->isFull() && $Company->isFull() && ((wlParams::get('officeCode') == 13 && $Document->isExist('certificate') && $Document->isExist('owner_passport') && $Document->isExist('proof_address')) || ($Document->isExist('certificate') && $Document->isExist('articles') && $Document->isExist('bresolution') && $Document->isExist('owner_passport'))))));die();
        }*/
		if (((isset($user_start_info->GroupType) && $user_start_info->GroupType != 2) && ($Individual->isFull() && $Document->isExist('identification'))) || ((isset($user_start_info->GroupType) && $user_start_info->GroupType != 1) && (current($par_model_array)->isFull() && $Company->isFull() && (((wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56) && $Document->isExist('certificate') && $Document->isExist('owner_passport') && $Document->isExist('proof_address')) || ($Document->isExist('certificate') && $Document->isExist('articles') && $Document->isExist('bresolution') && $Document->isExist('owner_passport')))))) {
			//if ($Individual->isFull() && $Document->isExist()) {
				$accesss = 'allow';
			//}
		}

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


            $platformId = Yii::app()->request->getPost('platformselect');
            $scheduleArr = Yii::app()->request->getPost('scheduleId');
            $scheduleId = isset($scheduleArr[$platformId])?$scheduleArr[$platformId]:0;
            $currencyArr = Yii::app()->request->getPost('currency');
            if (isset($currencyArr[$platformId])) {
                $currencyId = $currencyArr[$platformId];
            } else {
                $currencyId = '-1';
            }		
				
			if (isset($user_start_info->GroupType) && $user_start_info->GroupType != 2) {
				if ($Individual->isFull() && $Document->isExist('identification') && empty($pltforms)) {
					$registration->sendApprove();
				}
			}
			if (isset($user_start_info->GroupType) && $user_start_info->GroupType != 1) {
				if (current($par_model_array)->isFull() && $Company->isFull() &&
                    (
                        ($Document->isExist('certificate') && $Document->isExist('articles') && $Document->isExist('bresolution') && $Document->isExist('owner_passport')) ||
                        ((wlParams::get('officeCode') == 13 || wlParams::get('officeCode') == 56) && $Document->isExist('certificate') && $Document->isExist('proof_address') && $Document->isExist('owner_passport'))

                    ) &&
                    empty($pltforms)) {
					$registration->sendApprove();
				}
			}


            $registration->ApplySchedule($currencyId, $scheduleId, $platformId);
            if($status == 0){
                $nextWindow = 'next';
            }
        }
        $Schedule = $registration->GetSchedule('-1', 'false');
//        echo '<pre>';
//        print_r($Schedule); exit();
		//var_dump($Schedule);die();

		foreach($Schedule as $key=>$schTmp){
			$Schedule[$key]->scheduleType = false;
		}
		
        $ScheduleIs = $registration->GetSchedule('-1', 'true');
        //        echo '<pre>';
//        print_r($Schedule); exit();
		foreach($ScheduleIs as $key=>$schTmp){
			$ScheduleIs[$key]->scheduleType = true;
		}
		//var_dump($ScheduleIs, $Schedule);die();
		
        $condition = null;
        if (Yii::app()->request->getQuery('type')) {
            $arr = is_array($Schedule) ? $Schedule : $ScheduleIs;
            if (is_array($Schedule) AND is_array($ScheduleIs))
                $arr = array_merge($Schedule, $ScheduleIs);
			
            foreach ($arr as $platform) {
                if (str_replace(' ', '_', $platform->Name) == Yii::app()->request->getQuery('type')) {
                    $condition = $platform;
                }
            }
            $this->breadcrumbs = array(
                Yii::t("main", "251_setup_ib_conditions") => array('/ib/setupConditions'),
                $condition->Name);
        }
		
        if ($status == 0 && $accesss == 'deny') {
            $_SESSION['message'][] = array("text" => Yii::t("main", "168_this_page_will_be_available_after_filling_all_data") . " <a href='/ib/profile.html' >" . Yii::t("main", "73_my_profile_and_documents") . "</a>", "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
        } else {
            if (/* (isset($condition) && $condition->SelectedSchedule != -1) ||  */(!isset($condition) && count($Schedule) > 0)) {
                #$_SESSION['message'][] = array("text" => Yii::t("main", "169_please_carefully_select_the_commission_schedules_"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
            }
        }

		$commonSettings = (isset($condition->Schedule->nonSchedule)/*  && count((array)$condition->Schedule->nonSchedule)==0 */ && $condition->scheduleType && $condition->SelectedSchedule == -1) ? false : true;
		//var_dump((array)$condition->Schedule->nonSchedule);die();
		//var_dump(isset($condition->Schedule->nonSchedule), count((array)$condition->Schedule->nonSchedule)==0, $condition->scheduleType, $condition->SelectedSchedule == -1, $commonSettings);die();

        if($user_start_info->Code == '14202' || $user_start_info->Code == '14204'){
            unset($Schedule[7], $ScheduleIs[7]);
            if(isset($condition->PlatformID) && $condition->PlatformID == 7){
                Yii::app()->getController()->redirect('/ib/setupConditions.html');
            }
        }

        if(wlParams::get('officeCode') == 3){
            unset($Schedule[3], $Schedule[5], $ScheduleIs[3], $ScheduleIs[5]);
            if(isset($condition->PlatformID) && ($condition->PlatformID == 3 || $condition->PlatformID == 5)){
                Yii::app()->getController()->redirect('/ib/setupConditions.html');
            }
        }


        //$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        //if ($ip == '162.13.154.241') {
            if(count($ScheduleIs) === 0 && count($Schedule) === 1){
                $urlPath = str_replace(' ', '_', array_shift($Schedule)->Name);
                if(!strstr($_SERVER['REQUEST_URI'], $urlPath)){
                    Yii::app()->getController()->redirect('/ib/setupConditions/'.$urlPath);
                }
            }
        //}

        $this->render('setupConditions', array('Schedule' => $Schedule, 'ScheduleIs' => $ScheduleIs, 'Condition' => $condition, 'status' => $status, 'nextWindow' => $nextWindow, 'accesss' => $accesss, 'commonSettings' => $commonSettings, 'info' => $user_start_info));
    }

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

        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report") => array('/ib/'),
            Yii::t("main", "91_account_list_report"));
		
		$repor = new Report(3);
		$repor->attributes = $_REQUEST; 
        $repor->accountType = isset($_REQUEST['accountType'])?$_REQUEST['accountType']:0;
        $table = $repor->GetDataTable();
        $pagination = $repor->GetPagination();
        $count = $repor->GetCount();
        $link_error = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        $itemsOnPage = $repor->GetRowsTable();
		
		$accaunt= new Account();	
		/* $link_error=null;
		if( isset($_GET['client'])){
			$repor= new Report(3);
			$repor->SetCountRowsTable(50);
			$_REQUEST['group'] = '_'.$_GET['client'];
			$_REQUEST['groupAllIn'] = 1;
			$repor->attributes=$_REQUEST; 
			$itemsOnPage=$repor->GetRowsTable(); ###
			$table = $repor->GetDataTable();
			$pagination = $repor->GetPagination();
			$count = $repor->GetCount();
			$link_error=$repor->GetLinkCsvError();
		}elseif(Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report') || Yii::app()->request->getPost('groupAllIn') == 1 ){
			$repor= new Report(3);
			$repor->SetCountRowsTable(50);
			$repor->attributes=$_REQUEST; 
			$itemsOnPage=$repor->GetRowsTable(); ###
			$table = $repor->GetDataTable();
			$pagination = $repor->GetPagination();
			$count = $repor->GetCount();
			$link_error=$repor->GetLinkCsvError();
		}else{	
			$accaunt->attributes=$_REQUEST; 
			$accaunt->type = isset($_REQUEST['accountType']) ? $_REQUEST['accountType'] : 0;
			$accaunt->countRowsTable=(isset($_REQUEST['countRowsTable']))?($_REQUEST['countRowsTable']):$this->countRows; //переопределение
			$itemsOnPage=$accaunt->countRowsTable;
			if($accaunt->isForm() == 'accountTrader' || Yii::app()->request->getPost('formIs') == 'accountTrader' || (isset($_REQUEST['accountFilter']) && !empty($_REQUEST['accountFilter']))){
					$table = $accaunt->GetAccountTableTrader();
			}else{
					$table = $accaunt->GetAccountTableIb();
			}
			$pagination = $accaunt->GetPagination();
			$count = $accaunt->GetCount();
		} */
		
		
		$backLink = $accaunt->getBackLink();
		
        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();

        $this->render('accountList', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'backLink'=>$backLink));
    }
    
    public function actionReportBrokerInfo(){
        $this->pageTitle = Yii::t("main","1026_report_broker_info");
        $this->breadcrumbs = array(
        Yii::t("main", "81_ib_report") => array('/ib/'),
        Yii::t("main","1026_report_broker_info"));
        
        
        $repor = new Report(13);
	    $repor->attributes = $_REQUEST;
        $repor->accountType = isset($_REQUEST['accountType'])?$_REQUEST['accountType']:0;
        $table = $repor->GetDataTable();
        $pagination = $repor->GetPagination();
        $count = $repor->GetCount();
        $link_error = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        $itemsOnPage = $repor->GetRowsTable();
        
        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
        
        $this->render('reportBrokerInfo', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb));
    }
    
    public function actionPayment(){

//        if(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
        if (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,68,69,70,71,72,73,74,77,78,83,84])){
            die('access denied');
        }

            $this->pageTitle = Yii::t("main","925_payment_list");
        $this->breadcrumbs = array(
        Yii::t("main", "81_ib_report") => array('/ib/'),
        Yii::t("main","925_payment_list"));
        $link_error = null;
        
	$accaunt = new Account();
        if (Yii::app()->request->getPost('group') || Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report')){
            $repor = new Report(12);
            $repor->attributes = $_REQUEST;
            $itemsOnPage = $repor->GetRowsTable();
            $table = $repor->GetDataTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            $link_error = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        } else {            
            $accaunt->attributes = $_REQUEST;
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows;
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableTrader();

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

		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}

        $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('payment', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'parentcode'=>$parentcode, 'now'=>$now));

    }
    
    public function actionTrade() {

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

        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report") => array('/ib/'),
            Yii::t("trader","48_trade_report"));
        $link_error = null;
		$accaunt = new Account();
        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 = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        } else {            
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableTrader();



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

		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		$parentInfo = $accaunt->getParentContacts();

		if(isset($rez)&& $rez>0){$parentcode=$rez;}
				
		$backLink = $accaunt->getBackLink();
        if(isset($_GET['deb'])){

            echo '<pre>';
            print_r(array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'parentcode'=>$parentcode, 'backLink'=>$backLink, 'parentInfo'=>$parentInfo, 'info'=>$accaunt->getInfo()));
            exit();
        }
        $this->render('trade', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'parentcode'=>$parentcode, 'backLink'=>$backLink, 'parentInfo'=>$parentInfo, 'info'=>$accaunt->getInfo()));
    }
    public function actionClosedSum() {

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

        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report") => array('/ib/'),
            Yii::t("main", "95_closed_trades_report"));
        $link_error = null;
		//	var_dump(Yii::app()->request->getPost('group'), Yii::app()->request->getPost('formIs'), $_GET);die();     
		$accaunt = new Account();
	   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 = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        } else {            
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableTrader();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }

        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		$parentInfo = $accaunt->getParentContacts();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}

		$backLink = $accaunt->getBackLink();

        $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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'parentInfo'=>$parentInfo, 'now'=>$now));

//      $start_date=(isset($_POST['start_date']))?($_POST['start_date']):0;
//	$end_date=(isset($_POST['end_date']))?($_POST['end_date']):0;
//      'error_date'=>$error_date
    }
    public function actionDeposWithdrawal() {
        $this->pageTitle = Yii::t("main", "99_depositwithdrawal_report");

        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report") => array('/ib/'),
            Yii::t("main", "99_depositwithdrawal_report"));
        $link_error = null;
		$transaction_type = '';
		if(isset($_POST["transaction_type"])){
			$transaction_type = $_POST["transaction_type"];
		}
		$accaunt = new Account();
        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 = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        } else {            
            $accaunt->attributes = $_REQUEST; //if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableTrader();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }

        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}

        $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');

		$backLink = $accaunt->getBackLink();
        $this->render('deposWithdrawal', array('table' => $table, 'pagination' => $pagination, 'paltforms' => $view->GetList(), 'link_error' => $link_error, 'mas_numb' => $this->mas_numb, 'transaction_type' => $transaction_type, 'parentcode'=>$parentcode, 'backLink'=>$backLink, 'now'=>$now));
    }
    public function actionSummary() {
        $this->pageTitle = Yii::t("main", "101_summary_report");

        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report") => array('/ib/'),
            Yii::t("main", "101_summary_report"));
        $link_error = null;
		$accaunt = new Account();
        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 = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];
        } else {            
            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableTrader();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();
        }

        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		$parentInfo = $accaunt->getParentContacts();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}

        $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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'parentInfo'=>$parentInfo, 'now'=>$now));
    }
    public function actionClosedSumTrade() {

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

        $this->breadcrumbs = array(
            Yii::t("main", "81_ib_report") => array('/ib/'),
            Yii::t("main", "97_close_trade_summary_report"));
        $link_error = null;
		$accaunt = new Account();
        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 = (wlParams::get('officeCode') !== 80) ? $repor->GetLinkCsvError() : [];


        } else {

            $accaunt->attributes = $_REQUEST; //  if($repor->validate()){    //  запись отловить ошибки и в логи//  }
            $accaunt->countRowsTable = (isset($_REQUEST['countRowsTable'])) ? ($_REQUEST['countRowsTable']) : $this->countRows; //переопределение
            $itemsOnPage = $accaunt->countRowsTable;
            $table = $accaunt->GetAccountTableTrader();
            $pagination = $accaunt->GetPagination();
            $count = $accaunt->GetCount();

        }
        if (Yii::app()->request->isAjaxRequest) {
            exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
        }
        $view = new Platform();
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		$parentInfo = $accaunt->getParentContacts();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}

        $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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'parentInfo'=>$parentInfo, 'now'=>$now));
    }
    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 actionSegregated() {
        $this->pageTitle = 'Segregated Report';

        $this->breadcrumbs = array(
            'IB report' => array('/ib/'),
            'Segregated Report');

        $this->render('segregated');
    }
    public function actionHistory() {
        $this->pageTitle = 'History Report';

        $this->breadcrumbs = array(
            'IB report' => array('/ib/'),
            'History Report');


        $this->render('history');
    }
    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();
       /*  if ($status['approve'] != 3 && $status['approve'] != 1) {
            $_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");
        } */

        $ScheduleIs = $registr->GetSchedule('-1', 'true');
		
		$isView = false;
        if ($status['approve'] == 3 || $status['approve'] == 1) { // '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");			
		}
		
		$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';
			$Headers = @get_headers($url);
			if(substr_count($Headers[0], '200')>0) { $profileDocs[$docname]= $url;} else { $profileDocs[$docname] = wlParams::get('docsFolderServer')."/".$docid."/en/".$docname.'.pdf';}
		} 

        $this->render('accountRegistration', array('info' => $info, 'ScheduleIs' => $ScheduleIs, 'status' => $status, 'isView'=>$isView, 'profileDocs'=>$profileDocs));
    }
    public function actionWhiteLabel(){
        $this->pageTitle = Yii::t("main", "76_my_wl_program");

        $this->breadcrumbs = array(Yii::t("main", "76_my_wl_program"));
		

        if (isset($_GET['cancelRequest']) && $_GET['cancelRequest']) { 
			$mas_my_pl = array();
			$model = new WhiteLabel('WhiteLabel');		
            foreach ($model->GetRequestsList_WL() as $k) {
                $mas_my_pl[] = $k->id;
            }
            if (!in_array($_GET['cancelRequest'], $mas_my_pl)){
                Yii::app()->getController()->redirect("/");
            }else{
                $rez = $model->CancelRequest($_GET['cancelRequest']);
				if($rez->State == 0){
					$_SESSION['message'][] = array("text" => Yii::t("main","814_wl_diactivated"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
				}
            }
        }
		
		
		$Document = new Document();
		$allow = (count($Document->isExist('ibagreement')) > 0) ? true : false;
		
		$model = new WhiteLabel('WhiteLabel');	
		$requestList = $model->GetRequestsList_WL();
		
		$view=new Account();
        $info=$view->GetInfo();

        $user = new Registration();
        $ScheduleIs = $user->GetSchedule('-1', 'true');
        $status = $user->IsApprove();
		$alowPatforms = array();
		
		if(empty($ScheduleIs)){
            if(Yii::app()->params['type'] === 'eforex_global'){
                $_SESSION['message'][]=array("text"=>Yii::t("main", "807_fiilin_ib_cond_eforex"), "action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id, "type"=>"warning");
            }else{
                $_SESSION['message'][]=array("text"=>Yii::t("main", "807_fiilin_ib_cond"), "action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id, "type"=>"warning");
            }
		}else{
			foreach($ScheduleIs as $key){
				$alowPatforms[]=$key->PlatformID;
			}			
		}
		

        //	var_dump($status, count($ScheduleIs));die();
        /* if ($status != 3 || ( $status == 3 && count($ScheduleIs) == 0)) {
            $_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");
        } */
		
		$wlCosts['first'] = $model->GetSetting('MtWhiteLabelCost');
		$wlCosts['first'] = is_string($wlCosts['first']) ? $wlCosts['first'] : '6,500(test)';
		$wlCosts['month'] = $model->GetSetting('MtWhiteLabelMonthlyCost');
		$wlCosts['month'] = is_string($wlCosts['month']) ? $wlCosts['month'] : '1,250(test)';

        $this->render('whiteLabel', array('alowPatforms' => $alowPatforms, 'status' => $status, 'GroupType' => $info->GroupType, 'allow'=>$allow, 'WhiteLabel'=>$model, 'requestList'=>$requestList, 'plTable'=>$model->getPlatformTableLabels(), 'ScheduleIs'=>$ScheduleIs, 'wlCosts'=>$wlCosts));
    }
    public function actionWhiteLabel_full(){	
		$this->pageTitle = Yii::t("main", "174_white_label_on_mt");
		$bread_back = Yii::t("main", "76_my_wl_program");
		$url_back = '/ib/whiteLabel.html';
		$isPlatform = 2;
		
		$view=new Account();
        $info=$view->GetInfo();
				
        $country = new Registration('registration');

        $this->breadcrumbs = array($bread_back => array($url_back), $this->pageTitle);

        $model = new WhiteLabel('WhiteLabel');
        $model->platformType = (int) $isPlatform;
        $requests = $model->GetRequestsList_WL(); 

        $Document = new Document('File');
        $link_pl = null;	
		

        if (Yii::app()->request->isAjaxRequest) {
            $post = Yii::app()->request->getPost('WhiteLabel');

            foreach ($post as $key => $attr) {
                $wlValidate = CActiveForm::validate($model, array_keys(Yii::app()->request->getPost('WhiteLabel')));
               /*  if ($wlValidate != '[]') {
                    echo $wlValidate;
                    Yii::app()->end();
                } */
            }
			
			$Document->attributes = $postDocs = Yii::app()->request->getPost('Document');		
			$params = array();
			$params['addInfo'] = (!empty($post['id']) && ($post['id'] != -1)) ? $post['id'] : '';
			// Document model in view must be call only "$Document"  ---  IMPORTANT!!!
			$docErrors = $Document->ajaxDocValidate($postDocs, $Document, $params);  
			/*  if(!empty($docErrors)){
				echo $docErrors;
				Yii::app()->end();
			} */
			
			echo json_encode(array_merge(json_decode($docErrors, true), json_decode($wlValidate, true)));
			
            Yii::app()->end();
        }


        if (Yii::app()->request->isPostRequest){
            $isRequest = -1;
            if (!empty($requests)) {
                foreach ($requests as $rqst) {
                    if ($rqst->platformType == $_POST['WhiteLabel']['platformType']) {
                        $isRequest = $rqst->id;
                    }
                }
            }

            if (isset($_POST['Document'])) {
                $Document->attributes = Yii::app()->request->getPost('Document');
            }
			
            if (isset($_POST['WhiteLabel'])) {
                $model->attributes = $post = Yii::app()->request->getPost('WhiteLabel');		
				
				$isFileValidate = false;
				$wlValidate = $model->validate();
				$postValidateErrors = $model->getErrors();
				
				if(!empty($model->defDeposit) && $model->defDeposit == 'false'){
					unset($postValidateErrors['deposit']);
				}elseif(!empty($model->defDeposit) && $model->defDeposit == 'true'){
					unset($postValidateErrors['def_deposit']);
				}
				
				if(empty($postValidateErrors) && isset($_POST['Document'])){
					$params = array();
					$Document->attributes = $doc_post = Yii::app()->request->getPost('Document');

					if(isset($doc_post) && !empty($doc_post)){

						$isFileValidate = true;
						foreach($doc_post as $key=>$doc){

                            // todo COOKIE
							if(cookieDoc::isExist($key) || count($Document->isExist($key, $isRequest)) > 0){
							//if((isset(Yii::app()->session['Document'][$key]) && !empty(Yii::app()->session['Document'][$key])) || count($Document->isExist($key, $isRequest)) > 0){

							}else{
								$isFileValidate = false;
							}
						}
						if ($isFileValidate) {
							$model->status = $post['status'];
							$params['addInfo'] = $model->SendLinkWL($isRequest); ///insert
							//	Yii::app()->getController()->redirect("/ib/whiteLabel.html");
						}
						
					}else{
						if(count($Document->isExist('com_logo_mt', $isRequest)) > 0 && count($Document->isExist('com_banner_mt', $isRequest)) > 0 && count($Document->isExist('com_icon_mt', $isRequest)) > 0){
							$isFileValidate = true;
							$model->status = $post['status'];
							$params['addInfo'] = $model->SendLinkWL($isRequest); ///insert	
						}					
					}
					
					if (is_array($doc_post)) {
						//var_dump($params['addInfo']);die();
						if(!isset($params['addInfo']) || (isset($params['addInfo']) && ($params['addInfo'] == '' || $params['addInfo'] == -1))){
							$reqTmp = $model->GetRequestsList_WL();
							$params = array();
							foreach($reqTmp as $req){
								if($req->platformType == $model->platformType){
									$params['addInfo'] = $req->id;
								}
							}
						}
						$Document->postDocSave($doc_post, $params);
					}
				}elseif(empty($postValidateErrors) && count($Document->isExist('com_logo_mt', $isRequest)) > 0 && count($Document->isExist('com_banner_mt', $isRequest)) > 0 && count($Document->isExist('com_icon_mt', $isRequest)) > 0 ){
					$model->status = $post['status'];
					$model->SendLinkWL($isRequest); ///insert	
				}
				
				if(count($Document->isExist('com_logo_mt', $isRequest)) > 0 && count($Document->isExist('com_banner_mt', $isRequest)) > 0 && count($Document->isExist('com_icon_mt', $isRequest)) > 0 && empty($postValidateErrors)){
					Yii::app()->getController()->redirect("/ib/whiteLabelDocs.html");
				}
            } 
            if ($isFileValidate || $model->status == 3 || $model->status == 1){           
                Yii::app()->getController()->redirect("/ib/whiteLabelDocs.html");
            }
        }
		
        $Info = $requests = $model->GetRequestsList_WL();
 
        if (isset($Info) && is_array($Info)){
            foreach ($Info as $inf) {
				if($inf->status != 4){
					if ($inf->platformType == $isPlatform) {
						foreach ($inf as $key => &$attr) {
							$attr = urldecode($attr);
							
							if ($key == 'levereges' || $key == 'servers') {
								//var_dump($attr);
								$attr = json_decode(stripcslashes($attr));
								//var_dump($attr);
							}
							
							if ($key == 'textColor' || $key == 'backgrColor') {
								$attr = '#'.$attr;
							}
						}
						$model->attributes = (array) $inf;
						
						if(!$model->defDeposit){
							$model->def_deposit = $model->deposit;
							$model->deposit = null;
							$model->defDeposit = 'false';
						}else{
							$model->defDeposit = 'true';
						}
					}
				}else{
					$model->status = 4;
				}
            }
        }
        $status = $country->IsApprove();
		
		//var_dump($model->attributes);die();
        /* if ($status != 3){
			Yii::app()->getController()->redirect("/ib/whiteLabel.html");
		} */
        $ScheduleIs = $country->GetSchedule('-1', 'true');


        //$requests = $model->GetRequestsList_WL();
		//var_dump($requests);die();
        $list_wl = new WhiteLabel();
		
        $this->render('whiteLabel_full', array('model' => $model, 'Document' => $Document, 'section' => Yii::app()->request->getQuery('type'), 'header' => $this->pageTitle, 'country' => $country->GetCountry(), 'deposit_mass' => $model->deposit_mass, 'serv_mass' => $model->serv_mass, 'lever_mas' => $model->lever_mas, 'logoAlign_mass' => $model->logoAlign_mass, 'link_pl' => $link_pl, 'ScheduleIs' => $ScheduleIs, 'requests' => $requests, 'GroupType' => $info->GroupType));
    }
	
	public function actionWhiteLabelDocs(){
		$this->pageTitle = Yii::t("main", "794_wl_mt_docs");	
		$bread_back = Yii::t("main", "76_my_wl_program");
		$url_back = '/ib/whiteLabel.html';
		$this->breadcrumbs = array(
			Yii::t("main", "76_my_wl_program") => '/ib/whiteLabel.html', 
			Yii::t("main", "174_white_label_on_mt") => '/whiteLabelMT.html', 
			Yii::t("main","795_docs"));
		
		$isPlatform = 2;	
		$model = new WhiteLabel('WhiteLabel');		
		$model->platformType = (int) $isPlatform;
		$requests = $model->GetRequestsList_WL(); 
		foreach ($requests as $rqst) {
			if ($rqst->platformType == $isPlatform) {
				$isRequest = $rqst->id;
				$model->attributes =(array)$rqst;
			}
		}
		$params = array();
		$params['addInfo'] = (isset($model->id) && !empty($model->id)) ? $model->id : '';
		
		$Document = new Document('appFrom');
		
		if (Yii::app()->request->isAjaxRequest){
			//$params['addInfo'] = (!empty($post['id']) && ($post['id'] != -1)) ? $post['id'] : '';
			$Document->attributes = $postDocs = Yii::app()->request->getPost('Document');
			// Document model in view must be call only "$Document"  ---  IMPORTANT!!!
			$docErrors = $Document->ajaxDocValidate($postDocs, $Document, $params);  
			if(!empty($docErrors)){
				echo $docErrors;
				Yii::app()->end();
			}			
		}
		
		if (Yii::app()->request->isPostRequest){
			$Document->attributes = $post = Yii::app()->request->getPost('Document');
			if($post && is_array($post)){
				$Document->postDocSave($post, $params);
			}else{
				$_SESSION['message'][] = array("text" => Yii::t("funds", "509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
			}
			
			$WL = new WhiteLabel('WhiteLabel');
			$requests = $WL->GetRequestsList_WL();
			foreach($requests as $rqst){
				if($rqst->platformType == $isPlatform){
					$WL->attributes = (array)$rqst;
				}
			}
			
			//var_dump($WL->id, $requests, $WL->wlIsFull($isPlatform, $WL->id));die();
			if(count($Document->isExist('certificate')) > 0  && count($Document->isExist('owner_passport')) > 0 && $WL->wlIsFull($isPlatform, $WL->id)){
				if($WL->status == 0 || $WL->status == 2 || $WL->status == 4){
					$WL->SendRequestToOperations($WL->id);
				}
				Yii::app()->getController()->redirect("/ib/whiteLabel.html?compl");
			}
			if($WL->status == 3 || $WL->status == 1){
				Yii::app()->getController()->redirect("/ib/whiteLabel.html");
			}
		}
		
		$this->render('whiteLabelDocs', array('Document'=>$Document, 'model'=>$model));
	}
	
    public function actionSignIbAgreement(){


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

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

		
        $Document = new Document('IBAgreement');
		$docAgreement = $Document->isExist('ibagreement');


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

        if ($status['approve'] == 0) {
            $this->pageTitle = Yii::t("main", "53_sign_ib_agreement");
            $this->breadcrumbs = array(Yii::t("main", "53_sign_ib_agreement"));
			$registration = new Registration();
			$ScheduleIs = $registration->GetSchedule('-1', 'true');
			
			if(empty($ScheduleIs)){
                if(Yii::app()->params['type'] === 'eforex_global'){
                    $_SESSION['message'][]=array("text"=>Yii::t("main", "807_fiilin_ib_cond_eforex"), "action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id, "type"=>"warning");
                }else{
                    $_SESSION['message'][]=array("text"=>Yii::t("main", "807_fiilin_ib_cond"), "action"=>Yii::app()->controller->id."/".Yii::app()->controller->action->id, "type"=>"warning");
                }
			}else{
				$_SESSION['message'][] = array("text" => Yii::t("main", "168_this_page_will_be_available_after_filling_all_data") . " <a href='/ib/profile.html' >" . Yii::t("main", "73_my_profile_and_documents") . "</a>", "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
			}
        } else {
            $this->pageTitle = Yii::t("main", "75_my_ib_agreement");
            $this->breadcrumbs = array(Yii::t("main", "75_my_ib_agreement"));
        }
        if ($status['approve'] == 1) {
            if ($docAgreement) {
                $_SESSION['message'][] = array("text" => Yii::t("main", "177_you_have_already_signed_the_ib_agreement_the_oper"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
				$nextWindow = 'next';
			} else {
               /*  $_SESSION['message'][] = array("text" => Yii::t("main", "178_ib_agreement_will_be_visible_till_it_is_confirmed_"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning"); */
            }
        }
        if ($status['approve'] == 3) {
            if (!$docAgreement) {
                $_SESSION['message'][] = array("text" => Yii::t("main", "179_your_ib_agreement_is_not_in_the_database_please_c"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "warning");
            }
        }

        $this->render('signIbAgreement', array('status' => $status, 'document' => $Document, 'nextWindow' => $nextWindow, 'docAgreement' => $docAgreement));
    }
    public function actionTradersAgreementTerms() {
        $this->pageTitle = Yii::t("main", "184_traders_agreement_terms");

        $this->breadcrumbs = array(
            Yii::t("main", "My agreements with BMFN") => ('/ib/setupLegalInformation.html'),
            Yii::t("main", "184_traders_agreement_terms"));

        $registration = new Registration();
        $status = $registration->GetAgreement();

        if (Yii::app()->request->getPost('linfo_info_ib2_agree')) {
            $registration->SetAgreement();
        }

        $this->render('tradersAgreementTerms', array('status' => $status));
    }
    public function actionMoneyManager() {
        $this->pageTitle = Yii::t("main", "183_money_manager");

        $this->breadcrumbs = array(
            Yii::t("main", "183_money_manager"));

        $this->render('moneyManager');
    }
    public function actionOpenLiveAccount(){
    $this->pageTitle = Yii::t("main", "181_open_live_account");
    $this->breadcrumbs = array(
        Yii::t("main", "182_account_registration") => ('/ib/account-registration.html'),
        Yii::t("main", "181_open_live_account"));

            $Platform = new Platform();

    $account = new Account();
    $info = $account->GetAccount();
    $acc_info = $account->GetInfo();


    $platfAmount = array();

    foreach ($info as $key => $value) {
        $platfAmount[$key] = count($value);
    }
    $mas = array();
            $mas_refresh = array();
    $status = array();
    $status['approve'] = 0;
    $reg = new Registration;
    $status['approve'] = $reg->IsApprove();
    $ScheduleIs = $reg->GetSchedule('-1', 'true');
    $reg->initIndv();


    if (Yii::app()->request->isAjaxRequest){
        if (isset($_POST['platform'])){

            $post = Yii::app()->request->getPost('platform'); //POST platform=3,5,
            $post = substr($post, 0, (strlen($post) - 1));
            $pl = explode(",", $post);

            $platon = new Platform();
            $plaformLinckArr = $platon->GetLinksForUser();

                            $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, '_')){
                                            if (!empty($v)) { // Metatraders

                                                    $v_id = $v;

                                                    if (is_array($ScheduleIs)) {
                                                        foreach ($ScheduleIs as $value) {
                                                            if ($v == $value->PlatformID) {
                                                                    $platform = $value->Name;

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

                                                               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;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    //$mas[] = $reg->regNewAccount($v);
                                                    $tmp = $reg->regNewAccount($v_id);
/*
                                                    $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
                                                    if ($ip == '162.13.154.241') {
                                                        var_dump($tmp, $platform, $platformLinck);die();
                                                    }*/

													$mas[] = $tmp . '|' . $platform. '|' . $platformLinck;
                                                    $pieces = explode("|", $mas[0]);
                                                    $acc_info = $account->GetInfo(true);

                                            }
                                    }
            }


        }
        $mas = json_encode(array('mas' => array_merge($mas, $mas_refresh))); 

        $account->SendOpenAccMail($reg->email, $mas, $pieces[0]);
        //$info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Mail/SendOpenAccMail?guid='.Yii::app()->user->id.'&email='.$reg->email.'&json='.$mas);

        exit($mas);//{"mas":["33323276,EfXYMaXMwI3,Noor Capital MT4"]}
        Yii::app()->end();
    }

            $Platform = new Platform();
            $samePlatfromsArray = $Platform->samePlatfromsArray;
            foreach($ScheduleIs as $key=>$schedule){
                    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 = '';
						//unset($ScheduleIs[$key]);
					}else{
						$ScheduleIs[$key]->class = '';
						$ScheduleIs[$key]->info = '';
					}
            }



            $isView = false; 	
    if ($status['approve'] == 1 || $status['approve'] == 3) { 
        $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");
            }

    $this->render('openLiveAccount', array('info' => $info, 'mas' => $mas, 'ScheduleIs' => $ScheduleIs, 'platfAmount' => $platfAmount, 'status' => $status, 'acc_info' => $acc_info, 'isView'=>$isView));
}
    public function actionManual(){
        $this->pageTitle = Yii::t("main", "180_personal_cabinet_for_ib_manual");
        $this->breadcrumbs = array(Yii::t("main", "180_personal_cabinet_for_ib_manual"));
        $this->render('manual');
    }
    public function actionMySite(){
            $this->pageTitle = Yii::t("main", "461_ib_website");
            $this->breadcrumbs = array(
                        Yii::t("trader", "66_PromoCenter") => array('/ib/promoCenter.html'),
                        Yii::t("main", "461_ib_website"));

            $account = new Account();
    $info = $account->GetInfo();
            $Registration = new Registration('Individual');
            $params['status'] = $status = $Registration->IsApprove();

            $isView = false;
            if ($status == 3 || $status == 1) { // 'is ib not aprove' 
                    $isView = true;    
            }

            $params['isView'] = $isView;
            if($isView){

                    $Site = new MyWebsite($this->isStatus);		

                    $tmplang = (Yii::app()->language=="ar") ? 'ar' : Yii::app()->language;

                    if(in_array($tmplang, array_keys($Site->allow_langs))){
                            $site_lang = $tmplang;
                    }else{
                            $site_lang = 'en';
                    }

                    if(Yii::app()->request->isAjaxRequest){
                            $Site->attributes = $post = Yii::app()->request->getPost('MyWebsite');
                            $Site->attributes = $post = Yii::app()->request->getPost('MyWebsite');
                            $Site->platforms = $post['platforms'] = isset($post['platforms'])?$post['platforms'] : '';
                            $Site->langs = $post['langs'] = isset($post['langs'])?$post['langs'] : '';

                            //$post = $Site->attributes;
                            for($i = 1 ; $i<6 ; $i++){
                                    $name = 'social_link'.$i;
                                    if($Site->$name=='http://'){
                                            $Site->$name = '';
                                            unset($post[$name]);
                                    }
                            }
                    //	var_dump($post, $Site->attributes);die();
                            $valdt_attrs = array_keys($post);
                            if($_POST["domen_choose"]=='1'){
                                    if(in_array('domen',$valdt_attrs)){
                                            unset($valdt_attrs[array_search('domen', $valdt_attrs)]);
                                    }
                            }else{
                                    if(empty($post['domen'])){
                                            $Site->domen='error';
                                    }
                            }

                            $siteValidate = CActiveForm::validate($Site, $valdt_attrs);	
                            if($siteValidate != '[]'){
                                    echo $siteValidate;
                                    Yii::app()->end();
                            }	
                            Yii::app()->end();	
                    }

                    if(Yii::app()->request->isPostRequest){
                    //	http://ib.bmfn.com/createSite?code=76&fname=alexx&lname=koxx&phone=0936764523&email=ibtest@mail.ru&domen=koxx&deflang=en&langs=en,ru,cn&idDesign=1
                            $Site->attributes = $post = Yii::app()->request->getPost('MyWebsite');
                            $Site->platforms = $post['platforms'] = isset($post['platforms'])?$post['platforms'] : '';
                            $Site->langs = $post['langs'] = isset($post['langs'])?$post['langs'] : '';




                            $docValidation = $Site->validate();
                            $errorsList = $Site->getErrors();

                            if ($docValidation){

                            $post['code'] = $info->Code;
                            $post['langs'] = implode(",",$post['langs']);
                            $post['platforms'] = implode(",",$post['platforms']);

                            if($_POST["domen_choose"]==2){
                                    $post['subDomen'] = 'ib'.$info->Code;
                                    if(!empty($post['domen'])){
                                            $post['domen'] = str_replace('http://','',$post['domen']);
                                            if($post['domen'][strlen($post['domen'])-1]=='/'){
                                                    $post['domen'] = substr($post['domen'], 0, -1);
                                            } 
                                    }else{
                                      //      $Site->domen='';
                                    }
                            }else{
                                    //$post['subDomen'] = 'ib'.$info->Code;
                                    //$post['domen'] = '';
                            }



                                    $uploader = CUploadedFile::getInstance($Site, 'logo');
                                    if ($uploader) {
                                            $sourcePath = pathinfo($uploader->getName());
                                            $fileName = 'sitelogo_ib'.$info->Code.'.'.$sourcePath['extension'];
                                            $Site['logo'] = $uploader;
                                            $Site['logo']->saveAs($_SERVER["DOCUMENT_ROOT"] . '/assets/img/site_logos/'.$fileName);

                                            $image_size = getimagesize($_SERVER["DOCUMENT_ROOT"] . '/assets/img/site_logos/'.$fileName);
                                            if($image_size[1]>101){
                                                    $width = (101*(int)$image_size[0])/$image_size[1];
                                                    $image = Yii::app()->image->load($_SERVER["DOCUMENT_ROOT"] . '/assets/img/site_logos/'.$fileName);
                                                    $image->resize($width, 101);
                                                    $image->save(); 					
                                            }

                                            $post['logo_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/assets/img/site_logos/'.$fileName;
                                            $post['logo_name'] = $fileName;
                                    }
                                    $post['server'] = Yii::app()->params['server'];
                                    $post['userType'] = $info->Type;
                                if(isset($_GET['cd'])){
                                    $post['cd'] = true;
                                    $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/updateSite', $post,80);
                                    echo '<pre>';print_r($post);print_r($ib_site_info);die();
                                }else{
                                    $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/updateSite', $post,80);
                                }
                                //    $str = 'http://ib.bmfn.com/updateSite?';
                                //    foreach ($post as $kay=>$value) {
                                //        $str.=$kay.'='.$value.'&';
                                //    }
                                 
                                 //   echo $str.'<pre>';var_dump($ib_site_info);
                                 //   die();

                                    if($ib_site_info=="success"){
                                            $_SESSION['message'][] = array("text" => Yii::t("main", "498_you_alrdy_crt_site"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
                                    }						
                                    $Site = new MyWebsite();
                            } 
                    }	

                    $params['has_site'] = $Site->has_site;
                    $params['Site'] = $Site;		
                    $params['design'] = $Site->allow_designs;
                    $params['langs'] = $Site->allow_langs;
                    $params['platforms'] = $Site->allow_platforms;
                    $params['socials'] = $Site->allow_socials;
                    $params['site_lang'] = $site_lang; 

                    if($Site->has_site==1){
//				if($Site->domen!='' && isset($Site->domen)){
//					$rez = @file_get_contents($Site->domen.'/domenReady');
//					if($rez=='good'){
//                                                $params['urlToWebSite'] = $Site->domen;
//						$params['action'] = $Site->domen.'/admin/login';
//					}else{
//                                                $params['urlToWebSite'] = 'http://'.$Site->subDomen.'.ib.bmfn.com';
//						$params['action'] = 'http://'.$Site->subDomen.'.ib.bmfn.com/admin/login';					
//					}
//				}else{
                                    $params['urlToWebSite'] = 'http://'.$Site->subDomen.'.ib.bmfn.com';
                                    $params['action'] = 'https://'.$Site->subDomen.'.ib.bmfn.com/admin/login';
                                    if(isset($Site->domen) && !empty($Site->domen) && ($Site->domen != 'http://')){ 
                                            $rez = @file_get_contents($Site->domen.'/domenReady');
                                            if($rez=='good'){
                                                    $params['action'] = $Site->domen.'/admin/login';
                                            }					
                                    }
                            //}


                            $params['code'] = $info->Code;
                            $params['subDomen'] = $Site->subDomen;
                            //$params['domen'] = $Site->domen;
                            $params['login'] = $Site->login;
                            $params['password'] = $Site->password;
                    }
            }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");
            }
			$parentcode=5;
			$rez=$account->GetParentCode();
			if(isset($rez)&& $rez>0){$parentcode=$rez;}
			$params['parentcode'] = $parentcode;
            $this->render('mySite', $params);
    }
    public function actionOpenDemoAccount(){

            $this->pageTitle = Yii::t("main", "488_open_demo_acc");
            $this->breadcrumbs = array(
        Yii::t("main", "182_account_registration") => ('/ib/account-registration.html'),
        Yii::t("main", "488_open_demo_acc"));

            $Platform = new Platform();	
            $status = array();
            $mas_error = array();
            $mas_refresh = 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();

            ///////////
            $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($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');

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

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

												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;
												}
												
												$mas[] = $tmp . '|' . $ScheduleIs[$v]->Name . '|' . $platformLinck;
												$pieces = explode("|", $mas[0]);

                                                if($v != 1 && $v != 13 && $v != 14 && $v != 15){
                                                    $Funds->makeDemoDeposit($pieces[0],$Funds->amount);
                                                }


												$acc_info = $account->GetInfo(true);					
										}else{
												echo $validateFunds;
												Yii::app()->end();
										}		
								}						
							}

							$mas = array_merge($mas, $mas_error);
						}
				}
                    $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);
        Yii::app()->end();
    }

            $act_demo_acc_registr = array();
            if(isset($_GET["user"]) && isset($_GET["password"]) && isset($_GET["acct_id"])){
                    $act_demo_acc_registr["user"] = $_GET["user"];
                    $act_demo_acc_registr["password"] = $_GET["password"];
                    $act_demo_acc_registr["acct_id"] = $_GET["acct_id"];
                    $act_demo_acc_registr["name"] = 'ACT Trader';
                    $act_demo_acc_registr["download_link"] = 'http://setup.sysfx.com/setup/trader/bmf2/trader_setup.exe';
            }

            /* if ($status['approve'] != 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");
    } */

            $isView = false; 	
    if ($status['approve'] == 1 || $status['approve'] == 3) { 
        $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");
            }

            $demo_accounts = array();
            $apps_platforms = array();
            if($user_info->isMainOffice){
                if (isset($_GET["user"]) && isset($_GET["password"]) && isset($_GET["acct_id"])) {
                            $act_demo_acc_registr["user"] = $_GET["user"];
                            $act_demo_acc_registr["password"] = $_GET["password"];
                            $act_demo_acc_registr["acct_id"] = $_GET["acct_id"];
                            $act_demo_acc_registr["name"] = 'ACT Trader';
                            $act_demo_acc_registr["download_link"] = 'http://setup.sysfx.com/setup/trader/bmf2/trader_setup.exe';
                    }
                    $pl_param = 'all';
            }else{
                    $pl_param = 'schedule';
            }  
                            $demo_accounts = $Platform->getAvlblDemoAccs($pl_param);

        if(isset($_GET['deb'])){
            $platon = new Platform();
            $plaformLinckArr = $platon->GetLinksForUser();
            $v = 15;
            $links_tmp = $plaformLinckArr->$v;
            $links = array();
            foreach($links_tmp as $l){
                $links[$l->type] = $l;
            }
            echo '<pre>';
            print_r($links);exit();}
            $this->render('openDemoAccount', array('status' => $status, 'demo_accounts'=>$demo_accounts, 'act_demo_acc_registr'=>$act_demo_acc_registr, 'demo_user_attrs'=>$demo_user_attrs, 'Funds' => $Funds, 'demoValues' => $demoValues, 'isView'=>$isView, 'leverages' => $leverages, 'Registration' => $reg));
    }
    public function actionClientRegistration(){
    $this->pageTitle = Yii::t("main","689_client_regist_link");
    $this->breadcrumbs = array(Yii::t("main","689_client_regist_link"));

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

            if (Yii::app()->request->isAjaxRequest){
                    if($_POST['linkViaMail']){
							$mails = str_replace(' ', '', $_POST['mail']);
							$mails = explode(',', $mails);
                            $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';

                            $mail = new YiiMailer();
                            $mail->setView('linkViaMail');
                            $mail->setData(array('aff_link' => $http.'//'.$_SERVER['HTTP_HOST'].'/registration.html?ib='.$info->Code));
                            $mail->setLayout('base');
                            $mail->setFrom(Yii::app()->params['adminEmail'], Yii::app()->params['name_company']);
                            $mail->setTo($mails);
                            $mail->setSubject(Yii::app()->params['name_company'].' - '.Yii::t("main","630_account_opening"));
                            echo $mail->send();
                            Yii::app()->end();
                    }           
    }

    $this->render('clientRegistration', array('code'=>$info->Code));
}
    public function actionLetterExample(){
            $this->pageTitle = Yii::t("main","713_letter_example");
            $this->layout = 'empty';

            if(isset($_GET['template']) && file_exists($_SERVER['DOCUMENT_ROOT'].'/protected/views/mail/'.$_GET['template'].'.php')){			
                    $mail = new YiiMailer();
                    $mail->setView($_GET['template']);
                    if($_GET['template'] == 'linkViaMail'){
                            $account = new Account();
                            $info = $account->GetInfo();		
                            $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';				
                            $mail->setData(array('aff_link' => $http.'//'.$_SERVER['HTTP_HOST'].'/registration.html?ib='.$info->Code));			
                    }
                    $mail->setLayout('base');

                    $mail->setFrom('test123@i.ua');
                    $mail->setTo('test123@i.ua');
                    $mail->setSubject('test subject');

                    $fullLetter = $mail->send(true);

                    preg_match('/(<html>.*<\/html>)/s', $mail->send(true), $matches);


                    $this->render('mailExample', array('data' => $matches[1]));
            }else{
                    echo 'Such Template does not exist!';
            }


    }
	
	public function actionTradingRules(){
		$this->pageTitle = Yii::t("main", "1021_trading_rules");
            $this->breadcrumbs = array(Yii::t("main", "1021_trading_rules"));
		
		$account = new Account();
		$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';
			$Headers = @get_headers($url);
			if(substr_count($Headers[0], '200')>0) { $profileDocs[$docname]= $url;} else { $profileDocs[$docname] = wlParams::get('docsFolderServer')."/".$docid."/en/".$docname.'.pdf';}
		} 

        $this->render('tradingRules', array('profileDocs'=>$profileDocs));
	}

    public function actionSchedule(){
        $this->pageTitle = Yii::t("main", "1113_current_schedule");
        $this->breadcrumbs = array(Yii::t("main", "1113_current_schedule"));

        $account = new Account();
        $res = $account->GetCurrentSchedule();

        var_dump('actionSchedule');die();
    }
}
