<?php
class SpController 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( 'Leads', 'Crm', 'AddLeads','Competition','CompetitionRules','CompetitionResult','CompetitionResultDaily','CompetitionResultTotal','AccountList','Index','Trade','History','ClosedSum','DeposWithdrawal','Segregated','ClosedSumTrade','Summary','FindByEmail','DwnlCsv','Competition','Conditions','SalesResults','SalesRate','FormsAgreements','Support', 'MySite', 'ClientRegistration', 'LetterExample', 'exportLeadsToExcel', 'promoCenter', 'promoBanner', 'promoVideo'),
				'roles'=>array('user3'),
			),
			 array('deny',  // deny all users
				'users'=>array('*'),
			), 
		);
	}     
	
    public function actionIndex(){ 
		$this->pageTitle=Yii::t("sp","25_sp_reports");		
		
        $this->breadcrumbs=array(Yii::t("sp","25_sp_reports"));
	
        $Account = new Account();		
		$parentcode=5;
		$rez=$Account->GetParentCode();
		$info=$Account->getInfo();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
        $this->render('index', array('parentcode' => $parentcode, 'info' => $info));
    }

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




    //AccountList|Trade|History|ClosedSum|DeposWithdrawal|Segregated|Summary|Report
//    public function actionCrm(){
//	$this->pageTitle=Yii::t("sp","117_crm");    
//        $this->breadcrumbs=array(Yii::t("sp","117_crm"));
//		
//            $Filter = new Lead('filter');
//            
//		if(Yii::app()->request->isAjaxRequest){ 
//			if(isset($_POST['lead_save'])){
//                            $Lead = new Lead('sv');
//                            $Lead->attributes = Yii::app()->request->getPost('Lead');
//                            if($Lead->validate()){
//                                $Lead->update();
//                                $respons = array('state'=>'ok','id'=>$Lead->id);
//                                exit(json_encode($respons));
//                            }
//                            $respons = array('state'=>'no','error'=>$Lead->getErrors());
//                            exit(json_encode($respons));
//			}
//			$get = Yii::app()->request->getQuery('Lead');
//                       
//			$Filter->attributes = (array)$get;
//
//                        $table = $Filter->getLeadsTable();
//			$pagination = $Filter->GetPagination();
//                        
//                         
//			exit(json_encode(array('table'=>$table,'count'=>$pagination['count'],'itemsOnPage'=>$pagination['itemsOnPage'])));
//		}
//		
//		$Lead = new Lead('sv');
//		$table = $Lead->getLeadsTable();
//		$pagination = $Lead->GetPagination();
//		
//		$this->render('leads', array('Lead' => $Lead, 'Filter' => $Filter, 'table' => $table, 'pagination' => $pagination));
//                
//	}
	   
	public function actionLeads(){

		
		if(isset($_GET['no_regist'])){
			$this->breadcrumbs=array(
			Yii::t("sp","117_crm")=>array('/sp/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('/sp/crm.html'),
			Yii::t("sp","126_leads"));
			$this->pageTitle=Yii::t("sp","126_leads");    
		}
		
				
				
				
		$Filter = new Lead('filter');	

		if(Yii::app()->request->isAjaxRequest){
			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: {GetUserAccs:\'+\', 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('/sp/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");
					}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('/sp/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));
	}
        
        
        
        
        
        
        
        
 public function actionMySite(){
		$this->pageTitle = Yii::t("main", "461_ib_website");
        $this->breadcrumbs = array(Yii::t("main", "461_ib_website"));
		
		$account = new Account();
        $info = $account->GetInfo();
		$Registration = new Registration('Individual');
		$params['status'] = $status = $Registration->IsApprove();
		$params['isView'] = true;

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

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

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

			if(Yii::app()->request->isAjaxRequest){
				$Site->attributes = $post = Yii::app()->request->getPost('MyWebsite');
                                $Site->attributes = $post = Yii::app()->request->getPost('MyWebsite');
                                $Site->platforms = $post['platforms'] = isset($post['platforms'])?$post['platforms'] : '';
                                $Site->langs = $post['langs'] = isset($post['langs'])?$post['langs'] : '';
                                
				//$post = $Site->attributes;
				for($i = 1 ; $i<6 ; $i++){
					$name = 'social_link'.$i;
					if($Site->$name=='http://'){
						$Site->$name = '';
						unset($post[$name]);
					}
				}
			//	var_dump($post, $Site->attributes);die();
				$valdt_attrs = array_keys($post);
				if($_POST["domen_choose"]=='1'){
					if(in_array('domen',$valdt_attrs)){
						unset($valdt_attrs[array_search('domen', $valdt_attrs)]);
					}
				}else{
					if(empty($post['domen'])){
						$Site->domen='error';
					}
				}
				
				$siteValidate = CActiveForm::validate($Site, $valdt_attrs);	
				if($siteValidate != '[]'){
					echo $siteValidate;
					Yii::app()->end();
				}	
				Yii::app()->end();	
			}
			
			if(Yii::app()->request->isPostRequest){
			//	http://ib.bmfn.com/createSite?code=76&fname=alexx&lname=koxx&phone=0936764523&email=ibtest@mail.ru&domen=koxx&deflang=en&langs=en,ru,cn&idDesign=1
				$Site->attributes = $post = Yii::app()->request->getPost('MyWebsite');
                                $Site->platforms = $post['platforms'] = isset($post['platforms'])?$post['platforms'] : '';
                                $Site->langs = $post['langs'] = isset($post['langs'])?$post['langs'] : '';

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

				if ($docValidation){
                                    
                                $post['code'] = $info->Code;
				$post['langs'] = implode(",",$post['langs']);
				$post['platforms'] = implode(",",$post['platforms']);
                          
				if($_POST["domen_choose"]==2){
					$post['subDomen'] = 'ib'.$info->Code;
					if(!empty($post['domen'])){
						$post['domen'] = str_replace('http://','',$post['domen']);
						if($post['domen'][strlen($post['domen'])-1]=='/'){
							$post['domen'] = substr($post['domen'], 0, -1);
						} 
					}else{
					//	$Site->domen='';
					}
				}else{
					//$post['subDomen'] = 'ib'.$info->Code;
					//$post['domen'] = '';
				}
                                    
                                    
                                    
					$uploader = CUploadedFile::getInstance($Site, 'logo');
					if ($uploader) {
						$sourcePath = pathinfo($uploader->getName());
						$fileName = 'sitelogo_ib'.$info->Code.'.'.$sourcePath['extension'];
						$Site['logo'] = $uploader;
						$Site['logo']->saveAs($_SERVER["DOCUMENT_ROOT"] . '/assets/img/site_logos/'.$fileName);
						
						$image_size = getimagesize($_SERVER["DOCUMENT_ROOT"] . '/assets/img/site_logos/'.$fileName);
						if($image_size[1]>101){
							$width = (101*(int)$image_size[0])/$image_size[1];
							$image = Yii::app()->image->load($_SERVER["DOCUMENT_ROOT"] . '/assets/img/site_logos/'.$fileName);
							$image->resize($width, 101);
							$image->save(); 					
						}
						
						$post['logo_url'] = 'http://'.$_SERVER["SERVER_NAME"].'/assets/img/site_logos/'.$fileName;
						$post['logo_name'] = $fileName;
					}
					$post['server'] = Yii::app()->params['server'];
                                        
                                        $post['userType'] = $info->Type;
                                        
					$ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/updateSite', $post,80);
					//var_dump($ib_site_info);die();

					if($ib_site_info=="success"){
						$_SESSION['message'][] = array("text" => Yii::t("main", "498_you_alrdy_crt_site"), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "success");
					}						
					$Site = new MyWebsite();
				} 
			}	
			
			$params['has_site'] = $Site->has_site;
			$params['Site'] = $Site;		
			$params['design'] = $Site->allow_designs;
			$params['langs'] = $Site->allow_langs;
			$params['platforms'] = $Site->allow_platforms;
			$params['socials'] = $Site->allow_socials;
			$params['site_lang'] = $site_lang; 

//          COMMENTED BY ARSEN, 09/30/2024
//			if($Site->has_site==1){     //COMMENTED BY ARSEN, 09/30/2024
//				if($Site->domen!='' && isset($Site->domen)){
//					$rez = @file_get_contents($Site->domen.'/domenReady');
//					if($rez=='good'){
//                                                $params['urlToWebSite'] = $Site->domen;
//						$params['action'] = $Site->domen.'/admin/login';
//					}else{
//                                                $params['urlToWebSite'] = 'http://'.$Site->subDomen.'.ib.bmfn.com';
//						$params['action'] = 'http://'.$Site->subDomen.'.ib.bmfn.com/admin/login';					
//					}
//				}else{
//        COMMENTED BY ARSEN, 09/30/2024
//                                        $params['urlToWebSite'] = 'http://'.$Site->subDomen.'.sp.bmfn.com';
//
//					$params['action'] = 'https://'.$Site->subDomen.'.sp.bmfn.com/admin/login';
//                                        if(isset($Site->domen) && !empty($Site->domen) && ($Site->domen != 'http://')){
//                                               $rez = @file_get_contents($Site->domen.'/domenReady');
//                                                if($rez=='good'){
//                                                        $params['action'] = $Site->domen.'/admin/login';
//                                                }
//                                        }
                        
                        
				//}
				
				
//				$params['code'] = $info->Code;
//				$params['subDomen'] = $Site->subDomen;
//				//$params['domen'] = $Site->domen;
//				$params['login'] = $Site->login;
//				$params['password'] = $Site->password;
//
//			}
			$parentcode=5;
			$rez=$account->GetParentCode();
			if(isset($rez)&& $rez>0){$parentcode=$rez;}
			$params['parentcode'] = $parentcode;
		
		$this->render('mySite', $params);
	}
/*
OpenTrades=1;
CloseTrades = 2;
AccountList = 3;
DWA = 4;
*/
    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","4_sp_report")=>array('/sp/'),
        Yii::t("main","91_account_list_report"));
          
					
				$link_error=null;
				$accaunt= new Account();				
				if( isset($_GET['client'])){
					$repor= new Report(3);
					$repor->SetCountRowsTable(50);
					$_REQUEST['group'] = '_'.$_GET['client'];
					$_REQUEST['groupAllIn'] = 1;
					$repor->attributes=$_REQUEST; 
					$itemsOnPage=$repor->GetRowsTable(); ###
					$table = $repor->GetDataTable();
					$pagination = $repor->GetPagination();
					$count = $repor->GetCount();
					$link_error=(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->SetCountRowsTable(50);
					$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;
					//var_dump($accaunt->isForm());die();
					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 style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
								
		$view = new Platform();
		
		$backLink = $accaunt->getBackLink();

		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(), 'backLink'=>$backLink));
		}
       
    }
