<?php
ini_set("memory_limit","800M");
set_time_limit ( 3000 );
class CronController extends Zend_Controller_Action
{
	private $usersDB;
	private $tounament;
	private $assessment;
	private $fixture;
	
	public function init()
	{
		$this->usersDB = new Model_Profile;
		$this->assessment = new Model_Assessments;
		$this->fixture = new Model_Fixture;
		$this->tounament = new Model_Tournament;
		
	}
	
	
	
	
	public function autorunAction()
	{
		
        $this->_helper->layout->disableLayout();
		
	}
	
	
	
	
	public function queingAction()
	{
		$this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout();
		
		$applydb = new Model_AccreditationsApplications;
	   
        $queingArray = $applydb->getCue();
		if(count($queingArray)>0){
			
		
		foreach($queingArray as $data){
			
			$this->addtozip($data);
			if($data["AC"]==14){
				$this->senddata_to_Api($data["AAID"]);
			}
		}
		}
		
		
		
		
		/*
		ob_end_clean();
ignore_user_abort();
ob_start();
header("Connection: close");
echo "Total Left : ".count($queingArray);
header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
		*/
		
		
		
	}
	
	public function senddata_to_Api($ID){
		$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
		
		
		$applydb = new Model_AccreditationsApplications;
		$zonesdb = new Model_AccreditationZone;
		$APPLICATION = $applydb->getProfile($ID);
		$ZONES = "";
		if(!empty($APPLICATION["Zones"])){
		$ZonesArray = json_decode($APPLICATION["Zones"],true);
		$zones = $zonesdb->getZonesByIDs($ZonesArray);
		if(count($zones)>0){
			$n =0;
			foreach ($zones as $zone) {
				$c =" ";
				if($n==0){$c ="";}
				$ZONES .= $c.$zone["Number"];
				$n++;
			}
		}
			
		}
		$barcode = $APPLICATION["Barcode"];
		if(empty($barcode)){
			//$barcode = $APPLICATION["Ref"];
		}
		$data = array(
		    'G' => 'Guest',
		    'A' => 'acrSARugby',
		    'Barcode' => $barcode,
		    'Name' => $APPLICATION["FirstName"],
		    'Surname' => $APPLICATION["Surname"],
		    'IDNo' => $APPLICATION["IDnumber"],
		    'Category' => $APPLICATION["Cat"],
		    'Zone' => $ZONES,
		    'TheFile' => $APPLICATION["User_pic"]
		);
		$ch = curl_init();
	
    
    //curl_setopt($ch, CURLOPT_URL, "https://footprintapp.net/test/recievedata");
	curl_setopt($ch, CURLOPT_URL, "https://fsrugby.appwizard.co.za/scripts/AppWiz.dll");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
    //curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER,  array(
            'Content-type: multipart/form-data'
        ));
		
		
		
		
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$output = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);
		//print_r($output);
		
		
	}
	
	private function addtozip($data){
		
		$return = false;
		require_once("dompdf/dompdf_config.inc.php");
        
		$http = "http";
		if( isset($_SERVER['HTTPS'] ) ) 
		{
            $http = "https";
        }
		try{
        $url = $http."://".$_SERVER["SERVER_NAME"]."/pdf/a6/id/".$data["AAID"];
		
        $html = file_get_contents($url);
        $dompdf = new DOMPDF();
		$html = iconv('UTF-8','Windows-1250',$html);
        $dompdf->load_html($html);
		
		if(empty($html)){
			echo "<br />HTML EMPTY< BR />";
		}
		
		$Zonedb = new Model_AccreditationList;
		$Zones = $Zonedb->getApplicationZones($data["AC"]);
		
		echo "<br />";
		echo $data["AAID"]." ".$data["FullName"];
        
		                 
		$dompdf->set_option( 'dpi' , '300' );		
        $dompdf->set_paper('a6','portrait');
        //$dompdf->set_paper(array(0, 0, 1240, 1748), 'portrait');
        $dompdf->render();
        //$dompdf->stream($data["FirstName"]."_".$data["Surname"]."-".date("Y-m-dH:i:s").".pdf");
       // 
       
       
       // folder
       $folder = IMG_PATH."/accre/pdfs/";
	   $Accrefolder = $folder."/".$data["AC"];
	   if(!is_dir($Accrefolder)){
	   	 mkdir($Accrefolder);
	   	 
	   }
	   //Craete Category
	   $CategoryFolder = $Accrefolder."/".$data["Cat"];
	   
	   if(!is_dir($CategoryFolder)){
	   	 mkdir($CategoryFolder);
	   	 
	   }
	   
	   
	    
	   
	   $name = $data["Rol"];
	   // if teams 
	   
	   if($data["SquadID"]>0){
	   	$TeamsFolder = $CategoryFolder."/".$data["SquadName"];
	   	 if(!is_dir($TeamsFolder)){
	   	 mkdir($TeamsFolder);
	   	 
	   	}
		 
		 $rolesFolder = $TeamsFolder;
		 $name = $data["SquadName"];
	   }else{
	   	//Craete Roles
	   $rolesFolder = $CategoryFolder."/".$data["Rol"];
	   
	   if(!is_dir($rolesFolder)){
	   	 mkdir($rolesFolder);
	   	 
	   }
	   }
	   
	   
	   //ZipFOlder
	   if(file_exists($rolesFolder."/".$data["FirstName"]."_".$data["Surname"].".pdf")){ //if file exist delete
	   	unlink($rolesFolder."/".$data["FirstName"]."_".$data["Surname"].".pdf");
	   }
	  
	  if(file_put_contents($rolesFolder."/".$data["FirstName"]."_".$data["Surname"].".pdf", $dompdf->output()))
	  {
	  	$applydb = new Model_AccreditationsApplications;
		$update = $applydb->update(array("Cue"=>0,"Status"=>3,"Cue_error"=>0),"AAID ='".$data["AAID"]."'");
	  }
	  }catch(exception $e){
	  	echo "<br />There was a problem ,AAID: ".$data["AAID"]."<br /><pre>";
		$applydb = new Model_AccreditationsApplications;
		$update = $applydb->update(array("Cue_error"=>1),"AAID ='".$data["AAID"]."'");
		
		//print_r($e);
	  }
	   
	   
	  //$this-> zipfiles($rolesFolder,$CategoryFolder,$name);
	   
	}


        
        public function testareaAction()
	{
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
              $where = "";
            $tourn = $this->gettourn();
            echo "<pre>";
            print_r($tourn);
            
            
        }
        
		
		
		
		public function getaccreAction(){
			$this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
            $QueDB = new Model_AccreditationQueing;
         
            $Squads = $QueDB->fetchAll();
            if(count($Squads)>0){
            	foreach($Squads as $Squad){
            	$this->ApplyAccreditationNow($Squad["SID"]);
					$QueDB->delete("SID ='".$Squad["SID"]."'");
            	}
            }
            
        }
		
		
		
