<?php
class SvController 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('FormsAgreements','Competition','Employee','CompetitionRules','CompetitionResult','CompetitionResultDaily','CompetitionResultTotal','Index','SalesCompetition','LegalDocuments','Support','Conditions','SalesRate','AccountList','Trade','ClosedSum','ClosedSumTrade','DeposWithdrawal','FindByEmail','Summary','DwnlCsv', 'Leads', 'Crm', 'AddLeads', 'ClientRegistration', 'LetterExample', 'exportLeadsToExcel'),
				'roles'=>array('user2'),
			),
			 array('deny',  // deny all users
				'users'=>array('*'),
			), 
		);
	}

    public function init() {
        if(Yii::app()->params['styles_type'] == 'new'){
            $this->layout = 'sidebar';
        }
    }
	
	public function actionIndex(){ 
		$this->pageTitle=Yii::t("sp","49_sv_reports_short");		
		
        $this->breadcrumbs=array(Yii::t("sp","49_sv_reports_short"));
		
		
		
        $this->render('index');
    }
     public function actionFormsAgreements(){
            $this->pageTitle=Yii::t("sp","29_forms_and_agreements");

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

            $ViewFolder= wlParams::get('docsFolderServer').'/agreements';
            $json = file_get_contents($ViewFolder);
            $files = json_decode($json,true);
			
			$account = new Account();
			$info=$account->GetInfo();

            $this->render('formsAgreements', array('files'=>$files,'path'=>$ViewFolder, 'info'=>$info));
    }
	/*public function actionSalesCompetition(){ 
		$this->pageTitle=Yii::t("sp","51_sales_competition");		
		
        $this->breadcrumbs=array(Yii::t("sp","51_sales_competition"));
	
        $this->render('salesCompetition');
    }
	public function actionConditions(){
		$this->pageTitle=Yii::t("sp","32_conditions");
        
        $this->breadcrumbs=array(
        Yii::t("sp","26_sp_competition")=>array('/sv/competition/'),
        Yii::t("sp","36_monthly_sales_competition"));
		
                if (Yii::app()->request->isAjaxRequest){
                    $post = Yii::app()->request->getPost('Competition');
                    $Competition->GetAllSaleCompetitionRules();
                   // print_r( json_decode($post, true)); 
                    Yii::app()->end();
                }
                
		$Competition = new Competition();
		$rules = $Competition->GetAllSaleCompetitionRules();
               

                
		$this->render('conditions', array('rules' => $rules));
	}
	public function actionSalesRate(){
		$this->pageTitle=Yii::t("sp","30_sales_rate");
        
        $this->breadcrumbs=array(
        Yii::t("sp","26_sp_competition")=>array('/sv/competition/'),
        Yii::t("sp","30_sales_rate"));
		
		$Competition = new Competition();
		$sales = $Competition->getSalesDepositReport();
                print_r($sales);
		$count = 0;
		$table = '';
		foreach($sales as $sale){			
			$table .= '<tr><td>'.$count.'</td><td>'.$sale->Name.'</td><td>'.$sale->NetDeposit.'</td><td>'.$sale->TotalDeposit.'</td></tr>';			
			$count++; 
		}
		
		$this->render('salesRate', array('table'=>$table));
	}
	public function actionLegalDocuments(){ 
		$this->pageTitle=Yii::t("sp","53_legal_documents");		
		
        $this->breadcrumbs=array(Yii::t("sp","53_legal_documents"));
	
        $this->render('legalDocuments');
    }
	public function actionSupport(){ 
		$this->pageTitle=Yii::t("sp","3_support");		
		
        $this->breadcrumbs=array(Yii::t("sp","3_support"));
	
        $this->render('support');
    }*/
