<?php
class CompanyController extends Controller{
	
	public $layout = 'column2';
	public $countRows = 25;
        public $mas_numb = array("25", "50", "100", "200");
	
	public function accessRules() {

            return array(
                array('allow', // allow ib user to perform actions
                    'actions' => array('Index','Risks','ReportMT','ReportTransaction','ReportTransactionExport','ReportTransactionSummary','CompanyInfo','SummaryRisksInstr','SummaryRisksCurr','SummaryPL','SetupConditions', 'AccountList'),
                    'roles' => array('user14'),
                ),
                array('deny', // deny all users
                    'users' => array('*'),
                ),
            );
        }

    
    
	public function actionIndex() {
            $this->pageTitle=Yii::t("sp","55_company_info");		
            $this->render('index');
	}
         public function actionReportTransactionExport() {
             
            $startDate= explode('/', $_REQUEST['startDate']);
            $endDate= explode('/', $_REQUEST['endDate']);
             
            $startD = mktime("17","00","00",$startDate[0],$startDate[1],$startDate[2]);
            $endD = mktime("17","00","00",$endDate[0],$endDate[1],$endDate[2]);

            $url = (array)Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/SummaryTransactionReportToExcell?guid='.Yii::app()->user->id.'&from='.$startD.'&to='.$endD);
            $this->redirect($url[0]);
            Yii::app()->end();           
	}
        public function actionReportMT() {
                      
            $this->pageTitle=Yii::t("sp","143_ReportMT");		
            $this->breadcrumbs=array(Yii::t("sp","143_ReportMT"));
            
            $rep = new Report(10);  
            
            if(Yii::app()->request->isAjaxRequest){ 
               
                $rep->startDate = $_REQUEST['startDate'];
                $rep->endDate = $_REQUEST['endDate'];
                
                echo $rep->GetMTReport();
                Yii::app()->end();
            }
            
            $table =  $rep->GetMTReport();
            $this->render('reportMT', array('table'=>$table));
	}
        
        public function actionReportTransactionSummary() {
            $this->pageTitle=Yii::t("sp","143_ReportTransaction");		
            $this->breadcrumbs=array(Yii::t("sp","143_ReportTransaction"));
            
            $rep = new Report(9);  
            
            if(Yii::app()->request->isAjaxRequest){ 
               
                $rep->startDate = $_REQUEST['startDate'];
                $rep->endDate = $_REQUEST['endDate'];
                
                echo $rep->GetSummaryTransactionReport();
                Yii::app()->end();
            }
            
            $table = $rep->GetSummaryTransactionReport();

            $this->render('reportTransactionSummary', array('table'=>$table));
	}
        
        
        public function actionReportTransaction() {
            $this->pageTitle=Yii::t("sp","143_ReportTransaction");		
           
            if (isset($_REQUEST['typeTransaction'])){
                $type = $_REQUEST['typeTransaction'];
                $this->breadcrumbs=array(Yii::t("sp","143_ReportTransaction")=>array('/company/reportTransactionSummary.html'),$type);

                $rep = new Report(9);  

                $rep->attributes=$_REQUEST;
                $startDate  = $rep->startDate   = $_REQUEST['startDate'];
                $endDate    = $rep->endDate     = $_REQUEST['endDate'];   
                
               
            
                $table = $rep->ReportTransaction($type);
                $tableHead = $rep->getTableHead($type);
                $pagination = $rep->GetPagination();  
                $pagination['form'] = $type;
                $count = $rep->GetCount();
                $itemsOnPage = $rep->GetRowsTable(); 
                
                if(Yii::app()->request->isAjaxRequest){ 
                    exit(json_encode(array('table' => $table, 'count' => $count, 'itemsOnPage' => $itemsOnPage)));
                }                
                $this->render('reportTransaction', array('tableHead'=>$tableHead,'table'=>$table,'pagination'=>$pagination,'type'=>$type, 'mas_numb' => $this->mas_numb));
           }else{
               $this->redirect(array('/company/reportTransactionSummary.html'));
           } 
	}
        
        
        
       
        public function actionSetupConditions(){
		$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"));
		$Competition = new Competition();
                
                if (Yii::app()->request->isAjaxRequest){
                    switch (Yii::app()->request->getPost('Action')) {
                        case 'Add':
                            $obj = $Competition->AddSalesCompetitionRules();
                            print_r($obj['id']); 
                            break;
                        case 'Delete':
                            $post = json_decode(Yii::app()->request->getPost('Competition'), true);
                            $State = $Competition->DeleteSalesCompetitionRules($post['id']);
                            print_r($State); 
                            break;
                        case 'Update':
                            $post = Yii::app()->request->getPost('Competition');
                            $arr = json_decode($post, true);
                            $State = $Competition->UpdateSalesCompetitionRules($arr['id'], $post);
                            print_r($State); 
                            break;
                    }
                    Yii::app()->end();
                }
                
		
		$rules = $Competition->GetAllSaleCompetitionRules();
		$this->render('conditions', array('rules' => $rules));
	}
	