function random_id($bytes) {
    $rand = mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
    return bin2hex($rand);
}


////////////////////////
		
		
		
		
		
        public function gettourn(){
            $TournamentsDB = new Model_Tournament;
         
            $Tournament = $TournamentsDB->getAllOpen();
           
            if(count($Tournament)>0){ $Tournament= $Tournament->toArray();}
            return $Tournament;
            
            
        }
        
        
        public function readfileAction()
	{
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
            
        }
        
        
        
        
        public function matchesAction()
	{
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
           
            $tourns = $this->gettourn();
             $FixtureDB = new Model_Fixture;
            if(count($tourns)>0){
            foreach($tourns as $tourn){
               
                $this->setfixturesByWinAnLose($tourn["TID"]);
				
                if($tourn["Structure"] ==2){
					$FixtureDB->setSquadByScorePool($tourn);
					$FixtureDB->setSquadByScore($tourn);
				}else{
					$FixtureDB->setSquadByScore($tourn);
				}
                
                                
            }
            }
           
		
	}
        
        
        
        
        function setfixturesByWinAnLose($TID){
            
            $Squads = new Model_Squad();
           $Fixtures = $this->fixture->getWinAndLosePlayOff($TID);
		   $this->checkPoolPlayOffs($TID);
           print_r($Fixtures->toArray());
            //$Fixtures = $this->fixture->fetchAll("TID ='99'");
           if(count($Fixtures)>0){
            foreach($Fixtures as $Fixture){
                $HomeIDDate = $this->fixture->getFixtureResult($Fixture["HomeTeamGameNumber"],$Fixture["HomeTeamGameNumberOption"]);
                $AwayIDData = $this->fixture->getFixtureResult($Fixture["AwayTeamGameNumber"],$Fixture["AwayTeamGameNumberOption"]);
                
               $HomeID = $HomeIDDate["ID"];
               $AwayID = $AwayIDData["ID"];
               if($HomeID >0 && $AwayID>0){
                $this->fixture->updateData(array("Assignment"=>4,"HomeTeam"=>$HomeID,"AwayTeam"=>$AwayID), $Fixture["FID"]);
               }
               $content = file_get_contents("fixt.txt");
               file_put_contents("fixt.txt", $content."\n".date("y-m-d H:s:i"));
            }
           }
        }
        function checkPoolPlayOffs($TID){
            $Squads = new Model_Squad();
            $Fixtures = $this->fixture->getPoolRankingPlayOff($TID);
            $fno = 1;
            foreach($Fixtures as $Fixture){
                
               $SquadHome = $Squads->getGetSquadByRankInPool($TID,$Fixture["HomeTeamGameNumber"],$Fixture["HomeTeamGameNumberOption"]);
               $SquadAway = $Squads->getGetSquadByRankInPool($TID,$Fixture["AwayTeamGameNumber"],$Fixture["AwayTeamGameNumberOption"]);
              
               
              //$this->fixture->updateData(array("HomeTeam"=>$SquadHome["SID"],"AwayTeam"=>$SquadAway["SID"],"Assignment"=>4), $Fixture["FID"]);
                
               
               echo $fno.", ".$SquadHome["ShortName"]." VS ".$SquadAway["ShortName"]."<br />";
               echo "Home Pool:".$Fixture["HomeTeamGameNumber"]."  | Home Ranking: ".$Fixture["HomeTeamGameNumberOption"];
               echo "Away Pool:".$Fixture["AwayTeamGameNumber"]."  | Away Ranking: ".$Fixture["AwayTeamGameNumberOption"];
               echo "<pre>";
               print_r($SquadAway->toArray());
                
            $fno++;
            }
            
          
            
        }
	public function logsAction()
     {
    	
        $request = $this->getRequest();
        $id = $request->getParam("id");
		
		$TournDB = new Model_Tournament;
        $Tournament = $TournDB->fetchRow("TID ='".$id."'");
		
		
		
        $FixtureDB = new Model_Fixture;
		$FixtureDB->setSquadByScorePool($Tournament);
                
			    
                
    }