#----------------------------------------------------	
#-------------------------------------------------------------------------------	
#----------------------------------------------------	
    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($info->Login == '1000107408' || $info->Login == '1000107406' || $info->Code == 596 || $info->Code == 600 || $info->Code == 601 || $info->Code == 617 || $info->Code == 624){die();}

		
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
        $this->render('competition', array('parentcode'=>$parentcode));
    }
    public function actionCompetitionRules(){
		die();
        $this->pageTitle=Yii::t("sp","36_monthly_sales_competition");
        $this->breadcrumbs=array(
            Yii::t("sp","26_sp_competition")=>array('/sp/competition.html'),
            Yii::t("sp","36_monthly_sales_competition"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107408' || $info->Login == '1000107406' || $info->Code == 596 || $info->Code == 600|| $info->Code == 601 || $info->Code == 617 || $info->Code == 624){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('/sp/competition.html'),
            Yii::t("sp","133_compet_resultr"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107408' || $info->Login == '1000107406' || $info->Code == 596 || $info->Code == 600 || $info->Code == 601 || $info->Code == 617 || $info->Code == 624){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('/sp/competition.html'),
            Yii::t("sp","134_daily_results"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107408' || $info->Login == '1000107406' || $info->Code == 596 || $info->Code == 600 || $info->Code == 601 || $info->Code == 617 || $info->Code == 624){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('/sp/competition.html'),
            Yii::t("sp","135_total_results"));
        
		$account = new Account();
		$info=$account->GetInfo();
		if($info->Login == '1000107408' || $info->Login == '1000107406' || $info->Code == 596 || $info->Code == 600 || $info->Code == 601 || $info->Code == 617 || $info->Code == 624){die();}
		
        $Competition = new Competition();
        $resultTotal = $Competition->GetSalesCompetitionResultTotal();
        $table = $Competition->getSalesCompetitionRatesTable($resultTotal,array('totalDeposit'=>true, 'netDeposit'=>true, 'dailyResult'=>true, 'groupID'=>false));	 
//print_r($table);
//exit();
        $this->render('SC_ResultTotal', array('result' => $table));
    }
    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();
		
		$info=$account->GetInfo();
		//if($info->Login == '1000107408' || $info->Login == '1000107406'){die();}
		
		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?sp='.$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();
		$shortCode=$account->GetUserOfficeShortCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
        $this->render('clientRegistration', array('code'=>$info->Code,'parentcode'=>$parentcode,'shortCode'=>$shortCode));
    }
     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?sp='.$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 actionTrade(){
				
        $this->pageTitle=Yii::t("main","93_trade_report");
  
        $this->breadcrumbs=array(
        Yii::t("sp","4_sp_report")=>array('/sp/'),
        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->SetCountRowsTable(50);
				$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']))){
					$table = $accaunt->GetAccountTableTrader();
				}else{
					$table = $accaunt->GetAccountTableIb();
				}
				$pagination = $accaunt->GetPagination();
				$count = $accaunt->GetCount();
			}
					
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
								
		$view = new Platform();
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}		
		
		$backLink = $accaunt->getBackLink();

		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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink));
		}
    }
    public function actionHistory(){
        $this->render('history');
    }
	
	#----------------------------------------------------	
	#----------------------------------------------------	
	#----------------------------------------------------		
	
    public function actionClosedSum(){

		$this->pageTitle=Yii::t("main","95_closed_trades_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","4_sp_report")=>array('/sp/'),
        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->SetCountRowsTable(50);
			$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']))){
				$table = $accaunt->GetAccountTableTrader();
			}else{
				$table = $accaunt->GetAccountTableIb();
			}
			$pagination = $accaunt->GetPagination();
			$count = $accaunt->GetCount();
        }
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}			
				$view = new Platform();
				
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}				
		
		$backLink = $accaunt->getBackLink();
		
		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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now));
		}
    }
	
	#----------------------------------------------------	
	#----------------------------------------------------	
	#----------------------------------------------------	 
	
    public function actionDeposWithdrawal(){
				
				
		$this->pageTitle=Yii::t("main","99_depositwithdrawal_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","4_sp_report")=>array('/sp/'),
        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->SetCountRowsTable(50);
						$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']))){
								$table = $accaunt->GetAccountTableTrader();
						}else{
								$table = $accaunt->GetAccountTableIb();
						}
						$pagination = $accaunt->GetPagination();
						$count = $accaunt->GetCount();
        }
        if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
								
				$view = new Platform();
					$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
		$backLink = $accaunt->getBackLink();
		
		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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now ));
		}

    }
