<?php

class Report extends CFormModel
{
	private $_identity;
	
        private $type=3;          /*
                                    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;
                        /GetReport            public const int CloseTradesSummaryReport = 7;
                                  */
        public $accountType = 0;       //get platform = 0 - all, 1 live, 2 demo, other - no
        public $group='-1';      // -1 выводит всех // akk,gr;
        public $groupIn='-1';
        public $groupAllIn = 1;
        
        public $startDate = 0;   //фильтр начальной даты
        public $endDate   = 0;   //фильтр конечной даты
        public $platform  = '-1';   //фиьтр платформы
        
        public $filter = 'null';    //поиск по слову
        
        public $sort = 'null';      //имя поля по которому сортировать
        public $desc = 0;       //направление сортировки
        
        public $page = 0;       //текущая страницы
        public $countRowsTable=25 ;  //по сколько выводить     
        private $tableHead;
        private $listTotal=array();
        private $listReport = array(); // список репортов
        private $countListReport = 25; // поличество записей в репорте
        
		public $needGroups = 1;  // 1 - his and his childs; 0 - only his; 2 - only his childs
		public $RequestState = -1;
		public $state = -1;
		public $creationFrom = 0;
		public $creationTo = 99999999999;
		
		public $needLeads = 'true';
		
		public $ibID;
		public $types = '';
		public $accountId = '';
		
        public $email= 'null';    //Find account by email
        
        public $typeTransaction = 'null'; // for report Transaction 
		public $thead;
        