public function viewAction()
    {
    file_put_contents("cron.txt", date("y-m-d H:s:i"));
        $request = $this->getRequest();
        $id = 100;
        
        $TournDB = new Model_Tournament;
        $Tournament = $TournDB->fetchRow("TID ='".$id."'");
                
        $this->view->assign("data",$Tournament);
				$FixtureDB = new Model_Fixture;
				$data =$FixtureDB->getFixtures($id)->toArray();
				
		//Get Countries Hosting
                $CountryDB = new Model_Country;
		
                $Country = "";
                $n =0;
                foreach ($CountryDB->getAll() as $dataa)
                { 
                    if(!empty($dataa)){
                    $Co ="";
                    if($n>0){
                        $Co=" / ";
                        
                    }
                                     
                                        if(@in_array($dataa['country_code'],@json_decode($Tournament["Countries"],true))){
                                            $Country = $Country.$Co.$dataa['country_name'];
                                            
                                        }
                                     $n++;    
                }																			
                                                                            
                }
                
                $this->view->assign("Country",$Country);
                 
                
                                
                //Tournament Director
                $Officials = json_decode($Tournament["Officials"],true);
               
                $Director = "<a style='color:red'>Not Assigned</a>";
                if(count($Officials)>0){
                    
                    if(isset($Officials[1])){
                            $profileDB = new Model_Profile;
                            $Profile = $profileDB->getPerson($Officials[1]["UserID"]);
                            $Director = "<a href='/mambers/profile/id/".$Profile["UserID"]."' target='_black'>".  getFullName($Profile)."</a>";
                    }
                    
                }
                                
                 $this->view->assign("Director",$Director);               
                                
				
                
                
                     // see if all squads are created fro this tournament ()
               
                
                
		$dbAdminssions = new Model_SquadAdmission;
                        $AdmissionList= $dbAdminssions->getAll($id);
                        $this->view->assign("Admission",$AdmissionList);
                        
                       
				if($Tournament["Structure"] ==2){
					$FixtureDB->setSquadByScorePool($id,$Tournament);
					$FixtureDB->setSquadByScore($id);
					
				}else{
					$FixtureDB->setSquadByScore($id);
				}
				
				
				 $TitleDB = new Model_Title;
				$this->view->assign("Title",$TitleDB->getAll());
		
		
				
		$this->view->assign("fixtures",$data);
		
	
		
       $squadsDB = new Model_Squad;
		$Members = $squadsDB->getSquadByTaurnament($id);
		 $this->view->assign("Members",$Members->toArray());
			 
			 
			 
		
		$ReviewerBtn= 1;
		if(!isset($this->AccessRights["tournament"]["Actions"]["RefereeReviewer"]) && $Tournament["RefereeReviewer"] != $this->identity->UserID ){
			$ReviewerBtn = 0;
		}
		$this->view->assign("ReviewerBtn",$ReviewerBtn);
		
		 $this->view->assign("Tournnament",$Tournament->toArray());
		 $FixtureDB = new Model_Fixture;
		$logsDB = new Model_TournamentLogs;
		//$SerieslogsDB = new Model_SeriesLogs;
			
		$squadDB = new Model_Squad;
		$Squads= $squadDB->getAllByTourn($id);
		$listArray = array();
		$i =0;
			
			
			$totalP = 0;
	        $black = 0;
	        $white = 0;
	        $indian = 0;
	        $coloured = 0;
					$undefied = 0;
                                        $Injuredplayers = array();
			foreach($Squads as $Squad){
				if($Tournament["SeriesID"] >0){
					//$States = $logsDB->getRow($Squad["TournamentID"],$Squad["SID"]);
					
				}else{
				$States = $logsDB->getRow($Squad["TournamentID"],$Squad["SID"]);
				$listArray[$Squad["SID"]]["ShortName"]		=	$Squad["ShortName"];
				$listArray[$Squad["SID"]]["SID"]					=	$Squad["SID"];
				$listArray[$Squad["SID"]]["Played"]				=	$States["Played"];
				$listArray[$Squad["SID"]]["Won"]					=	$States["Won"];
				$listArray[$Squad["SID"]]["Drow"]					=	$States["Drow"];
				$listArray[$Squad["SID"]]["Lost"]					=	$States["Lost"];
				$listArray[$Squad["SID"]]["Tries"]				=	$States["Tries"];
				$listArray[$Squad["SID"]]["Convertions"]	=	$States["Convertions"];
				$listArray[$Squad["SID"]]["DropGoals"]		=	$States["DropGoals"];
				$listArray[$Squad["SID"]]["Penalty"]			=	$States["Penalty"];
				$listArray[$Squad["SID"]]["PF"]						=	$States["PF"];
				$listArray[$Squad["SID"]]["PA"]					=	$States["PA"];
				$listArray[$Squad["SID"]]["AS"]					=	$States["PA"];
				$listArray[$Squad["SID"]]["PD"]					=	$States["PD"];
                               
                                }
				$i++;
				
				
				
				
				
				
				
				
			}

			if($Tournament["SeriesID"]>0){
				
			}else{
				//$this->array_sort_by_column($listArray, 'PD',SORT_DESC);
			}
		
			
		
			
			
					
					
					
					
					
		$FixtureDB = new Model_Fixture;
		$MatchReport = $FixtureDB->getTournReport($id);
		$PlayersStats = array();
		foreach ($MatchReport as $MatchReport) {
			$Score = json_decode($MatchReport["Score"],true);
			if(count($Score)>0){
				
			
			foreach ($Score as $s) {
								
				
				$PlayersStats["tries"]= @$PlayersStats["tries"]+$s["tries"];
				$PlayersStats["Conversions"]=@$PlayersStats["Conversions"]+$s["Conversions"];
				$PlayersStats["Penalties"]=@$PlayersStats["Penalties"]+$s["Penalties"];
				$PlayersStats["DropGoals"]=@$PlayersStats["DropGoals"]+$s["DropGoals"];
				$points = ($s["tries"]*$MatchReport["Tries"])+ ($s["Conversions"]*$MatchReport["Conversion"]) +($s["Penalties"]*$MatchReport["Penalties"]) + ($s["DropGoals"]*$MatchReport["Dropgoal"]) ;
				
				$PlayersStats["Points"]=@$PlayersStats["Points"]+$points;
			}
			}
			
		}
		$this->view->assign("Status",$PlayersStats);		
		$squadDB = new Model_Squad;
			 
			$SquadsDrop= $squadDB->getAllSquadsByTourn($id);
                        $this->view->assign("SquadsDrop",$SquadsDrop);
                        
                        $Rounds = $FixtureDB->getFixtureRounds($id);
                        $this->view->assign("Rounds",$Rounds);
					
			 $StractureDB = new Model_TournamentStructure;
                         $Stractures = $StractureDB->getAll();
                         $Stracturetype = "";
                         foreach ($Stractures as $Stracture)
                         {
                             if($Stracture["TSID"]==$Tournament["Structure"]){
                                 $Stracturetype["Name"] =$Stracture["Name"];
                                 $Stracturetype["Singular"] =$Stracture["Singular"];
                                
                             }
                             
                         }
                         $this->view->assign("Stracture",$Stracturetype);
                         
                        
                         
                         
    }
    
    public function getfixtuesAction(){
         $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
            $this->getfixtues();
    }
    
    public function getfixtues(){
         
        $fixruresDB = new Model_Fixture;
        $allfixtures = $fixruresDB->getClosedFixturesForRefAss();
        foreach($allfixtures as $fixture){
            $Assor = 0;
            $CoachA = 0;
            $CoachB = 0;
             
            
            $count =0;
            
            $MatchOfficials = json_decode($fixture["MatchOfficials"],true);
            
            foreach($MatchOfficials as $Official){
                if($Official["Pos"]==8){
                   $Assor =  $Official["ID"];
                }
            }
            
            
           $CoachesA = json_decode($fixture["CoachesA"],true);
            
            foreach($CoachesA as $Coache){
                if($Coache["Position"]==10){
                   $CoachA =  $Coache["ID"];
                }
            }
            $CoachesB = json_decode($fixture["CoachesB"],true);
            
            foreach($CoachesB as $Coache){
                if($Coache["Position"]==10){
                   $CoachB =  $Coache["ID"];
                }
            }
            
           $Assesors[0]["UID"] = $Assor;
           $Assesors[0]["FID"] = $fixture["FID"];
           $Assesors[0]["DateCreated"] = $fixture["FixtureDate"];
           $Assesors[0]["UID"] = $Assor;
           $Assesors[0]["SID"] = 0;
           
            $Assesors[1]["UID"] = $CoachA;
           $Assesors[1]["FID"] = $fixture["FID"];
           $Assesors[1]["DateCreated"] = $fixture["FixtureDate"];
           $Assesors[1]["SID"] = $fixture["HomeTeam"];
            
           $Assesors[2]["UID"] = $CoachB;
           $Assesors[2]["FID"] = $fixture["FID"];
           $Assesors[2]["DateCreated"] = $fixture["FixtureDate"];
           $Assesors[2]["SID"] = $fixture["AwayTeam"];
            
           
           //check if line existes
           $RefAssDB = new Model_RefereeAssessors;
           
           foreach($Assesors as $Assesor){
              $Assessment = $RefAssDB->fetchRow("FID ='".$fixture["FID"]."' AND UID ='".$Assesor["UID"]."'");
              
              
                if($Assessment["RID"]>0){
                    $RefAssDB->update($Assesor, "RID ='".$Assessment["RID"]."'");
                }else{
                    $RefAssDB->insert($Assesor);
                }
           }
            
           
        }
      
        
    }
    
    
    }