#----------------------------------------------------	
#-------------------------------------------------------------------------------	
#----------------------------------------------------	
    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?sv='.$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();
           }           
    	}
		$parentcode=5;
		$rez=$account->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
        $this->render('clientRegistration', array('code'=>$info->Code,'parentcode'=>$parentcode));
    }
         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?sv='.$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 actionEmployee(){
        $this->pageTitle=Yii::t("sp","52_employee_information");			
        $this->breadcrumbs=array(Yii::t("sp","52_employee_information"));
        
        
        $accaunt= new Account();
       
        $accaunt->countRowsTable = $this->countRows;
   
        
        
           if(Yii::app()->request->isAjaxRequest){ 

                $get = Yii::app()->request->getQuery('Account');
                $accaunt->attributes = (array)$get;
                $accaunt->countRowsTable = $get['itemsOnPage'];
                
                $table = $accaunt->GetDeparmentContacts(); 
                $pagination = $accaunt->GetPagination();

                exit(json_encode(array('table'=>$table,'count'=>$pagination['count'],'itemsOnPage'=>$pagination['itemsOnPage'])));
        }
        
        $table = $accaunt->GetDeparmentContacts(); //GetAccountTableIb();
        $pagination = $accaunt->GetPagination();
        $this->render('employeeInformation',array('table'=>$table,'pagination'=>$pagination,'accaunt'=>$accaunt,'mas_numb'=>$this->mas_numb));
    }
    public function actionCompetition(){
        $this->pageTitle=Yii::t("sp","26_sp_competition");
        $this->breadcrumbs=array(Yii::t("sp","26_sp_competition"));
        $account = new Account();
		$parentcode=5;
		$rez=$account->GetParentCode();
		$info=$account->GetInfo();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		$this->render('competition', array('parentcode'=>$parentcode, 'info'=>$info));
    }
    public function actionCompetitionRules(){
        $this->pageTitle=Yii::t("sp","36_monthly_sales_competition");
        $this->breadcrumbs=array(
            Yii::t("sp","26_sp_competition")=>array('/sv/competition.html'),
            Yii::t("sp","36_monthly_sales_competition"));
			
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107403'){die();}
		
		$Competition = new Competition();
		$rules = $Competition->GetAllSaleCompetitionRules();
		$this->render('SC_Rules', array('rules' => $rules));
    }
    public function actionCompetitionResult(){
        $this->pageTitle=Yii::t("sp","133_compet_resultr");
        $this->breadcrumbs=array(
            Yii::t("sp","26_sp_competition")=>array('/sv/competition.html'),
            Yii::t("sp","133_compet_resultr"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107403'){die();}
		
        $Document = new Document();
        $listRes = $Document->isExist('competitionArchive');
        $listDocs = array();
        $listExcel = array();
        $tmpArr = array();
        $month = array('January'=>'11','February'=>'12','March'=>'13','April'=>'14','May'=>'15','June'=>'16','July'=>'17','August'=>'18','September'=>'19','October'=>'21','November'=>'22','December'=>'23');
        foreach ($listRes as $path) { 
            
            $path = str_replace('\\', '/', $path);
            $arr = explode('/', $path);
            $name = end($arr); 
             
          
            if(strstr($path,'.csv')){
                $delim = strstr($path,'_')?'_':' ';
                $tmp = explode($delim, str_replace('.csv', '', $name));
                $m = isset($month[$tmp[0]])?$month[$tmp[0]]:0;
                $y = isset($tmp[1])?$tmp[1]:2000;
                $tmpArr[$y.$m] = array(str_replace('.csv', '', $name) =>  $name);
            }
            if(strstr($path,'.xlsx')){
                $listExcel[str_replace('.xlsx', '', $name)] = $path;
            }
        }
        krsort($tmpArr);
        foreach ($tmpArr as $val){
            $listDocs[ key($val)] = current($val);
        }        
        $array = array_keys($listDocs);
        $searchFileKey = isset($_POST['file']) ? $_POST['file'] : current($array);

        $Competition = new Competition();
		$showTopTable = true;
		//if($_SERVER['REMOTE_ADDR'] == '77.222.143.18'){
		if(strtotime($searchFileKey) > strtotime('January 2017')){
			$showTopTable = false;
		}
		//}
        $result = $Competition->ParseCSV($listDocs[$searchFileKey]);
       

        $this->render('SC_Result', array('listDocs' => $listDocs,'result'=>$result,'selFile'=>$searchFileKey,'listExcel'=>$listExcel, 'showTopTable'=>$showTopTable));
    }
    public function actionCompetitionResultDaily(){
        $this->pageTitle=Yii::t("sp","134_daily_results");
        $this->breadcrumbs=array(
            Yii::t("sp","26_sp_competition")=>array('/sv/competition.html'),
            Yii::t("sp","134_daily_results"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107403'){die();}
		 
        $Competition = new Competition();
        $account = new Account();
        $office=$account->GetParentCode();
    
        $result = $Competition->GetSalesCompetitionResult('-1');
        $this->render('SC_ResultDaily', array('result' => $result,'selOffice'=>isset($_POST['selOffice'])?$_POST['selOffice']:'Total'));
    }
    public function actionCompetitionResultTotal(){
        $this->pageTitle=Yii::t("sp","135_total_results");
        $this->breadcrumbs=array(
            Yii::t("sp","26_sp_competition")=>array('/sv/competition.html'),
            Yii::t("sp","135_total_results"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107403'){die();}
		
        $Competition = new Competition();
        $resultTotal = $Competition->GetSalesCompetitionResultTotal();
		//var_dump($resultTotal);die();
		$resultTotal = $Competition->getSalesCompetitionRatesTable($resultTotal, $params = array('totalDeposit'=>true, 'netDeposit'=>true, 'dailyResult'=>false, 'groupID'=>false), $rgba = true);

        $this->render('SC_ResultTotal', array('result' => $resultTotal));
    }
    
#----------------------------------------------------	
#-------------------------------------------------------------------------------	
#----------------------------------------------------	
	public function actionAccountList(){

        $this->pageTitle=Yii::t("main","91_account_list_report");
        
		//	var_dump(Yii::app()->user->checkAccess('actionAccountList'));die();
		
		
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("main","91_account_list_report"));
          
					
							$link_error=null;
								
				$accaunt= new Account();
				if( isset($_GET['client'])){
					$repor= new Report(3);
					$_REQUEST['group'] = '_'.$_GET['client'];
					$_REQUEST['groupAllIn'] = 1;
					$repor->attributes=$_REQUEST; 
					$itemsOnPage=$repor->GetRowsTable(); ###
					$table = $repor->GetDataTable();
					$pagination = $repor->GetPagination();
					$count = $repor->GetCount();
					$link_error= (wlParams::get('officeCode') !== 80) ? $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->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->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']) && (!isset($_REQUEST['isIbCode']) || (isset($_REQUEST['isIbCode']) && $_REQUEST['isIbCode'] == 0)))){
						$table = $accaunt->GetAccountTableTrader();
					}else{
						$table = $accaunt->GetAccountTableIb();
					}
					$pagination = $accaunt->GetPagination();
					$count = $accaunt->GetCount();
				}
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
								
		$backLink = $accaunt->getBackLink();
		
		$view = new Platform();
								
		$prevPage = '';
		if(isset($_REQUEST['prevPage']) && !empty($_REQUEST['prevPage'])){
			$prevPage = $_REQUEST['prevPage'];
		}
		
		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$this->render('/reports/fullReport',array('table'=>$table, 'thead'=>$repor->thead));
		}else{						
			$this->render('accountList',array('table'=>$table,'pagination'=>$pagination,'paltforms'=>$view->GetList(),'link_error'=>$link_error,'mas_numb'=>$this->mas_numb, 'info'=>$accaunt->getInfo(), 'prevPage'=>$prevPage, 'backLink'=>$backLink));
		}
       
    }
	public function actionTrade(){
				
        $this->pageTitle=Yii::t("main","93_trade_report");
  
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("main","93_trade_report"));	
        $link_error=null;
		$accaunt= new Account();
								
			if(Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report') || Yii::app()->request->getPost('groupAllIn') == 1 ){
				$repor= new Report(1);
				$repor->attributes=$_REQUEST; 
				$itemsOnPage=$repor->GetRowsTable(); ### 
				//var_dump($repor->attributes, $_REQUEST);
				$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;
				if($accaunt->isForm() == 'accountTrader' || Yii::app()->request->getPost('formIs') == 'accountTrader' || (isset($_REQUEST['accountFilter']) && !empty($_REQUEST['accountFilter']) && (!isset($_REQUEST['isIbCode']) || (isset($_REQUEST['isIbCode']) && $_REQUEST['isIbCode'] == 0)))){
					$table = $accaunt->GetAccountTableTrader();
				}else{
					$table = $accaunt->GetAccountTableIb();
				}
				$pagination = $accaunt->GetPagination();
				$count = $accaunt->GetCount();
			}
					
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
		
		$backLink = $accaunt->getBackLink();
							
		$view = new Platform();
		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$this->render('/reports/fullReport',array('table'=>$table, 'thead'=>$repor->thead));
		}else{						
			$this->render('trade',array('table'=>$table,'pagination'=>$pagination,'paltforms'=>$view->GetList(),'link_error'=>$link_error,'mas_numb'=>$this->mas_numb, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink));
		}
    }
	public function actionClosedSum(){

		$this->pageTitle=Yii::t("main","95_closed_trades_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("main","95_closed_trades_report"));
		$link_error=null;
		$accaunt= new Account();

				
		if(Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report') || Yii::app()->request->getPost('groupAllIn') == 1 ){
			$repor= new Report(2);
			$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;
			if($accaunt->isForm() == 'accountTrader' || Yii::app()->request->getPost('formIs') == 'accountTrader' ||  (isset($_REQUEST['accountFilter']) && !empty($_REQUEST['accountFilter']) && (!isset($_REQUEST['isIbCode']) || (isset($_REQUEST['isIbCode']) && $_REQUEST['isIbCode'] == 0)))){
					$table = $accaunt->GetAccountTableTrader();
			}else{
					$table = $accaunt->GetAccountTableIb();
			}
			$pagination = $accaunt->GetPagination();
			$count = $accaunt->GetCount();
        }
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
								
		$backLink = $accaunt->getBackLink();
		
		$view = new Platform();
								
		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$this->render('/reports/fullReport',array('table'=>$table, 'thead'=>$repor->thead));
		}else{
            $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, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now));
		}
    }
	public function actionClosedSumTrade(){
	
		$this->pageTitle=Yii::t("main","97_close_trade_summary_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("main","97_close_trade_summary_report"));
        $link_error=null;
		$accaunt= new Account();
        if(Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report') || Yii::app()->request->getPost('groupAllIn') == 1 ){
                $repor= new Report(7);
                $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;
                if($accaunt->isForm() == 'accountTrader' || Yii::app()->request->getPost('formIs') == 'accountTrader' ||  (isset($_REQUEST['accountFilter']) && !empty($_REQUEST['accountFilter']) && (!isset($_REQUEST['isIbCode']) || (isset($_REQUEST['isIbCode']) && $_REQUEST['isIbCode'] == 0)))){
                    $table = $accaunt->GetAccountTableTrader();
                }else{
                    $table = $accaunt->GetAccountTableIb();
                }
                $pagination = $accaunt->GetPagination();
                $count = $accaunt->GetCount();
        }
		if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
	
		$backLink = $accaunt->getBackLink();
	
	    $view = new Platform();

		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$this->render('/reports/fullReport',array('table'=>$table, 'thead'=>$repor->thead));
		}else{

            $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, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now));
		}
	
    }
	public function actionDeposWithdrawal(){
				
				
		$this->pageTitle=Yii::t("main","99_depositwithdrawal_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        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('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report') || Yii::app()->request->getPost('groupAllIn') == 1 ){
						$repor= new Report(4);

						$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= new Account();
						$accaunt->attributes=$_REQUEST;
						$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']) && (!isset($_REQUEST['isIbCode']) || (isset($_REQUEST['isIbCode']) && $_REQUEST['isIbCode'] == 0)))){
								$table = $accaunt->GetAccountTableTrader();
						}else{
								$table = $accaunt->GetAccountTableIb();
						}
						$pagination = $accaunt->GetPagination();
						$count = $accaunt->GetCount();
        }
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
		
		$backLink = $accaunt->getBackLink();
		
		$view = new Platform();
		
		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$this->render('/reports/fullReport',array('table'=>$table, 'thead'=>$repor->thead));
		}else{

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

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

    }
	public function actionFindByEmail(){
        
        $this->pageTitle=Yii::t("sp","11_find_account_by_email");
        
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("sp","11_find_account_by_email"));
        $table = $pagination = null;
        
        if(Yii::app()->request->isPostRequest){
            $repor = new Report(6);
            $repor->attributes=$_REQUEST;
						$itemsOnPage=$repor->GetRowsTable(); ###
            $table = $repor->GetByEmailTable();
            $pagination = $repor->GetPagination();
            $count = $repor->GetCount();
            if(Yii::app()->request->isAjaxRequest){ 
				if($count==0){
					$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
				}
				exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
			}
        }
								
								$view = new Platform();
        $this->render('findByEmail',array('table'=>$table,'pagination'=>$pagination,'paltforms'=>$view->GetList(),'mas_numb'=>$this->mas_numb));
    }
	public function actionSummary(){
				
				
    	$this->pageTitle=Yii::t("main","101_summary_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("main","101_summary_report"));
						
        $link_error=null;
		$accaunt= new Account();
        if(Yii::app()->request->getPost('formIs') == 'report' || (isset($_GET['formIs']) && $_GET['formIs'] == 'report') || Yii::app()->request->getPost('groupAllIn') == 1 ){
						$repor= new Report(5);
						$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;
						if($accaunt->isForm() == 'accountTrader' || Yii::app()->request->getPost('formIs') == 'accountTrader' ||  (isset($_REQUEST['accountFilter']) && !empty($_REQUEST['accountFilter']) && (!isset($_REQUEST['isIbCode']) || (isset($_REQUEST['isIbCode']) && $_REQUEST['isIbCode'] == 0)))){
								$table = $accaunt->GetAccountTableTrader();
						}else{
								$table = $accaunt->GetAccountTableIb();
						}
						$pagination = $accaunt->GetPagination();
						$count = $accaunt->GetCount();
        }
		if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td></td><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="5">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
	
		$backLink = $accaunt->getBackLink();
	
		$view = new Platform();
	
		if(isset($_POST['allReport']) && $_POST['allReport'] == 'on'){
			$this->render('/reports/fullReport',array('table'=>$table, 'thead'=>$repor->thead));
		}else{
            $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, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now));
		}
       
    }
	
	public function actionDwnlCsv(){
		if(isset($_GET['isLeadlist'])){
			
		}
		$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 actionExportLeadsToExcel(){
		$Lead = new Lead();
		$Lead->needWithUsers = $_GET['needWithUsers'];
		$link = $Lead->ExportLeadsToExcel();
		
		if($link != "ReportIsEmpty"){
			Yii::app()->getController()->redirect($link);
		}else{
            exit('ReportIsEmpty');		
		}
	}
	
	public function actionLeads(){

		
		if(isset($_GET['no_regist'])){
			$this->breadcrumbs=array(
			Yii::t("sp","117_crm")=>array('/sv/crm.html'),
			Yii::t("sp","125_no_reg_leads"));
			$this->pageTitle=Yii::t("sp","125_no_reg_leads");    
		}else{
			$this->breadcrumbs=array(
			Yii::t("sp","117_crm")=>array('/sv/crm.html'),
			Yii::t("sp","126_leads"));
			$this->pageTitle=Yii::t("sp","126_leads");    
		}
		
				
				
				
		$Filter = new Lead('filter');	

		if(Yii::app()->request->isAjaxRequest){
			//var_dump($_REQUEST);die();
			if(isset($_POST['assignLead2User'])){
				$Lead = new Lead();
				$result = $Lead->ApplyLeadToUser($_POST['userId'], $_POST['id']);
				if($result->State == 0){
					echo 'ok';
				}else{
					echo 'no';
				}
				
				Yii::app()->end();
			}
			
			if(isset($_POST['viewAllComments'])){
				$Lead = new Lead();
				$comments = $Lead->GetLeadComments($_POST['id']);
				$comView = $Lead->GetCommentsHistoryView($comments);
				echo $comView;
				Yii::app()->end();
			}
		
			if(isset($_POST['GetUserForCRMData'])){  
				$Lead = new Lead();
				$userLikeList = (isset($_POST['id']) && !empty($_POST['id'])) ? $Lead->GetUserForCRMData($_POST['id']) : '';
				$table = '';
				if(!empty($userLikeList)){
					$table .= '<input id="isLikeList" type="hidden" value="1" />';				// must be the first tag
					$table .= $Lead->getShortUserListTable($userLikeList);
				}else{
					$repor= new Report(11);
					$repor->SetCountRowsTable(15);
					$repor->attributes=$_REQUEST; 
					$repor->needLeads = 'false';
					$itemsOnPage=$repor->GetRowsTable(); ###
					if(isset($_POST['search'])){
						$repor->filter = ($_POST['search'] == '') ? 'null' : $_POST['search'];
					}
					if(isset($_POST['current'])){
						$repor->page = $_POST['current'];
					}
					$repor->SendRequest();
					$userList = $repor->GetListReport();
					$table .= '<input id="isLikeList" type="hidden" value="0" />'; 				// must be the first tag
					if(!empty($userList)){
						$table .= $Lead->getShortUserListTable($userList);
						$pagination = $repor->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\');
									//$(\'#Lead_current\').val($currP);
									console.log($currP);
								  
									$(\'#link_dialog .contentDiv\').html(\'<div style="text-align:center;">'.Yii::t("main","125_loading_data").'...</div>\');
									$.ajax({
										type: "POST",
										url: window.location.pathname,
										data: {GetUserForCRMData:\'+\', search:$(\'#filter\').val(), current:$currP},
										success: function (data){ 
											$(\'#link_dialog .contentDiv\').html(data);
										}
									});										
								}
							});
						});
						</script>';
					}else{
						$table .= '<div style="text-align:center;">'.Yii::t("sp","169_there_is_no_user_2_link").'</div>';
					}
				}
				echo $table;
				Yii::app()->end();
			}
			
			
			if(isset($_POST['removeLead']) && isset($_POST['id']) && !empty($_POST['id'])){ 
				$Lead = new Lead('svUpdate');
				$rez = $Lead->RemoveLeadData($_POST['id']);
				if($rez->State == '0'){
					echo 'ok';
				}else{
					echo 'bad';
				}
				Yii::app()->end();
			}   
			
			if(isset($_POST['lead_save'])){                           
				$Lead = new Lead('svUpdate');
				$Lead->attributes = $post = Yii::app()->request->getPost('Lead');
				if($Lead->validate(array_keys($post))){
					//$Lead->Remind = !empty($Lead->Remind) ? strtotime($Lead->Remind) : -1;
					$rez = $Lead->update();
					if($rez->State == 0){
						$respons = array('state'=>'ok','id'=>$Lead->Id,'date'=>date("m/d/Y"));
					}else{
						$respons = array('state'=>'no','id'=>$Lead->Id, 'error'=>Yii::t("sp","164_lead_update_failed"));
					}
					exit(json_encode($respons));
				}
				$respons = array('state'=>'no','error'=>$Lead->getErrors(),'id'=>$Lead->Id);
				exit(json_encode($respons));
			}
			
			if(isset($_POST['clearFilters'])){  
				$table = $Filter->getLeadsTable();
				$pagination = $Filter->GetPagination();
											
				exit(json_encode(array('table'=>$table,'count'=>$pagination['count'],'itemsOnPage'=>$pagination['itemsOnPage'])));
			}
			
			
			$get = $_REQUEST;

			foreach($Filter->attributes as $key=>$value){
				if(isset($get[$key])){
					if($key == 'Remind' || $key == 'commentDate' || $key == 'creationDate'){
						if(empty($get[$key])){
							$Filter->$key = -1;
						}else{
							$Filter->$key = strtotime($get[$key]);
						}
					}else{
						$Filter->$key=$get[$key];
					}
				}
			}
			//var_dump($Filter->attributes);die();
			if(isset($get['filterKey']) && !empty($get['filterKey'])){		// save fliter value in table in right place
				$fkey = str_replace('Lead_','',$get['filterKey']);
				$Filter->$fkey = $Filter->filter;					
			}
            $table = $Filter->getLeadsTable();
			$pagination = $Filter->GetPagination();
                        
			
			exit(json_encode(array('table'=>$table,'count'=>$pagination['count'],'itemsOnPage'=>$pagination['itemsOnPage'])));
			//exit(json_encode(array('table'=>$table)));
		}
		
		$Lead = new Lead('sv');
		$table = $Lead->getLeadsTable();
		$pagination = $Lead->GetPagination();

		$account = new Account();
		$info = $account->GetInfo();
		
		/*$this->render('leads', array('Lead' => $Lead, 'Filter' => $Filter, 'table' => $table, 'pagination' => $pagination));*/
		$this->render('leads', array('Lead' => $Lead, 'Filter' => $Filter, 'table' => $table, 'pagination' => $pagination, 'info'=>$info, 'leadsCount'=>$Lead->countLeadsList));
	}	

	public function actionCrm(){
		$this->pageTitle=Yii::t("sp","117_crm");    
        $this->breadcrumbs=array(Yii::t("sp","117_crm"));
		
		$this->render('crm', array());
	}
	
	public function actionAddLeads(){
		$this->pageTitle=Yii::t("sp","127_add_lead");    
		$this->breadcrumbs=array(
			Yii::t("sp","117_crm")=>array('/sv/crm.html'),
			Yii::t("sp","127_add_lead"));
	
		$Registration = new Registration('registration');
		$countries = $Registration->GetCountry();
		$Account = new Account();
		$info = $Account->getInfo();
		unset($countries['']);

		$Lead = new Lead('sv');
		$Parent = $Lead->getSpList();
		$priorityList = $Lead->getStaticArray('Priority');
		$stateList = $Lead->getStaticArray('State');
		$stateInSysList = $Lead->getStaticArray('StateInSystem');
		$langList = $Lead->getStaticArray('Language');
		$sourceList = $Lead->getStaticArray('Source');
                
                $Document = new Document('Leads');
                
		if (Yii::app()->request->isAjaxRequest){
            $post = Yii::app()->request->getPost('Lead');
			if(isset($_POST['add'])){
				$Lead->attributes = Yii::app()->request->getPost('Lead');
				echo CActiveForm::validate($Lead);
				Yii::app()->end();
			}elseif(isset($_POST['upload'])){
				$Document->attributes = $postDocs = Yii::app()->request->getPost('Document');
				$docErrors = $Document->ajaxDocValidate($postDocs, $Document);  
				if(!empty($docErrors)){ echo $docErrors;  Yii::app()->end();} 
			}
			Yii::app()->end();
		}
		if(Yii::app()->request->isPostRequest){
			$Lead->attributes = Yii::app()->request->getPost('Lead');
			if(isset($_POST["add"])){
					$Lead->Source = 1;
					//$Lead->CommentDate = ($Lead->Comment == '') ? '' : date("m/d/Y");
				if($Lead->validate()){
					$Lead->Remind = ($Lead->Remind == '') ? 0 : strtotime($Lead->Remind);
					$rez = $Lead->add();
					if(is_numeric($rez)){
						$_SESSION['message'][] = array("text" => Yii::t("sp", "172_lead_was_added"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
					}elseif(is_string($rez) && $rez == 'UserAlreadyExists'){
						$_SESSION['message'][] = array("text" => Yii::t("main", "39_this_email_has_already_registered"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
                    }else{
						$_SESSION['message'][] = array("text" => Yii::t("funds", "509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
					}
					$Lead = new Lead('sv');
				}
			}elseif(isset($_POST["upload"])){
					$Document->attributes = $post = Yii::app()->request->getPost('Document');
					if($post && is_array($post)){
							$Document->postDocSave($post);
							$this->redirect(array('/sv/leads.html'));
					}else{
							$_SESSION['message'][] = array("text" => Yii::t("funds", "509_somthing_went_wrong"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
							$Document->addError('leads', Yii::t("sp","139_add_success"));
							$respons = array('State'=>'','operation'=>'upload','error'=>$Lead->getErrors());
							exit(json_encode($respons));
					}
			}
		}
		$this->render('addLeads', array('Lead' => $Lead, 'countries' => $countries, 'Parent' => $Parent, 'priorityList' => $priorityList, 'stateList' => $stateList, 'stateInSysList' => $stateInSysList, 'langList' => $langList, 'sourceList' => $sourceList, 'Document' => $Document, 'info'=>$info));
	}
}