        public function rules(){
            return array(
                array('platform'        , 'numerical'),
                array('countRowsTable'  , 'numerical'),
                array('groupAllIn'      , 'numerical'),
                array('accountType'     , 'numerical'),
                array('startDate'   	, 'length', 'min'=>3),
                array('endDate'    		, 'length', 'min'=>3),
                array('filter'    		, 'length', 'min'=>3), 
                array('sort'        	, 'length', 'min'=>3),
                array('desc'        	, 'boolean'),
                array('page'        	, 'numerical'),
                array('group'       	, 'length', 'min'=>3),
                array('email'       	, 'email'),
                array('creationTo, creationFrom'        , 'numerical'),
            );
	}
        public function Report($val){
            $this->type = $val;
            $acc = new Account();
            $info = $acc->GetInfo();
            $paretCode=$acc->GetParentCode();
			$parentInfo = $acc->getParentContacts();
			
			
            switch ($this->type) {
		        case 1: //OpenTrades
					if( $info->Code == 600 ||  $parentInfo["Code"] == 600 || in_array($info->Code, [11106, 11107, 11109, 11110])){
						$this->tableHead = array('Name','Commission','Swap','Profit');
					}
					/* elseif($parentInfo["Code"] == 600) {//TODO IVAN 8.5.2017
						$this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','Limit','Stop','Swap','Profit','Pips' ,'OpenTime','AccountCurrency','Platform');
					} */
                    elseif(wlParams::get('officeCode') == 50){
						$this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','Limit','Stop','Swap','Profit','Pips' ,'OpenTime','AccountCurrency','Platform');
                    }elseif(Yii::app()->params['type'] == 'eforex' && $info->Code == 15849){
						$this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','Limit','Stop','Swap','Profit','Pips' ,'OpenTime','AccountCurrency','Platform');
                    }elseif(in_array(wlParams::get('officeCode'),[83,84,90,91,92,93])){
                        $this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','Limit','Stop','Commission','Swap','Profit','Pips' ,'OpenTime','AccountCurrency');
                    }else{
						$this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','Limit','Stop','Commission','Swap','Profit','Pips' ,'OpenTime','AccountCurrency','Platform');
					}
	           	break;	
                case 2: //CloseTrades
					if(wlParams::get('officeCode') == 22){
						if($info->Type == 3 || $info->Type == 2)
						    $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','AccountCurrency'); //sp
						elseif ($info->Type == 4)
                            $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','AccountCurrency'); //ib
					}else{
						if($info->Type == 2){ //sv
//                            if(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
                            if (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70])){
						        $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips',/* 'SalesRebates', 'Rebates','Spread',*/'AccountCurrency');
                            }elseif(in_array(wlParams::get('officeCode'),[83,84])){
                                $this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips', /* 'SalesRebates', */ 'Rebates', /* 'Spread', */ 'AccountCurrency');
                            }elseif(in_array(wlParams::get('officeCode'),[90,91,92,93])){
                                $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','Rebates','AccountCurrency');
                            }else{
						        $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips',/* 'SalesRebates', */'Rebates','Spread','AccountCurrency');
                            }
                        }elseif ($info->Type == 3){ //sp
//                            if(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
                            if (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70,90,91,92,93])){
								$this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips',/* 'SalesRebates', 'Spread',*/'AccountCurrency'); //sp
                            }elseif($info->Code == 600 || $parentInfo["Code"] == 600){
								$this->tableHead = array('Name','Commission','Swap','Profit'); //sp
                            }elseif(in_array(wlParams::get('officeCode'),[83,84])){
                                $this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips',/* 'SalesRebates', 'Spread', */'AccountCurrency');
                            }else{
								$this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips',/* 'SalesRebates', */'Spread','AccountCurrency'); //sp
							}
						}
						elseif ($info->Type == 4){ //ib
                            if($parentInfo["Code"] == 600){//TODO IVAN 8.5.2017
                                $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Swap','ClosePrice','CloseTime','Profit','Pips','AccountCurrency'); //ib
//                            }elseif(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
                            }elseif (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70])){
								$this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','AccountCurrency'); //ib
                            }elseif (in_array(wlParams::get('officeCode'),[90,92,93])){
                                $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','Rebates','AccountCurrency'); //ib
							}elseif(wlParams::get('officeCode') == 50){
								$this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Swap','ClosePrice','CloseTime','Profit','Pips','AccountCurrency'); //ib
							}elseif(Yii::app()->params['type'] == 'eforex' && $info->Code == 15849){
                                $this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Swap','ClosePrice','CloseTime','Profit','Pips','Rebates','AccountCurrency'); //ib
                            }elseif(in_array(wlParams::get('officeCode'),[83,84])){
                                $this->tableHead = array('Ticket','Login','Name','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','AccountCurrency'); //ib
                            }else{
								$this->tableHead = array('Ticket','Login','Name','Platform','Type','Symbol','Volume','OpenPrice','OpenTime','Stop','Limit','Commission','Swap','ClosePrice','CloseTime','Profit','Pips','Rebates','Spread','AccountCurrency'); //ib

							}
						} 
					}
					if($info->Type == 6) {
                        if (in_array(wlParams::get('officeCode'), [83, 84])) {
                            $this->tableHead = $this->tableHead = array('Ticket', 'Login', 'Name', 'Type', 'Symbol', 'Volume', 'OpenPrice', 'OpenTime', 'Stop', 'Limit', 'Commission', 'Swap', 'ClosePrice', 'CloseTime', 'Profit', 'Pips', 'AccountCurrency'); //trader
                        } else {
                            $this->tableHead = $this->tableHead = array('Ticket', 'Login', 'Name', 'Platform', 'Type', 'Symbol', 'Volume', 'OpenPrice', 'OpenTime', 'Stop', 'Limit', 'Commission', 'Swap', 'ClosePrice', 'CloseTime', 'Profit', 'Pips', 'AccountCurrency'); //trader
                        }
                    }
			   break;
                case 3: //AccountList
									if($info->Type == 2) //sv
                                        if(in_array(wlParams::get('officeCode'),[83,84])) {
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity', /* 'Platform', */ 'Currency','IBName', 'Sales', 'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                            }
									else {
                                        $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency','IBName', 'Sales', 'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                    }
									if($info->Type == 3){ //sp
										if($info->Code == 596 || $info->Code == 600 || $parentInfo["Code"] == 600 || $info->Code == 624){
											$this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency','IBName','Enabled','Country','City','RegistrationDate');
                                        }elseif(wlParams::get('officeCode') == 83){
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Currency','IBName','Enabled','Country','City','RegistrationDate');
                                        }else{
											$this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency','IBName','Enabled','Country','Phone','Email','City','Address','RegistrationDate');
										}
										//$this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency','IBName','Enabled','Country','Phone','Email','City','Address','RegistrationDate');
									}
									if($info->Type == 4){ //ib
                                        if(wlParams::get('officeCode') == 80){
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency'/* ,'Sales' */,'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                        }elseif(in_array(wlParams::get('officeCode'), [83, 84])) {
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Currency'/* ,'Sales' */,'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                        } else{
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency'/* ,'Sales' */,'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                        }
                                    }
									if($info->Type == 6){ //trader
                                        if(wlParams::get('officeCode') == 80 ){
                                            $this->tableHead = array('Login','PlatformType','Name','Balance'/*,'Equity'*/, 'Platform','Currency',/* 'IBName' ,*/'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                       }elseif(wlParams::get('officeCode') == 83){
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Currency',/* 'IBName' ,*/ 'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                        }else{
                                            $this->tableHead = array('Login','PlatformType','Name','Balance','Equity','Platform','Currency',/* 'IBName' ,*/'Enabled','Country','Phone','Email','City','Address','RegistrationDate');
                                        }
                                    }

                break;
                case 4: //DWA 
					if($info->Type == 2) //sv
                        if(in_array(wlParams::get('officeCode'),[83,84])) {
                            $this->tableHead = array('AccountID', 'TicketID', 'Name', 'SalesName', 'IBName', 'Amount', 'Date', 'Comment');
                        }else{
                            $this->tableHead = array('AccountID', 'TicketID', 'Name', 'Platform', 'SalesName', 'IBName', 'Amount', 'Date', 'Comment');
                        }
					if($info->Type == 3 ) //sp
                        if(in_array(wlParams::get('officeCode'),[83,84])) {
                            $this->tableHead = array('AccountID', 'TicketID', 'Name',  'IBName', 'Amount', 'Date', 'Comment');
                        }else{
                            $this->tableHead = array('AccountID', 'TicketID', 'Name', 'Platform', 'IBName', 'Amount', 'Date', 'Comment');
                        }
					if($info->Type == 4)	//ib		
                        if(in_array(wlParams::get('officeCode'),[83,84])) {
                            $this->tableHead = array('AccountID', 'TicketID', 'Name',  'Amount', 'Date', 'Comment');
                        }else{
                            $this->tableHead = array('AccountID', 'TicketID', 'Name', 'Platform', 'Amount', 'Date', 'Comment');
                        }
					if($info->Type == 6)	//trader
                        if(in_array(wlParams::get('officeCode'),[83,84])) {
                            $this->tableHead = array('AccountID', 'TicketID', 'Name',  'Amount', 'Date', 'Comment');
                        }
					else
					    {
                        $this->tableHead = array('AccountID','TicketID','Name','Platform','Amount','Date','Comment');
					    }
                break;
                case 5: //SummaryReport
					if(wlParams::get('officeCode') == 22){
					   if($info->Type == 2) $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions','Swaps','Volume');  //sv
					   if($info->Type == 3){ //sp
							if($paretCode<23 || $paretCode>27){
							    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions','Swaps','Volume');
							}
							elseif(in_array(wlParams::get('officeCode'),[83,84])){
                                $this->tableHead = array('AccountID','Name','Deposit','Withdrawal','Volume');
                            }
							else{
							    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Volume');}
						}
						if ($info->Type == 4){  //ib	
							if(($paretCode<23 || $paretCode>27)) {
                                $this->tableHead = array('AccountID', 'Name', 'Platform', 'Deposit', 'Withdrawal', 'Commissions', 'Swaps', 'Volume');
                            }elseif(in_array(wlParams::get('officeCode'),[83,84,90,91,92,93])){
                                $this->tableHead = array('AccountID','Name','Deposit','Withdrawal','Volume');
							}else{
								$this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Volume');
							}
						}		
					}else{
							if($info->Type == 2)
							    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions',/* 'SalesRebates', */'Swaps','Volume');  //sv
						   if($info->Type == 3){
								if($paretCode<23 || $paretCode>27){
									if($info->Code == 600 || $parentInfo["Code"] == 600 ){
										$this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal',/* 'SalesRebates', */'Swaps','Volume');
                                    }elseif(in_array(wlParams::get('officeCode'),[83,84])){
                                        $this->tableHead = array('AccountID','Name','Deposit','Withdrawal','Commissions',/* 'SalesRebates', */'Swaps','Volume');

                                    }else{
										$this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions',/* 'SalesRebates', */'Swaps','Volume'); 
									}
								}
								else{
									$this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Volume');
								}
							}//sp
							if ($info->Type == 4){  //ib	


                                if($parentInfo["Code"] == 600){//TODO IVAN 8.5.2017
                                    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Swaps','Volume');
//                                }elseif(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
                                }elseif (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70])){
								    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions','Swaps','Volume');
                                }elseif (in_array(wlParams::get('officeCode'),[83,84])){
                                    $this->tableHead = array('AccountID','Name','Deposit','Withdrawal','Commissions','Swaps','Volume');
								}elseif(wlParams::get('officeCode') == 50){
									$this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Swaps','Volume');
								}elseif(($paretCode<23 || $paretCode>27) && !in_array($info->Code, [11106, 11107, 11109, 11110])){
                                    if(Yii::app()->params['type'] == 'eforex' && $info->Code == 15849){

									    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Rebates','Swaps','Volume');
                                    }else{
									    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions','Rebates','Swaps','Spread','Volume');
                                    }
								}else{
									$this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Volume');
								}


							}	
					}
					if($info->Type == 6) //trader
                        if(wlParams::get('officeCode') == 83) {
                            $this->tableHead = array('AccountID', 'Name', 'Deposit', 'Withdrawal', 'Commissions', 'Swaps', 'Volume');
                        }
					else
					    {
					    $this->tableHead = array('AccountID','Name','Platform','Deposit','Withdrawal','Commissions','Swaps','Volume');
					    }
                break;
                case 6: //FindByEmail
                        $this->tableHead = array('Login','Name','IBName','IBNumber','Sales','Office');
                break;	
                case 7: //CloseTradesSummaryReport
					if(wlParams::get('officeCode') == 22){
                        if($info->Type == 3 || $info->Type == 2) $this->tableHead = array('Type','Volume','Comission','Swaps','Profit'); //sp
                        elseif ($info->Type == 4)  $this->tableHead = array('Type','Volume','Comission','Swaps','Profit'); //ib
					}else{
						if($info->Type == 2){ //sv
//                            if(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
                            if (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70,83,84])){
						        $this->tableHead = array('Type','Volume','Comission'/* ,'SalesRebates' ,'Rebates'*/,'Swaps','Profit'/*,'Spread'*/);
                            }elseif (in_array(wlParams::get('officeCode'),[90,91,92,93])){
                                $this->tableHead = array('Type','Volume','Comission'/* ,'SalesRebates' */,'Rebates','Swaps','Profit');
                            }else{
						        $this->tableHead = array('Type','Volume','Comission'/* ,'SalesRebates' */,'Rebates','Swaps','Profit','Spread');
                            }
                        }elseif ($info->Type == 3){ //sp
//                            if(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){

                            if (in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70,83,84,90,91,92,93])){
                                $this->tableHead = array('Type','Volume','Comission',/* 'SalesRebates', */'Swaps','Profit'/*,'Spread'*/); //sp

                                //var_dump($this->tableHead);die();
                            }elseif (in_array(wlParams::get('officeCode'),[78])){
								$this->tableHead = array('Volume','Comission','Swaps','Profit','Spread'); //sp
                            }elseif($info->Code == 600 || $parentInfo["Code"] == 600){
								$this->tableHead = array('Type','Volume',/* 'SalesRebates', */'Swaps','Profit','Spread'); //sp
							}else{
                                $this->tableHead = array('Type','Volume','Comission',/* 'SalesRebates', */'Swaps','Profit','Spread'); //sp
                            }

                        }elseif ($info->Type == 4){ //ib
						    if($parentInfo["Code"] == 600){//TODO IVAN 8.5.2017
                                $this->tableHead = array('Type','Volume','Swaps','Profit');
//                            }elseif(wlParams::get('officeCode') == 44 || wlParams::get('officeCode') == 60 || wlParams::get('officeCode') == 62 || wlParams::get('officeCode') == 64 || wlParams::get('officeCode') == 65 || wlParams::get('officeCode') == 68){
                            }elseif(in_array(wlParams::get('officeCode'),[44,60,62,64,65,67,69,70,83,84])){
								$this->tableHead = array('Type','Volume','Comission','Swaps','Profit'); //ib
							}elseif(wlParams::get('officeCode') == 50){
								$this->tableHead = array('Type','Volume','Swaps','Profit'); //ib
							}elseif(Yii::app()->params['type'] == 'eforex' && $info->Code == 15849){
								$this->tableHead = array('Type','Volume','Rebates','Swaps','Profit'); //ib
                            }elseif(in_array(wlParams::get('officeCode'),[78])){
                                $this->tableHead = array('Volume','Comission','Rebates','Swaps','Spread','Profit'); //ib
                            }else{
								$this->tableHead = array('Type','Volume','Comission','Rebates','Swaps','Spread','Profit'); //ib
							}
						}
					}
                        if($info->Type == 6) $this->tableHead = array('Type','Volume','Comission','Swaps','Profit'); //trader
                break;	
                case 8: //Company GetIBAccountsReport	
                         $this->tableHead = array('Type','Volume','Comission','Swaps'); 
                break;
                case 9: //Company Transaction
                         $this->tableHead = array(
                                'Return'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Note'=>'allHide','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Deposit'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','IBCode'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Withdrawal'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','IBCode'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Bonus Promotion'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','IBCode'=>'pc','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Note'=>'allHide','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Bad Tick'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'IB Payment'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Bonus Withdrawal'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Internal Transfer'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','IBCode'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Note'=>'allHide','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Other'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Office Promotion'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'Money4me'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                'payment'=>array('Date'=>'pc','Type'=>'pc tab mob','Category'=>'pc tab','Office'=>'pc','Sales'=>'pc tab','Platform'=>'pc tab mob','Ammount'=>'pc','AmmountToSend'=>'pc tab mob','User'=>'allHide','Status'=>'pc','Customer'=>'pc tab','Account'=>'pc','CreditedAccount'=>'pc tab mob','CreditedPlatform'=>'pc tab mob','Currency'=>'pc','CreditCard'=>'allHide'),
                                
                            );
                break;
                case 10: //Company DailyReport
                    if($info->Type == 4 && $parentInfo["Code"] == 600) {//TODO IVAN 8.5.2017
                         $this->tableHead = array('serverName','prevBalance','balance','currentEquity','prewEquity','floatingPL','serverId','prewFloatingPL','dwa','realizedPL','swaps','plEQBasis','plEqCalc','Difference','BalFloating','EQDiff');
                    }else{
                         $this->tableHead = array('serverName','prevBalance','balance','currentEquity','prewEquity','floatingPL','serverId','prewFloatingPL','dwa','realizedPL','swaps','commission','plEQBasis','plEqCalc','Difference','BalFloating','EQDiff');
                    }
                break;
                case 11: //User List
						if($info->Type == 4){
							$this->tableHead = array('UserID','Name','Email','Phone','Address','Language','State','RequestState','RequestComment','UserType','AccountCount','Birthday','Country','Enable','RegistrationDate','ParentName','LastComment'); 
							//var_dump($this->tableHead);
						}elseif($info->Type == 3 && wlParams::get('parentBonusActivation')){
							$this->tableHead = array('UserID','Name','Email','Phone','Address','Language','State','RequestState','RequestComment','BonusState','UserType','AccountCount','Birthday','Country','Enable','RegistrationDate','ParentName'/* ,'LeadState','LeadRemind','LeadPriority' */,'Source','LastComment'); 
							//var_dump('111');
						}else{
							$this->tableHead = array('UserID','Name','Email','Phone','Address','Language','State','RequestState','RequestComment','UserType','AccountCount','Birthday','Country','Enable','RegistrationDate','ParentName'/* ,'LastComment','LeadState','LeadRemind','LeadPriority' */,'Source','LastComment'); 
							//var_dump('222');
						}
						//var_dump($this->tableHead);
						/* var_dump('aaa'.$info->Type);
						var_dump($this->tableHead); */
                break;
                case 12: //payment report for IB 
                    //$this->type = 9;
                    if($info->Type == 4 && $parentInfo["Code"] == 600){//TODO IVAN 8.5.2017
                        $this->tableHead = array('date','accountID','deposit','withdrawal','balance','prewbalance','currency','realizedPL','netDeposit','swaps');
                    }elseif($info->Type == 3){
						$this->tableHead = array('date','accountID','deposit','withdrawal','balance','prewbalance','currency','realizedPL','netDeposit','swaps','commissions','rebates','spread'/* ,'salesRebates' */);						
					}else{
						$this->tableHead = array('date','accountID','deposit','withdrawal','balance','prewbalance','currency','realizedPL','netDeposit','swaps','commissions','rebates','spread');						
					}
                break;
            
            }



		//	var_dump($this->tableHead);
			if((isset($info->HideRebates) && $info->HideRebates) || $info->Code == 596 || $info->Code == 600){
				$this->tableHead = CArray::remove_by_value($this->tableHead, 'Rebates');
				$this->tableHead = CArray::remove_by_value($this->tableHead, 'SalesRebates');
			}


			
			if(isset($info->HideSpread) && $info->HideSpread){
				$this->tableHead = CArray::remove_by_value($this->tableHead, 'Spread');
			}

			if(wlParams::get('officeCode') == 78){
				$this->tableHead = CArray::remove_by_value($this->tableHead, 'Platform');
			}



			
			//	var_dump($this->tableHead, isset($info->HideSpread), $info->HideSpread);die();
			
			//var_dump($this->tableHead);die();
        }
		
		
	
		
		public function getLabelsHead($key){
			$lables = array('Ticket'=>Yii::t("main","134_ticket"), 'Login'=>Yii::t("main","122_login"), 'Name'=>Yii::t("main","123_name"), 'Type'=>Yii::t("main","135_type"), 'Symbol'=>Yii::t("main","136_symbol"), 'Volume'=>Yii::t("main","137_volume"), 'OpenPrice'=>Yii::t("main","138_open_price"),  'Limit'=>Yii::t("main","139_limit"), 'Stop'=>Yii::t("main","140_stop"), 'Commission'=>Yii::t("main","141_commission"), 'Swap'=>Yii::t("main","142_swap"), 'Profit'=>Yii::t("main","143_profit"), 'Pips'=>Yii::t("main","144_pips"), 'OpenTime'=>Yii::t("main","145_open_time"), 'AccountCurrency'=>Yii::t("main","146_currency"), 'Platform'=>Yii::t("main","124_platform"), 'ClosePrice'=>Yii::t("main","148_close_price"), 'CloseTime'=>Yii::t("main","147_close_time"), /* 'SalesRebates'=>Yii::t("sp","20_sales_rebates"), */ /* 'salesRebates'=>Yii::t("sp","20_sales_rebates"), */ 'Spread'=>Yii::t("main","149_spread"),'spread'=>Yii::t("main","149_spread"), 'Rebates'=>Yii::t("sp","20_sales_rebates"), 'rebates'=>Yii::t("sp","20_sales_rebates"), 'PlatformType'=>Yii::t("main","124_1_Platform_Type"), 'Balance'=>Yii::t("main","126_balance"), 'balance'=>Yii::t("main","126_balance"), 'Equity'=>Yii::t("main","127_equity"), 'Currency'=>Yii::t("main","146_currency"), 'currency'=>Yii::t("main","146_currency"), 'IBName'=>Yii::t("sp","16_ib_name"), 'Sales'=>Yii::t("sp","sp_name"), 'Enabled'=>Yii::t("main","110_enabled_1"), 'Country'=>Yii::t("main","129_country"), 'Phone'=>Yii::t("main","130_phone"), 'Email'=>Yii::t("main","131_email"), 'City'=>Yii::t("main","132_city"), 'Address'=>Yii::t("main","133_address"), 'RegistrationDate'=>Yii::t("sp","111_creationDate"), 'AccountID'=>Yii::t("main","157_account"), 'accountID'=>Yii::t("main","157_account"), 'TicketID'=>Yii::t("main","134_ticket"), 'SalesName'=>Yii::t("sp","140_spname"), 'Amount'=>Yii::t("main","152_amount"), 'Date'=>Yii::t("main","153_date"), 'Comment'=>Yii::t("main","154_comment"), 'Deposit'=>Yii::t("main","155_deposit"), 'deposit'=>Yii::t("main","155_deposit"), 'Withdrawal'=>Yii::t("main","156_withdrawal"), 'withdrawal'=>Yii::t("main","156_withdrawal"), 'Commissions'=>Yii::t("main","141_commission"), 'commissions'=>Yii::t("main","141_commission"), 'Swaps'=>Yii::t("main","151_swaps"), 'swaps'=>Yii::t("main","151_swaps"), 'Volume'=>Yii::t("main","137_volume"), 'IBNumber'=>Yii::t("sp","15_ibnumber"), 'Sales'=>Yii::t("main","128_sales"), 'Office'=>Yii::t("sp","23_office"), 'Comission'=>Yii::t("main","141_commission"), 'UserID'=>Yii::t("main","20_Login"), 'Language'=>Yii::t("main","840_lang"), 'State'=>Yii::t("main","841_state"), 'RequestState'=>Yii::t("main","844_request_state"), 'RequestComment'=>Yii::t("main","845_request_comment"), 'UserType'=>Yii::t("main","842_user_type"), 'AccountCount'=>Yii::t("main","843_acc_count"), 'Birthday'=>Yii::t("main","29_birthday"), 'Enable'=>Yii::t("main","902_enable"), 'ParentName'=>Yii::t("main","886_parent_name"), 'BonusState'=>Yii::t("sp","182_bonus"), 'LastComment'=>Yii::t("sp",'107_comment'), 'LeadState'=>Yii::t("sp",'109_state'), 'LeadRemind'=>Yii::t("sp",'106_remind'), 'LeadPriority'=>Yii::t("sp",'105_priority'), 'Source'=>Yii::t("sp",'114_source'), 'date'=>Yii::t("main",'153_date'), 'realizedPL'=>Yii::t("sp",'215_realized_pl'), 'prewbalance'=>Yii::t("sp",'214_prev_balance'), 'netDeposit'=>Yii::t("main",'9_net_deposit'), 'GroupAccount'=>Yii::t("sp",'216_group_account'), 'TradingAccount'=>Yii::t("main",'330_trading_account'), 'TypeName'=>Yii::t("main",'135_type'), 'Ticket'=>Yii::t("main",'134_ticket'), 'GroupBalance'=>Yii::t("sp",'217_group_balance'));
			return $lables[$key];
		}
		
        //--------------------------------------------------------
        public function SetCountRowsTable($val){
            $this->countRowsTable = $val;
        }
        							
        public function SetPlatform($val){
            $this->platform = $val;								
        }
								
        public function GetPlatform(){
               return $this->platform;
       } 
	   
	   public function GetListReport(){
               return $this->listReport;
       }
								
        public function initGroup(){			
            if ($this->group != '-1') {
				if($this->group[0] == '_'){
					$this->groupIn = str_replace('_',';',substr($this->group, 1));
				}else{
					$this->groupIn = str_replace('_',';',$this->group);
				}             
            }
        }
        
		public function initDate(){	
	
            $start=$this->startDate;
            $end=$this->endDate;
		//	var_dump($start, $end);die();
            if($start == 0){
                $start = mktime("17","00","00",date("m"),date("d")-1,date("Y"));
            }else{						
				$start = date('m/d/Y', strtotime($start .' -1 day'));
				$start_d =explode("/",$start);
                $start = mktime("17","00","00",$start_d[0],$start_d[1],$start_d[2]);
            }
            if($end == 0){
                $end = mktime("16","59","59",date("m"),date("d"),date("Y"));
            }else{							
				$end_d =explode("/",$end);
				$end=mktime("16","59","59",$end_d[0],$end_d[1],$end_d[2]);
			}				
            $this->startDate = $start ; 
            $this->endDate = $end ;
						
        }  

		public function initDate_old(){	
            $start=$this->startDate;
            $end=$this->endDate;
            if($start == 0){
                $start = mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
            }else{
                $start_d =explode("/",$start);
                $start=mktime(date("H"),date("i"),date("s"),$start_d[0],$start_d[1],$start_d[2]);
            }
            if($end == 0){
                $end = mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
            }else{
                $end_d =explode("/",$end);
                $end=mktime(date("H"),date("i"),date("s"),$end_d[0],$end_d[1],$end_d[2]);
            }										
            $this->startDate = $start;
            $this->endDate = $end ;
        } 		
							
        public function ValidDate($start,$end){
            if(!$start_s =explode("/",$start,3)){return false;}
            if(!$end_e =explode("/",$end,3)){return false;}
            $pattern = "#^(\d{1,2})/(\d{1,2})/(\d{4})#"; 

            //if(@checkdate($start_s[0],$start_s[1],$start_s[2]) && @checkdate($end_e[0],$end_e[1],$end_e[2]) && strlen($start)<= $end)
            if(preg_match($pattern, $start))
            {
             return true;
            }else{

             return false;
            }

        }	
    public function GetList($null=false){ 
        $null=($null)?(1):(0); // когда 1 то вывод всех по всем 0 вывод свои клиентов
        $res = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/GetReport?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='.$this->startDate.'&to='.$this->endDate);

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($res, Yii::app()->params['json_server'].'/API/Reports/GetReport?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='.$this->startDate.'&to='.$this->endDate);die();
        }*/

        return $res;
    }

    public function SendRequest(){
		
	/* 
        $filter = 'null';       //искать слово по всем имеющимся данным (конкретного аккаунта или репорта или ...)
        $sort = 'null';         //сортировка по столбцу (передаю имя поля по которому сортировать)
        $desc = 0;              //направление сортировки
        $countRowsTable = 10;   // количество записей в таблице
        $page = 0;              // текущая страница ($page умножаем $countRowsTable)
	 */
        //if(strlen($this->filter)<2){die('ff');$this->filter = 'null';}//почемуто инициализирует пустым значением с поста		

		$this->initGroup();	
		
	//	var_dump($_POST);die();
		if(isset($_POST["quick_date"]) && !empty($_POST["quick_date"])){
			if($_POST["quick_date"]=='day'){
                $tmpEnd = $this->endDate = $tmpStart = $this->startDate = date('m/d/Y', strtotime('-1 day'));
			}elseif($_POST["quick_date"]=='week'){
				$tmpStart = $this->startDate = date('m/d/Y', strtotime(date('Y').'W'.date('W').'1 -7 days'));
				$tmpEnd = $this->endDate = date('m/d/Y', strtotime(date('Y').'W'.date('W').'5 -7 days'));
			}elseif($_POST["quick_date"]=='month'){
				$start = date('m/t/Y', strtotime('previous month'));
				$start_d = explode("/",$start);
				
                $tmpStart = $this->startDate = date('m/d/Y', mktime("00","00","00",$start_d[0],"01",$start_d[2]));
                $tmpEnd = $this->endDate = date('m/d/Y', mktime("00","00","00",$start_d[0],$start_d[1],$start_d[2]));
			//	var_dump(date('m/d/Y', $tmpStart), date('m/d/Y', $tmpEnd));die();
			}
		}else{
			$tmpStart = $this->startDate;
			$tmpEnd = $this->endDate;		
		}
		//$_POST['startDate'] = $tmpStart;
		//$_POST['endDate'] = $tmpEnd;
        $this->initDate();
		$_POST['startDate'] = date('m/d/Y H:i:s', $this->startDate);
		$_POST['endDate'] = date('m/d/Y H:i:s', $this->endDate);
		
		$this->startDate = strtotime($tmpStart);
		$this->endDate = strtotime($tmpEnd);
		
		if(isset($_POST['needGroups'])){
			if(isset($_GET['group']) && $_GET['group'] != -1 && !isset($_GET['iname'])&& !isset($_GET['refname'])){
				$this->needGroups = 0;
			}else{
				$this->needGroups = $_POST['needGroups'];				
			}
		}elseif(isset($_GET['needGroups'])){
			$this->needGroups = $_GET['needGroups'];
		}else{
			if(isset($_GET['group']) && $_GET['group'] != -1 && !isset($_GET['iname'])&& !isset($_GET['refname'])){
				$this->needGroups = 0;
			}
		}


		//var_dump($null);die();
        $page = $this->page > 0?$this->page - 1:0;
        $sort = str_replace(' ','',$this->sort);

        if(!Yii::app()->request->isAjaxRequest){
            $this->filter = 'null';
            $sort = 'null';
            $page = 0; 
            $this->desc = 0;
        }
		if(isset($_POST['transaction_type']) && $_POST['transaction_type']!=''){
			$this->filter = $_POST['transaction_type'];
		}
		$this->filter = ($this->filter == '') ? 'null' : $this->filter;
		 
		if($this->type != 3){ // demo accs only for account list
			$this->accountType = 1;
		}
		
		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$page = 0;
			$this->countRowsTable = 99999999;
		}
		
		
		/* OnlyOwnAndTraders = 0,
        InnerGroupsOwnAndTraders = 1,
        OnlyInnerGroups = 2 
		OnlyOwn = 3
		
		
		OnlyOwnAndTraders = 0 - личные и его трэйдеров
		InnerGroupsOwnAndTraders = 1 - все
		OnlyInnerGroups = 2 - только групп, которые под ним
		OnlyOwn = 3 - только личные
		 = 4 - только его трейдеров
		*/
		
		/****** new reports ******/

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

		if($this->needGroups != 2 && !Yii::app()->request->isAjaxRequest){
			if(isset($_REQUEST["check_all"]) && !isset($_REQUEST['ownAccs'])){
				if((isset($_GET['group']) && strstr($_GET['group'], ',')) || (isset($_POST['group']) && strstr($_POST['group'], ','))){
				    $ggroup = isset($_GET['group']) ? $_GET['group'] : $_POST['group'];

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

					$parts = explode(',', $ggroup);
					if($parts[1] == $info->Type || (isset($_GET['parentRole']) && $_GET['parentRole'] == $parts[1])){
						$this->needGroups = 0;
					}
				}
			}else{
				if((isset($_GET['group']) && strstr($_GET['group'], ',')) /*|| (isset($_POST['group']) && strstr($_POST['group'], ','))*/){
                    //$ggroup = isset($_GET['group']) ? $_GET['group'] : $_POST['group'];
                    $ggroup = isset($_GET['group']) ? $_GET['group'] : '';

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

					$parts = explode(',', $ggroup);
					if($parts[1] == $info->Type || (isset($_GET['parentRole']) && $_GET['parentRole'] == $parts[1])){
						$this->needGroups = 3;
					}
				}
			}
		}

        if(wlParams::get('officeCode') === 78 && $info->Type == 4){
            $this->needGroups = 1;
        }

		if($this->type == 11){
			$this->state = (isset($_GET["state"])) ? $_GET["state"] : '-1'; 
			$this->RequestState = (isset($_GET["RequestState"])) ? $_GET["RequestState"] : '-1';
			$this->creationFrom = strstr($this->creationFrom, '/') ? strtotime($this->creationFrom) : $this->creationFrom;
			$this->creationTo = strstr($this->creationTo, '/') ? strtotime($this->creationTo) : $this->creationTo;
			
			//var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetUserList?guid=' . Yii::app()->user->id . '&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&state='.$this->state.'&requestState='.$this->RequestState.'&needLeads='.$this->needLeads.'&from='.$this->creationFrom.'&to='.$this->creationTo);die();
            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetUserList?guid=' . Yii::app()->user->id . '&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&state='.$this->state.'&requestState='.$this->RequestState.'&needLeads='.$this->needLeads.'&from='.$this->creationFrom.'&to='.$this->creationTo);die();
            }*/

            $tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/GetUserList?guid=' . Yii::app()->user->id . '&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&state='.$this->state.'&requestState='.$this->RequestState.'&needLeads='.$this->needLeads.'&from='.$this->creationFrom.'&to='.$this->creationTo);
			//var_dump($tmp);die();
		}elseif($this->type == 12){
			//GetBrokerPaymentReportByDays(string guid, long from, long to, string sort, bool desc, int pageSize, int page, string filter, int? accountId, int ibID)
	
			if(isset($_REQUEST['ibID']) && !empty($_REQUEST['ibID'])){
				$ibID = $_REQUEST['ibID'];
			}
			$desc = ($this->desc == 1) ? 'true' : 'false';
			$filter = ($this->filter == 'null') ? '' : $this->filter;
			$sort = ($sort == 'null') ? '' : $sort;
			$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/GetBrokerPaymentReportByDays?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$filter.'&sort='.$sort.'&desc='.$desc.'&pageSize='.$this->countRowsTable.'&page='.$page.'&accountId='.$this->accountId.'&ibID='.$ibID);	
			//var_dump(Yii::app()->params['json_server'].'/API/Reports/GetBrokerPaymentReportByDays?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$filter.'&sort='.$sort.'&desc='.$desc.'&pageSize='.$this->countRowsTable.'&page='.$page.'&accountId='.$this->accountId.'&ibID='.$ibID, $tmp);die();



			//'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&state='.$this->state.'&requestState='.$this->RequestState.'&needLeads='.$this->needLeads.'
			
		}else{
			$this->startDate = ($this->startDate == '') ? 0 : $this->startDate;
			$this->endDate = ($this->endDate == '') ? 0 : $this->endDate;

            /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
                var_dump(Yii::app()->params['json_server'].'/API/Reports/GetReport?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page.'&accountType='.$this->accountType);die();
            }*/

			$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/GetReport?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page.'&accountType='.$this->accountType);

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump($tmp, Yii::app()->params['json_server'].'/API/Reports/GetReport?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page.'&accountType='.$this->accountType);die();
            }*/
		}
        
        $this->startDate = $tmpStart;
		$this->endDate = $tmpEnd;   
		$this->initDate_old();
		if(isset($tmp->count) && $tmp->count != null){
            $this->listReport = $tmp->reportList;
			$this->listTotal = isset($tmp->total) ? $tmp->total : 0;
            $this->countListReport = $tmp->count;
        }else{
            $this->listReport = 0;
            $this->countListReport = 0;
			$this->listTotal = 0;
        }
    }
	
    public function number_format_bmfn($number, $decimals, $dec_point = '.', $thousands_sep = ',', $notround = true){
                $sumbol = '';
                $sumbolpos = '';
                if(substr($number, 0, 1) == '$'){
                    $sumbol = '$';
                    $number = substr($number, 1);         
                }elseif (strpos($number, 'pip')) {
                     $sumbolpos = ' pip';
                }
                
                $number = number_format((float)$number, $decimals, $dec_point, $thousands_sep);
                
		if(strstr($number, $dec_point) && (float)$number!=0){ 
			$rez = rtrim($number, '0');
			//if($twozeros){
			if($rez{strlen($rez)-1}==$dec_point){
				$rez = $rez.'00';
			}elseif($rez{strlen($rez)-2}==$dec_point){
                                $rez = $rez.'0';
                        }
                            
			if(!$notround && round($rez, 2)!=0){
				$rez = round($rez, 2);
			}
			/* }else{
				$rez = ($rez{strlen($rez)-1}==$dec_point) ? str_replace($dec_point,'',$rez) : $rez; 
			} */
		}else{
			$rez = '0.00';
		}			
		return $sumbol.$rez.$sumbolpos;
	}
    public function GetDataTable(){

			$account = new Account;
			$info = $account -> GetInfo();
		   //var_dump('111', $this->attributes);die();
			$this->SendRequest();
			 
			 
			 /********* total **********/
			
			#print_r((array)$this->listTotal);
			 #echo count((array)$this->listTotal);
				if($this->countListReport>0){
					$mas_total_key=array();
					$mas_total_value=array();
					if(isset($this->listTotal) && !empty($this->listTotal)){						
						foreach($this->listTotal as $k=>$v){
							$mas_total_key[]=$k;
							$mas_total_value[$k]=$v;
						}
					}
				}
		
			            
           $table  = '';   		   
          if(is_array($this->listReport) && count($this->listReport)>0){ /// проверка на пустую таблицу
			$this->thead = '<tr>';


  		for($i=0; $i<count($this->listReport);$i++){
			$odd = ($i%2==0) ? 'odd' : 'even';
                         $table.= '<tr class="'.$odd.'">';
						 $enable = isset($this->listReport[$i]->Enable) ? $this->listReport[$i]->Enable : '';



                         foreach ($this->tableHead as $row){
							if($row=="OpenTime" || $row=="CloseTime" || $row=="Date"){
							 $this->listReport[$i]->$row=str_replace("T"," ",$this->listReport[$i]->$row);
									$this->listReport[$i]->$row=substr($this->listReport[$i]->$row,0,19);
							} 
                            
							if ($row=="Login"){ 						
								if ( strtolower(str_replace(' ', '_',$info->Name)) == strtolower( $this->listReport[$i]->Name)) {
									$this->listReport[$i]->$row = '<a href="/accountOverview.html?acnumber='.$this->listReport[$i]->$row.'">'.$this->listReport[$i]->$row.'</a>';
								}
							}
							
							//$this->tableHead = array('date','accountID','deposit','withdrawal','balance','prewbalance','currency','realizedPL','netDeposit','swaps','commissions','rebates','spread','salesRebates');
						 
							if($row=="Balance" || $row=="Equity" || $row=="Volume" || $row=="Profit" || $row=="Amount" || $row=="Deposit" || $row=="Withdrawal" || $row=="Commission" || $row=="Comission" || $row=="deposit" || $row=="balance" || $row=="prewbalance" || $row=="realizedPL" || $row=="netDeposit" || $row=="swaps" /* || $row=="salesRebates" */){
								$this->listReport[$i]->$row = $this->number_format_bmfn($this->listReport[$i]->$row, 2, '.', ',',true);
							}elseif($row=="Spread"){
								$this->listReport[$i]->$row = $this->number_format_bmfn($this->listReport[$i]->$row, 4, '.', ',',true);
							}elseif($row=="Rebates" || /* $row=="SalesRebates" || */ $row=="Swaps" || $row=="Swap"){
								$this->listReport[$i]->$row = $this->number_format_bmfn($this->listReport[$i]->$row, 4, '.', ',',true);
							}elseif($row=="ClosePrice" || $row=="OpenPrice" || $row=="Limit" || $row=="Stop"){
								$this->listReport[$i]->$row = $this->number_format_bmfn($this->listReport[$i]->$row, 5, '.', ',',true);
							}elseif($row=="Pips"){
								$this->listReport[$i]->$row = number_format($this->listReport[$i]->$row);
							}elseif($row=="AccountCount" && $this->type == 11){
								$this->listReport[$i]->$row = '<span class="accCountNum">'.number_format($this->listReport[$i]->$row).'</span>';
							}elseif($row=="Birthday"){
								$this->listReport[$i]->$row = ((float)$this->listReport[$i]->$row != -62135596800) ? date('m/d/Y', $this->listReport[$i]->$row) :  '';
							}elseif($row=="RegistrationDate"){
								$this->listReport[$i]->$row = ($this->listReport[$i]->$row == '1970-01-01T00:00:00' || $this->listReport[$i]->$row == '') ? '' : date('m/d/Y', strtotime($this->listReport[$i]->$row));
							}elseif($row=="Enable"){
								$this->listReport[$i]->$row = ($this->listReport[$i]->$row) ? Yii::t("main","110_enabled") : Yii::t("main","111_disabled");
							}elseif($row=="LeadRemind"){
								$this->listReport[$i]->$row = date('m/d/Y', strtotime($this->listReport[$i]->$row));
							}elseif($row=="LeadState"){
								$Lead = new Lead('UserLead');
								$array = $Lead->getStaticArray('State');
								$this->listReport[$i]->$row = $array[$this->listReport[$i]->$row];
							}elseif($row=="date"){
								$this->listReport[$i]->$row = '<span class="repTableInner redDate"><span class="repValue">'.date('m/d/Y', strtotime($this->listReport[$i]->$row)).'</span><input type="hidden" name="rType" value="" /></span>';
							}elseif($row=="withdrawal"){
								$this->listReport[$i]->$row = '<span class="repTableInner">'.$this->number_format_bmfn($this->listReport[$i]->$row, 2, '.', ',',true).'<input type="hidden" name="rType" value="1,3,4" /></span>';
								/* if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){ balance
									var_dump($this->listReport[$i]->$row);die();									
								} */
							}elseif($row=="rebates"){
								$this->listReport[$i]->$row = '<span class="repTableInner">'.$this->number_format_bmfn($this->listReport[$i]->$row, 2, '.', ',',true).'<input type="hidden" name="rType" value="5" /></span>';
							}elseif($row=="commissions"){
								$this->listReport[$i]->$row = '<span class="repTableInner">'.$this->number_format_bmfn($this->listReport[$i]->$row, 2, '.', ',',true).'<input type="hidden" name="rType" value="6" /></span>';
							}elseif($row=="spread"){
								$this->listReport[$i]->$row = '<span class="repTableInner">'.$this->number_format_bmfn($this->listReport[$i]->$row, 2, '.', ',',true).'<input type="hidden" name="rType" value="8" /></span>';
							}elseif($row=="LeadPriority"){
								$Lead = new Lead('UserLead');
								$array = $Lead->getStaticArray('Priority');
								$this->listReport[$i]->$row = $array[$this->listReport[$i]->$row];
							}elseif($row=="Source"){
								$Lead = new Lead('UserLead');
								$array = $Lead->getStaticArray('Source');
								$this->listReport[$i]->$row = ($this->listReport[$i]->$row == '') ? '' : $array[$this->listReport[$i]->$row];
		
								//var_dump($this->listReport[$i],  $array);die();
							}elseif($row=="BonusState"){
								$selected = ($this->listReport[$i]->$row) ? 'checked="checked"' : '';									
								$this->listReport[$i]->$row = '<input type="checkbox" id="'.$this->listReport[$i]->UserID.'" class="user_bonus" '.$selected.' /><label for="'.$this->listReport[$i]->UserID.'">&nbsp;</label>';
							} 
							

                            $this->listReport[$i]->$row=($row=="Commissions") ? $this->number_format_bmfn(str_replace('-','',$this->listReport[$i]->$row), 2, '.', ',',true) : $this->listReport[$i]->$row;
						

                            if($this->type==3){
                                if($row=="PlatformType"){
                                    $class_name = ($this->listReport[$i]->$row=='Live') ? "listReportAccountTypeLive" : "listReportAccountTypeDemo";
                                    $this->listReport[$i]->$row =  '<div class='.$class_name.'>'.$this->listReport[$i]->$row.'</div>';
                                }
                            if($row=="Enabled")
                                  $this->listReport[$i]->$row=($this->listReport[$i]->$row==1) ? Yii::t("main","110_enabled") : Yii::t("main","111_disabled");
                            }
							
							
							//пересмотреть!!!!!!!!!!!!!!!!!!!!!
							if(Yii::app()->language=="cn"){
								if($this->type==7){
							 
									if($row=="Type"){
										$this->listReport[$i]->$row=str_replace("Forex","外汇",$this->listReport[$i]->$row);
										$this->listReport[$i]->$row=str_replace("CrudeOil","原油",$this->listReport[$i]->$row);
										$this->listReport[$i]->$row=str_replace("Futures","期货",$this->listReport[$i]->$row);
										$this->listReport[$i]->$row=str_replace("Gold","黄金",$this->listReport[$i]->$row);
										$this->listReport[$i]->$row=str_replace("Silver","白银",$this->listReport[$i]->$row);
									}
								}
							}
														
							$bg=($this->listReport[$i]->$row<0)?('class="red_report_minus"'):false;
							$table.='<td '.$bg.'>'.$this->listReport[$i]->$row.'</td>';
                            
							if($i == 0){
								$this->thead .= '<th class="h_'.$row.'">'.$this->getLabelsHead($row).'</th>';								
							}
							
                         }
						if($this->type == 11 && !isset($_POST['allReport'])){ // open acc button for UserList  
							$assign = ($info->Type == 2 && (int)$info->ID == (int)$this->listReport[$i]->ParentID) ? '<div class="lead_assign icon-29usergroup action_icon" title="'.Yii::t("main","884_appoint").'" ></div>' : '';
							$editUser = in_array((int)$this->listReport[$i]->RequestStateNum, array(0,2)) ? '<a class="lead_edit_new icon-32pencil action_icon" target="_blank" href="/createUser.html?login='.$this->listReport[$i]->UserID.'" title="'.Yii::t("main","374_edit").'" ></a>' : '';
							$openAcc = ($enable != '' && $enable) ? '<div class="lead_edit icon-59chartadd action_icon" title="'.Yii::t("main","847_new_account").'" ><input type="hidden" value="'.$this->listReport[$i]->UserID.'" class="hidden_login" /></div>' : '';
							$addComment = '<div class="user_comment icon-93viewcomments action_icon" title="'.Yii::t("sp","107_comment").'" ><input type="hidden" value="'.$this->listReport[$i]->UserID.'" class="hidden_login" /></div>';
							$table.='<td><div>'.$addComment.$openAcc.$editUser.$assign.'</div></td>';
						}
                         $table.= '</tr>';
                    }
						
					$this->thead .= '</tr>';
						/********* total **********/
						if($this->type != 11){						
							if($this->countListReport>0){
							 $table.='<tr style="background-color:rgba(255,0,0,.1);" title="'.Yii::t("main","112_summary").'">';
								foreach($this->tableHead as $row){
								
									if(in_array($row,$mas_total_key) && $row!="OpenTime" && $row!="CloseTime" && $row!="date" && $row!="accountID" && $row!="currency"){
										
										if($row=="Commissions" && $this->type==5)
											$mas_total_value[$row]=str_replace('-','',$mas_total_value[$row]);
																			
																			
                                                                                        if($row=="Balance" || $row=="Equity" || $row=="Volume" || $row=="Profit" || $row=="Amount" || $row=="Deposit" || $row=="Withdrawal" ){
                                                                                                       $mas_total_value[$row] = $this->number_format_bmfn($mas_total_value[$row], 2, '.', ',',true);
                                                                                       }elseif($row=="Spread"){
                                                                                                       $mas_total_value[$row] = $this->number_format_bmfn($mas_total_value[$row], 4, '.', ',',true);
                                                                                       }elseif($row=="Rebates" || /* $row=="SalesRebates" || */ $row=="Swaps" || $row=="Swap"){
                                                                                                       $mas_total_value[$row] = $this->number_format_bmfn($mas_total_value[$row], 4, '.', ',',true);
                                                                                       }elseif($row=="ClosePrice" || $row=="OpenPrice" || $row=="Limit" || $row=="Stop"){
                                                                                                       $mas_total_value[$row] = $this->number_format_bmfn($mas_total_value[$row], 5, '.', ',',true);
                                                                                       }elseif($row=="Pips"){
                                                                                                       $mas_total_value[$row] = number_format($mas_total_value[$row]);
                                                                                       }else{
                                                                                                  $mas_total_value[$row] = $this->number_format_bmfn($mas_total_value[$row], 2, '.', ',',true);
                                                                                       }								
										$table.='<td class="border-top" >'.$mas_total_value[$row].'</td>';
									}else{
										if(($this->type==2 && $row=="Ticket") || (($row=="Login"  || $row=="AccountID") && ($this->type!=2 && $this->type!=7)) || ($this->type==7 && $row=="Type")){
											$table.='<td class="border-top" ><strong>'.Yii::t("main","112_summary").':</strong></td>';
										}
										else{		
											$table.='<td class="border-top" >&nbsp;</td>';
										}
									}
								
								}
								$table.="</tr>";
							}
						}
						
										
          }else {
                $table.= '<tr><td style="text-align: center; display:table-cell;" colspan="0"><br>'.Yii::t("main","107_no_reports").'<br>&nbsp;</td></tr>';
            }
        return $table;
   }
    public function GetPagination(){
            $pagination = array();
            $pagination['form']         =   'report';

            $pagination['group']        =   $this->group;
            $pagination['groupAllIn']   =   $this->groupAllIn;
            $pagination['needGroups']   =   $this->needGroups;
            
            $pagination['current']      =   $this->page;
            $pagination['count']        =   $this->countListReport;     //всего колл клиентов на стр.
            $pagination['itemsOnPage']  =   $this->countRowsTable;      //колл на странице
            

            $pagination['startDate']    =   date("n/j/Y", $this->startDate);
            $pagination['endDate']      =   date("n/j/Y", $this->endDate);
            $pagination['platform']     =   $this->platform;
            $pagination['filter']       =   $this->filter;
            $pagination['state']       	=   $this->state;
            $pagination['RequestState'] =   $this->RequestState;
            
            $pagination['email']        =   $this->email;
            
            return $pagination;
   }
    public function GetTotal(){
		$array_total=(array)$this->listTotal;
		return $array_total;
	 }
    public function GetByEmailTable(){
       $this->initGroup();	
        $this->initDate();
        if(strlen($this->filter)<3){$this->filter = 'null';}	
        $page = $this->page > 0?$this->page - 1:0;
        $sort = str_replace(' ','',$this->sort);
        if(!Yii::app()->request->isAjaxRequest){
            $this->filter = 'null';
            $sort = 'null';
            $page = 0; 
            $this->desc = 0;
        }
				$this->email=trim($this->email);
				if(empty($this->email)){
					$this->email='null';
				}
      //var_dump(Yii::app()->params['json_server'].'/API/Reports/FindAccountByEmail?guid='.Yii::app()->user->id.'&email='.$this->email.'&platform='.$this->platform.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page);
        $tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/FindAccountByEmail?guid='.Yii::app()->user->id.'&email='.$this->email.'&platform='.$this->platform.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page);

        /*if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74') {
            var_dump(Yii::app()->params['json_server'].'/API/Reports/FindAccountByEmail?guid='.Yii::app()->user->id.'&email='.$this->email.'&platform='.$this->platform.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->countRowsTable.'&page='.$page, $tmp);die();
        }*/

		//var_dump($tmp);die();
		
        if($tmp != null){
            $this->listReport = $tmp->reportList;
            $this->countListReport = $tmp->count;
        }else{
            $this->listReport = 0;
            $this->countListReport = 0;
        }
		//print_r($this->tableHead);exit();
        $table  = '';
        if($this->countListReport > 0){				
            for($i=0; $i<count($this->listReport);$i++){
                $table.= '<tr>';
				$table.='<td></td>';
                foreach ($this->tableHead as $row) {
                   
				   $table.='<td class="'.$row.'">'.$this->listReport[$i]->$row.'</td>';
                }
                $table.= '</tr>';
            }
        }else{
             $table.= '<tr><td style="text-align: center; display:table-cell;" colspan="0"><br>'.Yii::t("main","107_no_reports").'<br>&nbsp;</td></tr>';
        }
        return $table;

   }