        public function actionRisks() {
            $this->pageTitle=Yii::t("sp","54_risks");		
            $this->breadcrumbs=array(Yii::t("sp","54_risks"));
            $Risks = new Risks();
            $platforms = $Risks->GetServersList();
            $this->render('risks', array('platforms'=>$platforms));
	}
	public function actionSummaryRisksInstr(){
		$this->pageTitle=Yii::t("sp","84_summary_risks");		
		
		$this->breadcrumbs=array(
		Yii::t("sp","54_risks")=>array('/company/risks.html'),
		Yii::t("sp","84_summary_risks"));

		$Risks = new Risks();
		$Report = new Report(8);
		$platforms = array();
		foreach($Risks->GetServersList() as $pl){
			$platforms[$pl->PlatformID] = $pl;
		}
		
		if(isset($_GET['server']) && $_GET['server']!=''){
			$serverId = $_GET['server'];
		}else{
			$serverId = -1;
		}
		$data = $Risks->GetServerRiskPairPL($serverId);
		$table = '';
		$tr_count = 0;
		foreach($data as $dt){
			$table .= '<tr>';
				$total_volume = 0;
				$cust_net_exposure = 0;
				$delta_pl = 0;
				$total_pl = 0;
				if(isset($_POST["opdened"]) && !empty($_POST["opdened"])){
					if(in_array($tr_count, $_POST["opdened"])){
						$table .= '<td class="plus__ znak__">–</td>';
					}else{
						$table .= '<td class="plus__ znak__">+</td>';					
					}
				}else{
					$table .= '<td class="plus__ znak__">+</td>';					
				}
				foreach($dt as $key=>$td){
					if($key=='Symbol'){
						$class = 'aleft';
						$table .= '<td class="'.$class.'">'.$td.'</td>';
					}else{
						$class = '';
						$table .= '<td class="'.$class.'">'.$Report->number_format_bmfn($td, 2, '.', ',',true).'</td>';
					}
					switch($key){
						case 'BuyVolume': 
							$total_volume += (float)$td;
						break;
						case 'SellVolume': 
							$total_volume += (float)$td;
							$table .= '<td>'.$Report->number_format_bmfn($total_volume, 2, '.', ',',true).'</td>';
						break;
						case 'LongExplosure': 
							$cust_net_exposure += (float)$td;
						break;
						case 'ShortExplosure': 
							$cust_net_exposure -= (float)$td;
							$table .= '<td>'.$Report->number_format_bmfn($cust_net_exposure, 2, '.', ',',true).'</td>';
						break;
						case 'ClosedPL': 
							$total_pl += (float)$td;
						break;
						case 'PreviousFloatPL': 
							$delta_pl = (float)$td;
						break;
						case 'FloatPL': 
							$delta_pl = abs($delta_pl-(float)$td);
							$total_pl += $delta_pl;
							$table .= '<td>'.$Report->number_format_bmfn($delta_pl, 2, '.', ',',true).'</td>';
							$table .= '<td>'.$Report->number_format_bmfn($total_pl, 2, '.', ',',true).'</td>'; 
						break;					
					}
				}
			$table .= '</tr>';
			$tr_count++;
		}
		
		if(Yii::app()->request->isAjaxRequest){ 
			echo json_encode($table);
			Yii::app()->end();
		}
        $this->render('summaryRisksInstr', array('table'=>$table, 'platforms'=>$platforms, 'serverId'=>$serverId));
	}
	public function actionSummaryRisksCurr(){
		$this->pageTitle=Yii::t("sp","84_summary_risks");		
		
		$this->breadcrumbs=array(
		Yii::t("sp","54_risks")=>array('/company/risks.html'),
		Yii::t("sp","84_summary_risks"));

		$Risks = new Risks();
		$Report = new Report(8);
		$platforms = array();
		foreach($Risks->GetServersList() as $pl){
			$platforms[$pl->PlatformID] = $pl;
		}
		
		if(isset($_GET['server']) && $_GET['server']!=''){
			$serverId = $_GET['server'];
		}else{
			$serverId = -1;
		}
		
		$data = $Risks->GetServerRiskExplosure($serverId);
		$table = '';
		$tr_count = 0;
		$minus = 0;
		$plus = 0;
		//var_dump($data);die();
		foreach($data as $dt){
			$table .= '<tr>';
			foreach($dt as $key=>$td){
				if($key=='priority')continue;
				$class = '';
				if((float)$td>=0){
					$plus += (float)$td;
				}else{
					$minus += (float)$td; 
					$class .= 'red'; 
				}
				
				if($key=='Currency'){
					$class .= " aleft";
				}else{
					$class .= "";
				}
				
				if(is_numeric($td)){
					$table .= '<td class="'.$class.'">'.number_format($td, 2, '.', ',').'</td>';
				}else{
					$table .= '<td class="'.$class.'">'.$td.'</td>';
				}
			}
			$table .= '</tr>';
			
			$trtotals  = '<tr class="cbg"><td class="bold aleft">'.Yii::t("sp","42_total").'</td><td></td><td>'.number_format($plus+$minus, 2, '.', ',').'</td></tr>';
			$trtotals .= '<tr class="cbg"><td class="bold aleft">'.Yii::t("sp","80_agr_long").'</td><td></td><td>'.number_format($plus, 2, '.', ',').'</td></tr>';
			$trtotals .= '<tr class="cbg"><td class="bold aleft">'.Yii::t("sp","81_agr_short").'</td><td></td><td>'.number_format($minus, 2, '.', ',').'</td></tr>';
		
		}
		$table = $trtotals.$table;
		if(Yii::app()->request->isAjaxRequest){ 
			echo json_encode($table);
			Yii::app()->end();
		}
        $this->render('summaryRisksCurr', array('table'=>$table, 'platforms'=>$platforms, 'serverId'=>$serverId));
	}
	public function actionSummaryPL(){
		$this->pageTitle=Yii::t("sp","70_all_summary_pl");		
		
        $this->breadcrumbs=array(
		Yii::t("sp","54_risks")=>array('/company/risks.html'),
		Yii::t("sp","70_all_summary_pl"));
	
		$Risks = new Risks();
		$Report = new Report(8);
		$platforms = array();
		foreach($Risks->GetServersList() as $pl){
			$platforms[$pl->PlatformID] = $pl;
		}
	
		$data = $Risks->GetServersSummaryPL();
		
		$table = '';
		$tr_count = 0;
		foreach($data as $dt){
			$table .= '<tr>';
			$delta_pl = 0;
			$total_pl = 0;
			if(isset($_POST["opdened"]) && !empty($_POST["opdened"])){
				if(in_array($tr_count, $_POST["opdened"])){
					$table .= '<td class="plus__ znak__">–</td>';
				}else{
					$table .= '<td class="plus__ znak__">+</td>';					
				}
			}else{
				$table .= '<td class="plus__ znak__">+</td>';					
			}
			
		//	var_dump($dt);die();
			foreach($dt as $key=>$td){
				if($key=='ServerID'){
					$table .= '<td class="aleft">'.$platforms[$td]->Name.'</td>';
				}else{
					$table .= '<td>'.$Report->number_format_bmfn($td, 2, '.', ',',true).'</td>';
				}
				switch($key){
					case 'ServerID': 
						$total_pl = (float)$td;
					break;
					case 'RealizedPL': 
						$total_pl = (float)$td;
					break;
					case 'StartFloatingPL': 
						$delta_pl = (float)$td;
					break;
					case 'CurrentFloatingPL': 
						$delta_pl = (float)$td - $delta_pl;
						$table .= '<td>'.$Report->number_format_bmfn($delta_pl, 2, '.', ',',true).'</td>';
						
						$total_pl = $delta_pl + $total_pl;
						$table .= '<td>'.$Report->number_format_bmfn($total_pl, 2, '.', ',',true).'</td>';
					break;
				}
			}
			$table .= '</tr>';
		}
		
	//	var_dump($Risks->GetServersList(), $Risks->GetServersSummaryPL());die();
		if(Yii::app()->request->isAjaxRequest){ 
			echo json_encode($table);
			Yii::app()->end();
		}
        $this->render('summaryPL', array('table'=>$table));
	}
	