#----------------------------------------------------	
#----------------------------------------------------	
#----------------------------------------------------			   
    public function actionSegregated(){
        
        $this->render('segregated');
    }
/*----------------------------------------------*/				
/*----------------------------------------------*/				
/*----------------------------------------------*/					
    public function actionClosedSumTrade(){
	
		$this->pageTitle=Yii::t("main","97_close_trade_summary_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","4_sp_report")=>array('/sp/'),
        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->SetCountRowsTable(50);
                $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']))){
                    $table = $accaunt->GetAccountTableTrader();
                }else{
                    $table = $accaunt->GetAccountTableIb();
                }
                $pagination = $accaunt->GetPagination();
                $count = $accaunt->GetCount();
        }
		if(Yii::app()->request->isAjaxRequest){ 
			if($count==0){
				$table = '<tr><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
			}
			exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
		}
	
	     $view = new Platform();
		 
		 $backLink = $accaunt->getBackLink();
		 
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
		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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now));
		}
	
    }
#----------------------------------------------------	
#----------------------------------------------------	
#----------------------------------------------------					
    public function actionSummary(){
				
				
    	$this->pageTitle=Yii::t("main","101_summary_report");
        
        $this->breadcrumbs=array(
        Yii::t("sp","4_sp_report")=>array('/sp/'),
        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->SetCountRowsTable(50);
						$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']))){
								$table = $accaunt->GetAccountTableTrader();
						}else{
								$table = $accaunt->GetAccountTableIb();
						}
						$pagination = $accaunt->GetPagination();
						$count = $accaunt->GetCount();
        }
	if(Yii::app()->request->isAjaxRequest){ 
		if($count==0){
			$table = '<tr><td style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
		}
		exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
	}
	
		$view = new Platform();
		
		$parentcode=5;
		$rez=$accaunt->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}
		
		$backLink = $accaunt->getBackLink();
		
		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, 'parentcode'=>$parentcode, 'info'=>$accaunt->getInfo(), 'backLink'=>$backLink, 'now'=>$now));
		}
       
    }
    public function actionFormsAgreements(){
            $this->pageTitle=Yii::t("sp","29_forms_and_agreements");

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

			$account = new Account();
			$info=$account->GetInfo();
			if($info->Login == '1000107408' || $info->Login == '1000107406'|| $info->Code == 596 || $info->Code == 600 || $info->Code == 601 || $info->Code == 617 || $info->Code == 624){die();}
			
            $ViewFolder= wlParams::get('docsFolderServer').'/agreements';
            $json = file_get_contents($ViewFolder);
            $files = json_decode($json,true);

            $this->render('formsAgreements', array('files'=>$files,'path'=>$ViewFolder));
    }
    public function actionSupport(){
            $this->pageTitle=Yii::t("sp","28_support");

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

            $this->render('support', array());
    }