/*--------------------------------------------------*/
   
   
   public function GetMTReport(){
        
        if (strlen($this->filter) < 2) {  $this->filter = 'null';}
        $page = $this->page > 0 ? $this->page - 1 : 0;
        $sort = strlen($this->sort) > 0 ? str_replace(' ', '', $this->sort) : 'null';
        $sort = $sort == 'Login' ? 'GrId' : $sort;

        
        $this->initDate();

        if($this->startDate == 0){ $this->startDate = mktime("17","00","00",date("m"),date("d")-7,date("Y"));}
        
        $tmp =  (array)Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Operations/GetDailyTransactionsReport?guid=' . Yii::app()->user->id .'&from='.$this->startDate  . '&to=' . $this->endDate);
       

        $table  = '';  
        if(count($tmp)>0 ){
            
            $table  = '<thead><tr>';  
            foreach ($this->tableHead as $head){
                $table  .= '<th>'.$head.'</th>';
            }
            $table  .= '</tr></thead><tbody>';
            foreach ($tmp as $dateDay => $v_dateDay){
                 $table.= '<tr><td class="newDay"  colspan="18">'.$dateDay.'</td></tr>';
            foreach ($v_dateDay as $currency => $v_currency){
                foreach ($v_currency->reportList as $list){
                     $table.= '<tr>';
                     foreach ($this->tableHead as $head){
                            if(isset($list->$head)){
                                if($head=="serverName"){
                                    $table.='<td>'.$list->$head.'</td>';
                                }elseif($head=="date"){
                                    $list->$head=substr($list->$head,0,10);
                                    $table.='<td>'.$list->$head.'</td>';
                                 }else{
                                      $bg=($list->$head < 0)?('class="red_report_minus"'):false;
                                      $list->$head = $this->number_format_bmfn($list->$head, 2, '.', ',',true);
                                      $table.='<td '.$bg.'>'.$list->$head.'</td>';
                                 }
                            }else{
                                $table.='<td> - </td>';
                            }                          
                     }
                     $table.='</tr>';
                }
                $table.='<tr class="back_tr_odd">';
                foreach ($this->tableHead as $head){
                    
                    if(isset($v_currency->total->$head)){
                         if($head=="serverName"){
                                $table.='<td>'.$v_currency->total->$head.'</td>';
                         }elseif($head=="date"){
                                $v_currency->total->$head=substr($v_currency->total->$head,0,10);
                                $table.='<td>'.$v_currency->total->$head.'</td>';
                         }else{
                              $bg=($v_currency->total->$head < 0)?('class="red_report_minus"'):false;
                              $v_currency->total->$head = $this->number_format_bmfn($v_currency->total->$head, 2, '.', ',',true);
                              $table.='<td '.$bg.'>'.$v_currency->total->$head.'</td>';
                         }
                    }elseif($head=="serverName"){
                        $table.='<td>Total for '.$currency.'</td>';
                    }else{
                        $table.='<td> - </td>';
                    }  
                }
                 $table.='</tr>';
            }}
             $table  .= '</tbody>';
        }else{
            $table.= '<tr><td style="text-align: center; display:table-cell;" colspan="0"><br>'.Yii::t("main","107_no_reports").'<br>&nbsp;</td></tr>';
        }
        return $table;
        
        
    }
   
   
    public function GetSummaryTransactionReport(){
        
        $this->initDate();	
        
        $list = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/GetSummaryTransactionReport?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate);
      //  echo Yii::app()->params['json_server'].'/API/Transactions/GetSummaryTransactionReport?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate;
      //  print_r($list);
      //  exit();
        $table  = '<thead><tr><th></th>';  
        $currency = array();
        foreach ($list as $k=>$v){
            $table  .= '<th id="'.$k.'">'.$k.'</th>';
            foreach ($v as $kk=>$vv){$currency[$kk] = $kk;}
        }
        $table  .= '</tr></thead><tbody>';
        foreach ($currency as $cur){
            $table  .= '<tr><td class="firstTd">'.$cur.'</td>';  
            foreach ($list as $k=>$v){ 
                $tmp = isset($v->$cur)?$v->$cur:'&ndash;';
                $table .= '<td>'.$this->number_format_bmfn($tmp, 2, '.', ',',true).'</td>'; 
            }
            $table  .= '</tr>';
        }
        $table  .= '</tbody>';
        return $table;
    }
    
     public function getTableHead($type){
         return $this->tableHead[$type];
     }
    
    public function ReportTransaction($type){
        
        if (strlen($this->filter) < 2) {  $this->filter = 'null';}
        $page = $this->page > 0 ? $this->page - 1 : 0;
        $sort = strlen($this->sort) > 0 ? str_replace(' ', '', $this->sort) : 'null';
        $sort = $sort == 'Login' ? 'GrId' : $sort;

        
        $this->initDate();
        
        $tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Transactions/GetTransactionReport?guid=' . Yii::app()->user->id .'&from='.$this->startDate  . '&to=' . $this->endDate .'&type='.$type . '&filter=' . $this->filter . '&sort=' . $sort . '&desc=' . $this->desc  . '&countRowsTable=' . $this->countRowsTable . '&page=' . $page);
       
//                
 //      echo Yii::app()->params['json_server'] . '/API/Transactions/GetTransactionReport?guid=' . Yii::app()->user->id .'&from='.$this->startDate  . '&to=' . $this->endDate .'&type='.$type . '&filter=' . $this->filter . '&sort=' . $sort . '&desc=' . $this->desc  . '&countRowsTable=' . $this->countRowsTable . '&page=' . $page;
//        echo '<pre>';
//        print_r($this->tableHead[$type]);
//        print_r($tmp->reportList);
 //      exit();
        

        $table  = '';  

        if(isset($tmp->count) && count($tmp->count)>0 ){
            $this->listReport = $tmp->reportList;
            $this->countListReport = $tmp->count;

            $arr_row = array_keys($this->tableHead[$type]);

                    for($i=0; $i<count($this->listReport);$i++){
                         $table.= '<tr>';
                         foreach ($arr_row as $row) {
                             
                             if(isset($this->listReport[$i]->$row) && strlen($this->listReport[$i]->$row)>0){
                                if($row=="OpenTime"|| $row=="Date"){
                                 $this->listReport[$i]->$row=str_replace("T"," ",$this->listReport[$i]->$row);
                                        $this->listReport[$i]->$row=substr($this->listReport[$i]->$row,0,19);
                                } 
                                if($row=="Amount" || $row=="AmountToSend" || $row=="Ammount" || $row=="AmmountToSend" || $row=="Commission" || $row=="Comission"){
                                        $this->listReport[$i]->$row = $this->number_format_bmfn($this->listReport[$i]->$row, 2, '.', ',',true);
                                }elseif($row=="Spread"){
                                        $this->listReport[$i]->$row = $this->number_format_bmfn($this->listReport[$i]->$row, 4, '.', ',',true);
                                }          
                                $bg=($this->listReport[$i]->$row < 0)?('class="red_report_minus"'):false;
                                $table.='<td '.$bg.'>'.$this->listReport[$i]->$row.'</td>';
                             }else{
                                $table.='<td> - </td>';
                             }
                                
                         }
                         $table.= '</tr>';
                    }	
            }else{
                $table.= '<tr><td style="text-align: center; display:table-cell;" colspan="0"><br>'.Yii::t("main","107_no_reports").'<br>&nbsp;</td></tr>';
            }
        return $table;
        
        
    }
   
   
   
   
 		public function GetLinkCsv(){
			//$this->initDate_old();
			$this->initGroup();	
			$null = ($this->groupAllIn == 1 AND $this->groupIn == -1)?(1):(0); // когда 1 то вывод всех по всем 0 вывод свои клиентов
		
			//var_dump(Yii::app()->params['json_server'].'/API/Reports/ExportToExcel?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='.strtotime($this->startDate).'&to='.strtotime($this->endDate).'&type='.$this->accountType);
			$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/ExportToExcel?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='. strtotime($this->startDate).'&to='.strtotime($this->endDate).'&type='.$this->accountType);
			//var_dump(Yii::app()->params['json_server'].'/API/Reports/ExportToExcel?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&from='. strtotime($this->startDate).'&to='.strtotime($this->endDate).'&type='.$this->accountType, $tmp);die();
			//var_dump($tmp);die();
			return $tmp;
		}
		
		public function GetLinkCsvError(){


				$new_time_from=$this->startDate=$this->startDate-86400;
				$null = ($this->groupAllIn == 1 AND $this->groupIn == -1)?(1):(0); // когда 1 то вывод всех по всем 0 вывод свои клиентов
				//	return json_decode($this->listReport);

            /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
            if ($ip == '162.13.154.241') {
                var_dump(Yii::app()->params['json_server'].'/API/Reports/ExportToExcel?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$null.'&from='.$new_time_from.'&to='.$this->endDate.'&type='.$this->accountType);die();
            }*/

				return Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/ExportToExcel?guid='.Yii::app()->user->id.'&reportType='.$this->type.'&platform='.$this->platform.'&idsForReport='.$this->groupIn.'&needGroups='.$null.'&from='.$new_time_from.'&to='.$this->endDate.'&type='.$this->accountType);
		}
		
		public function ExportUsersToExcel(){
			//var_dump(Yii::app()->params['json_server'].'/API/CRM/ExportUserListToExcel?guid='.Yii::app()->user->id.'&filter='.$this->filter.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&state='.$this->state.'&requestState='.$this->RequestState.'&needLeads='.$this->needLeads.'&from='.$this->creationFrom.'&to='.$this->creationTo);
			$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/CRM/ExportUserListToExcel?guid='.Yii::app()->user->id.'&filter='.$this->filter.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&state='.$this->state.'&requestState='.$this->RequestState.'&needLeads='.$this->needLeads.'&from='.$this->creationFrom.'&to='.$this->creationTo);
			//var_dump($tmp);die();
			
			return $tmp;		
		}
			