	public function actionCompanyInfo() {
		$this->pageTitle=Yii::t("sp","55_company_info");		
		
        $this->breadcrumbs=array(
		Yii::t("sp","55_company_info"));
	
		$cReport = new Report(8);
		
		$cReport->group = '-1';	
		
		if (Yii::app()->request->isAjaxRequest) {
			$cReport->startDate = $_POST['start_date'];
			$cReport->endDate = $_POST['end_date'];
			$cReport->initDate();
			if(isset($_GET['group'])){
				$cReport->group = $_GET['group'];
			}
			$table = $cReport->GetTotalReportByIBS();
			echo $table;
			Yii::app()->end();
		}
		
		$start = $start_user = mktime("00","00","00",date("m"),"01",date("Y"));
		$start = date('m/d/Y', strtotime(date('m/d/Y', $start) .' -1 day'));
		$start_d =explode("/",$start);
		$cReport->startDate = mktime("17","00","00",$start_d[0],$start_d[1],$start_d[2]);
		
		$cReport->endDate = mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));

		$table = $cReport->GetTotalReportByIBS();
        $this->render('companyInfo', array('startDate'=>$start_user, 'endDate'=>$cReport->endDate, 'table'=>$table));
	}
	public function actionAccountList() {
        $this->pageTitle=Yii::t("main","91_account_list_report");	
		$this->breadcrumbs=array(Yii::t("main","91_account_list_report"));	
		
		/*$this->breadcrumbs=array(
        Yii::t("sp","49_sv_reports_short")=>array('/sv/reports.html'),
        Yii::t("main","91_account_list_report"));*/
          
					
				$link_error=null;
								
				/*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=$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=$repor->GetLinkCsvError();
				}else{*/
					$accaunt= new Account();
					$accaunt->attributes=$_REQUEST; 
				
					$accaunt->countRowsTable=(isset($_REQUEST['countRowsTable']))?($_REQUEST['countRowsTable']):$this->countRows; //переопределение					
					$itemsOnPage=$accaunt->countRowsTable;
					//print_r($itemsOnPage); die();
					if($accaunt->isForm() == 'accountTrader' || Yii::app()->request->getPost('formIs') == 'accountTrader'){
					$table = $accaunt->GetAccountTableTrader();
				//	var_dump('c', $accaunt->group, $accaunt->isForm());die();
					}else{
							$table = $accaunt->GetAccountTableIb();
					}
					print_r($table); die();
					//$pagination = $accaunt->GetPagination();
					//var_dump($accaunt->isForm(), $pagination);die();
					//$pagination['form'] = $accaunt->isForm();
					//$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)));
		}
								
				$view = new Platform();*/
								
								
								
        $this->render('accountList',array('table'=>$table/*,'pagination'=>$pagination,'paltforms'=>$view->GetList(),'link_error'=>$link_error,'mas_numb'=>$this->mas_numb*/));
       
	}
}