#----------------------------------------------------	
#----------------------------------------------------	
#----------------------------------------------------	
    public function actionFindByEmail(){
        
        $this->pageTitle=Yii::t("sp","11_find_account_by_email");
        
        $this->breadcrumbs=array(
        Yii::t("sp","4_sp_report")=>array('/sp/'),
        Yii::t("sp","11_find_account_by_email"));
        $table = $pagination = null;
        
        if(Yii::app()->request->isPostRequest){
            $repor = new Report(6);
			$repor->SetCountRowsTable(50);
            $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 style="display:table-cell; text-align:center; font-size:13px; color:black;" colspan="0">'.Yii::t("main","441_no_results").'</td><tr>';
				}
				exit(json_encode(array('table'=>$table,'count'=>$count,'itemsOnPage'=>$itemsOnPage)));
			}
        }
		$Account = new Account();		
		$parentcode=5;
		$rez=$Account->GetParentCode();
		if(isset($rez)&& $rez>0){$parentcode=$rez;}				
								$view = new Platform();
        $this->render('findByEmail',array('table'=>$table,'pagination'=>$pagination,'paltforms'=>$view->GetList(),'mas_numb'=>$this->mas_numb, 'parentcode'=>$parentcode));
    }
    public function actionDwnlCsv(){
		$repor= new Report($_GET['rp']);
		$repor->attributes=$_REQUEST; 
		$link=$repor->GetLinkCsv();
		

		if($repor->GetLinkCsvError() != "ReportIsEmpty"){
			Yii::app()->getController()->redirect($link);
		}else{
			exit('ReportIsEmpty');		
		}
	}
	
	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 actionPromoCenter() {
            $this->pageTitle = Yii::t("trader", "66_PromoCenter");
            $this->breadcrumbs = array(Yii::t("trader", "66_PromoCenter"));
			$view=new Account();
			$ParentCode=$view->GetParentCode();
			
            $this->render('promoCenter', array('ParentCode'=>$ParentCode));
    }
    public function actionPromoBanner() {
            if(Yii::app()->browser->isBrowser('Internet Explorer') && (Yii::app()->browser->getVersion() == '8.0')){							
                Yii::app()->getController()->redirect("/errorIE7");
            }
            $this->pageTitle = Yii::t("trader", "67_PromoBanner");
            $this->breadcrumbs = array(
                Yii::t("trader", "66_PromoCenter") => array('/sp/promoCenter.html'),
                Yii::t("trader", "67_PromoBanner"));

            
            $account = new Account();
            $info = $account->GetInfo();
            
            $limit = 5;
            $model = new MyBanner();
            if(Yii::app()->request->isAjaxRequest){
                 if(isset($_REQUEST['type'])){ 
                    if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'new'){
                       echo 'new'.$_REQUEST['settings'];
                       $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/newBanner', array('limit'=>$limit, 'code'=>$info->Code, 'server'=>Yii::app()->params['server'],'settings'=>$_REQUEST['settings'] ),80);
                       print_r($ib_site_info);
                   }

                   if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'update'){
                       echo 'update'.$_REQUEST['settings'];
                       $ib_site_info = Yii::app()->curl->post('http://ib.bmfn.com/updateBanner', array('code'=>$info->Code, 'server'=>Yii::app()->params['server'],'settings'=>$_REQUEST['settings'],'hashtag'=>$_REQUEST['hashtag'] ),80);
                       print_r($ib_site_info);
                   }

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

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

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

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