/*--------------------------------------------------*/
   public function GetCount(){
       return $this->countListReport;
   }
   public function GetFilters(){
       return $this->countListReport;
   }
   public function GetRowsTable(){
       return $this->countRowsTable;
   }
   
   
	public function GetTotalReportByIBS(){
            echo Yii::app()->params['json_server'].'/API/Operations/GetTotalReportByIBS?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&idsForReport='.$this->group;
            $data = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Operations/GetTotalReportByIBS?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&idsForReport='.$this->group);
            print_r($data);exit();
            $table = '';
		foreach($data as $tr){
			$table .= '<tr>';
				foreach($tr as $key=>$td){
					if($key =='accountID' || $key =='date')continue;
					$table .= '<td>';
					$table .= $this->number_format_bmfn($td, 2, '.', ',',true);
					$table .= '</td>';
				}
			$table .= '</tr>';
		}
		//var_dump($data);die();
		return $table;
	}
	
	public function getUsersTrAccsTable($secHead = '', $yourAccs = array()){
		if(is_array($this->listReport) && count($this->listReport)>0){
			$table = '<table id="short_users_accs_list__">
						<thead>
							<tr>
								<th class="pc suLogin">'.Yii::t("main","20_Login").'</th>
								<th class="pc suName">'.Yii::t("main","123_name").'</th>
								<th class="pc suPlatform">'.Yii::t("main","124_platform").'</th>
								<th class="pc suCurrency">'.Yii::t("main","146_currency").'</th>
								<th class="pc suBalance">'.Yii::t("main","126_balance").'</th>
							</tr>
						</thead>
						<tbody>';
			
			$Account = new Account();
			$info = $Account->GetInfo();
			
			if(!in_array(0, $info->InternalTransferProhibitions)){
				$displayTR = 'style="display:none;"';
				$userZnak = 'plus__';
				$znak = '+';
			}else{
				$displayTR = '';
				$userZnak = 'minus__';
				$znak = '-';
			}
			
			
			if(!in_array(1, $info->InternalTransferProhibitions) || !in_array(2, $info->InternalTransferProhibitions)){
				if($secHead != '' && !empty($secHead)){
					$table .= '<tr class="accs_head_tr your_acc"><td colspan="5" ><div class="znak__ '.$userZnak.'">'.$znak.'</div>'.Yii::t("main","965_your_accs").'</td></tr>';
					foreach($secHead as $tr){
						if(isset($tr->PlatformType) && $tr->PlatformType == -1){
							$accTypeClass = 'isYourSystemAcc';
							if(in_array(2, $info->InternalTransferProhibitions)){
								continue;
							}
						}else{
							$accTypeClass = 'isYourTradingAcc';
							if(in_array(1, $info->InternalTransferProhibitions)){
								continue;
							}
						}
						$table .= '<tr class="your_acc_tr '.$accTypeClass.'" '.$displayTR.'">
						<td><input type="hidden" class="trAccLogin" value="'.$tr->AccountNum.'" />'.$tr->AccountNum.'</td>
						<td></td>
						<td>'.((isset($tr->Platform) && !empty($tr->Platform)) ? $tr->Platform : Yii::t("main","16_bmfn_account")).'</td>
						<td class="accCurrency">'.$tr->Currency.'</td>
						<td class="accBalance">'.$tr->Balance.'</td></tr>';
					}
				}
			}
			
			if(!in_array(0, $info->InternalTransferProhibitions)){
				$table .= '<tr class="accs_head_tr users_acc"><td colspan="5" style="border-top:1px solid white;"><div class="znak__ minus__">–</div>'.Yii::t("main","964_your_users_accs").'</td></tr>';
				foreach($this->listReport as $trAcc){
					//var_dump( $trAcc);die();
					if($trAcc->Login=='33331775'){
						continue;
					}
					if(!in_array($trAcc->Login, $yourAccs)){
						$table .= '<tr class="users_acc_tr">
							<td><input type="hidden" class="trAccLogin" value="'.$trAcc->Login.'" />'.$trAcc->Login.'</td>
							<td class="line2name">'.$trAcc->Name.'</td>
							<td>'.$trAcc->Platform.'</td>
							<td class="accCurrency">'.$trAcc->Currency.'</td>
							<td class="accBalance">'.$trAcc->Balance.'</td></tr>';
					}
				}
			}
			
			$table .= '</tbody>
				</table>
				<div class="tfoot hide-if-no-paging">
					<div id="page-preloader"><?php echo Yii::t("main","125_loading_data"); ?>...</div>
					<div id="pagination_dialog"></div>
				</div>
			';
				
				
			$pagination = $this->GetPagination();
			$pagination['current'] = ($pagination['current']) ? $pagination['current'] : 1;
			$table .= '<script>
			$(document).ready(function(){
				$(\'#pagination_dialog\').pagination({
					items: '.$pagination['count'].',
					itemsOnPage: '.$pagination['itemsOnPage'].',
					currentPage: '. $pagination['current'].',
					nextText: "'.Yii::t("main","231_next").'",
					prevText: "'.Yii::t("main","364_prev").'",
					onPageClick : function(){
						
						$currP = $(\'#pagination_dialog\').pagination(\'getCurrentPage\');

						$(\'#link_trAccs .userAccsDiv\').css(\'height\',$(\'#link_trAccs .userAccsDiv\').height()+\'px\').html(\'<div class="loadingData">'.Yii::t("main","125_loading_data").'...</div>\');
						$.ajax({
							type: "POST",
							url: window.location.pathname,
							data: {GetUserAccs:\'+\', filter:$(\'#filter\').val(), platform:$(\'#filtr_platform\').val(), page:$currP},
							success: function (data){ 
								$(\'#link_trAccs .userAccsDiv\').html(data);
								$(\'#link_trAccs .userAccsDiv\').css(\'height\',\'auto\');
							}
						});										
					}
				});
			});
			</script>';
		}else{
			$table = '<div class="emptyTableMessage">'.Yii::t("main","1004_ther_is_no_such_acc").'</div>';
		}
		
		return $table;
	}
	
	public function GetIBAccountsDetailedReportForClient(){
		$desc = ($this->desc == 0 ) ? 'false' : 'true';
		//var_dump(Yii::app()->params['json_server'].'/API/Reports/GetIBAccountsDetailedReportForClient?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$this->sort.'&desc='.$desc.'&pageSize='.$this->countRowsTable.'&page='.$this->page.'&types='.$this->types.'&accountId='.$this->accountId.'&ibID='.$this->ibID);die();
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/GetIBAccountsDetailedReportForClient?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$this->sort.'&desc='.$desc.'&pageSize='.$this->countRowsTable.'&page='.$this->page.'&types='.$this->types.'&accountId='.$this->accountId.'&ibID='.$this->ibID);	
		//GetIBAccountsDetailedReportForClient(string guid, long from, long to, string filter, string sort, bool desc, int pageSize, int page, string types, int? accountId, int ibID)
		//var_dump(Yii::app()->params['json_server'].'/API/Reports/GetIBAccountsDetailedReportForClient?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$this->sort.'&desc='.$desc.'&pageSize='.$this->countRowsTable.'&page='.$this->page.'&types='.$this->types.'&accountId='.$this->accountId.'&ibID='.$this->ibID, $tmp);die();
		//$this->listReport = $tmp->reportList;
		
		
		$this->listReport = $tmp->reportList;
		$this->listTotal = isset($tmp->total) ? $tmp->total : 0;
        $this->countListReport = $tmp->count;
		
		
		return $tmp;
	}
	
	public function GetIBAccountsDetailedReportTable(){
		if(!empty($this->listReport)){			
			$tableBody = '';		
		
			foreach($this->listReport as $row){
				$tableHead = '<tr>';
				$summary = '<tr style="background-color:background-color:rgba(255,0,0,.1);" title="'.Yii::t("main","112_summary").'">';
				$tableBody .= '<tr>';
				foreach($row as $key=>$elem){
					if($key == 'Date'){
						$tableBody .= '<td class="detail_'.$key.'">'.date('m/d/Y H:i:s', strtotime($elem)).'</td>';
						$summary .= '<td></td>';
					}elseif($key == 'GroupAccount' || $key == 'TradingAccount' || $key == 'TypeName' || $key == 'Ticket'){
						$tableBody .= '<td class="detail_'.$key.'">'.$elem.'</td>';
						$summary .= '<td></td>';
					}elseif($key == 'Amount' || $key == 'GroupBalance'){
						$tableBody .= '<td class="detail_'.$key.'">'.$this->number_format_bmfn($elem, 2, '.', ',',true).'</td>';
						$sum = (isset($this->listTotal->$key)) ? $this->number_format_bmfn($this->listTotal->$key, 2, '.', ',',true) : '';
						$summary .= '<td>'.$sum.'</td>';
					}else{
						continue;
					}
					$tableHead .= '<th>'.$this->getLabelsHead($key).'</th>';
				}				
				$summary .= '</tr>';
				$tableHead .= '</tr>';
				$tableBody .= '</tr>';
			}	
			
			return '<table class="table_clients__ sub_table"><thead>'.$tableHead.'</thead><tbody>'.$tableBody.$summary.'</tbody></table>';
		}
		
		return '<table class="table_clients__"><tbody><tr><td>'.Yii::t("main","441_no_results").'</td></tr></tbody></table>';
	}
	
	public function ExportIBAccountsDetailedReportToExcelForClient(){
		$desc = ($this->desc == 0 ) ? 'false' : 'true';
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/ExportIBAccountsDetailedReportToExcelForClient?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$this->sort.'&desc='.$desc.'&types='.$this->types.'&accountId='.$this->accountId.'&ibID='.$this->ibID);	
		
		return $tmp;
	}
	
	public function ExportBrokerPaymentReportToExcel(){
		//(string guid, long from, long to, string sort, bool desc, string filter, int? accountId, int ibID)
		$desc = ($this->desc == 0 ) ? 'false' : 'true';
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Reports/ExportBrokerPaymentReportToExcel?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$this->sort.'&desc='.$desc.'&accountId='.$this->accountId.'&ibID='.$this->ibID);	
		//var_dump(Yii::app()->params['json_server'].'/API/Reports/ExportBrokerPaymentReportToExcel?guid='.Yii::app()->user->id.'&from='.$this->startDate.'&to='.$this->endDate.'&filter='.$this->filter.'&sort='.$this->sort.'&desc='.$desc.'&accountId='.$this->accountId.'&ibID='.$this->ibID, $tmp);die();
		
		return $tmp;
	}
	
    
}
