<?php
ini_set("memory_limit","800M");

class PdfController extends Zend_Controller_Action
{
	
    public function fixturesbydateAction()
    {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
        $tid = $request->getParam("tid");
        $round = $request->getParam("round");
        $FixtureDB = new Model_Fixture;
        $TournDB = new Model_Tournament;
        if($tid>0){
            if($round>0){
                $Fixtures = $FixtureDB->getFixtureByRounds($tid, $round);
            }else{
                $Fixtures = $FixtureDB->getAllFixtureByTourn($tid);
            }
        $Tourn = $TournDB->getTourny($tid);
        $this->view->assign("Fixtures",$Fixtures);
        $this->view->assign("Tourn",$Tourn);
        if($round>0){
        }else{
           $this->_helper->viewRenderer('pdf/allfixtures', null, true);
        }
        }
        
        
        
	
      
    }
	public function getimageAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout();
        
        $request = $this->getRequest();
        $id = $request->getParam("id");
        $Aplications_DB = new Model_AccreditationsApplications;
        $Aplication = $Aplications_DB->getImagesAccreID($id);
        header("Content-type: image/jpeg");
        echo $Aplication['User_pic'] ;
      
       
 
  	}
	
	public function mypassAction()
    {
    	
       // $this->_helper->viewRenderer->setNoRender();
       $applydb = new Model_AccreditationsApplications;
	   
	  
	   $request = $this->getRequest();
	   $id = $request->getParam("id");
        $data = $applydb->getByID($id);
		
		$Zonedb = new Model_AccreditationList;
		$Zones = $Zonedb->getApplicationZones($data["AC"]);
		$pic = $Zonedb->getMyPass($data["AC"]);
		
		$file = "accre/MyPASS.jpg";
		//$file = '/accre/MyPASS-001-mobile.jpg';
		if(!empty($pic["Mypass_Bg"])){
			 $file =$pic["Mypass_Bg"];
		}
		$this->view->assign("BGIMG",$file);
		
		$MainFolder = UPLOADS_PATH;
				if(!is_dir($MainFolder))
				  {
				 	mkdir($MainFolder);
				  }
				  
				  
				  $barCodeFile = "";
		if(is_dir($MainFolder)){
			
				//save barcode
				$barCodeFile ="barcode".$id.".jpg";
				$http = "http://";
	if( isset($_SERVER['HTTPS'] ) ) {
            $http = "https://";
        }
	$barcode = $data["Ref"];
	if(!empty($data["Barcode"])){
		$barcode = $data["Barcode"];
	}
        $url = $http.$_SERVER["SERVER_NAME"]."/pdf/barcode/code/".$barcode;
		$img = $MainFolder."/".$barCodeFile;
		file_put_contents($img, file_get_contents($url));
			}
		$Zones = $Zones->toArray();
		$this->array_sort_by_column($Zones,"Number");
		
		$AccreditationProfile      =   $Zonedb->getProfileByID($data["AC"]);
		
		$AccritationTitle = $this->GetTtitle($AccreditationProfile);
		//$AccritationTitle ="Coca-Cola u16 Grant Khomo Week & u13 Craven Week";
		$this->view->assign("TITLE",$AccritationTitle);
		$this->view->assign("ACCRE",$AccreditationProfile);
		$this->view->assign("BARCODE",$barCodeFile);
		$this->view->assign("DATA",$data);
		$this->view->assign("ZONES",$Zones);
		
      	$this->_helper->layout->disableLayout();
		
		 

		$this->_helper->viewRenderer('pdf/mypass', null, true);
	}
	
	
	
	private function GetTtitle($AccreditationProfile){
	$AccreditationName =  $AccreditationProfile["TournName"];

if(!empty($AccreditationProfile["AccreditationName"]))
{
	$AccreditationName = $AccreditationProfile["AccreditationName"];
}




return $AccreditationName;
}
	
	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);
		
		
	}
    
    public function barcodeAction()
    {
    	$request = $this->getRequest();
		$code = $request->getParam("code");
        $this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
		require_once (TCPDF_PATH."/tcpdf_barcodes_2d.php");

		$type = "PDF417";

		$barcodeobj = new TCPDF2DBarcode($code, $type);

		$barcodeobj->getBarcodePNG();
	} 


 public function a5Action()
    {
    	
       // $this->_helper->viewRenderer->setNoRender();
       $applydb = new Model_AccreditationsApplications;
	   
	   $request = $this->getRequest();
	   $id = $request->getParam("id");
        $data = $applydb->getProfile($id);
		
		
		
		$Accredb = new Model_AccreditationList;
		$Zones = $Accredb->getApplicationZonesView($data["AC"]);
		
		$AccriditationProfile = $Accredb->getProfileByID($data["AC"]);
		
		
		
		//$Accreditation = $Zonedb->getProfileByID($data["AC"]);
		
		$MainFolder = UPLOADS_PATH;
				if(!is_dir($MainFolder))
				  {
				 	mkdir($MainFolder);
				  }
				  
				  
				  $barCodeFile = "";
		if(is_dir($MainFolder)){
			
				//save barcode
				$barCodeFile ="barcode".$id.".jpg";
				$http = "http://";
	if( isset($_SERVER['HTTPS'] ) ) {
            $http = "https://";
        }
	$barcode = $data["Ref"];
	if(!empty($data["Barcode"])){
		$barcode = $data["Barcode"];
	}
	
        $url = $http.$_SERVER["SERVER_NAME"]."/pdf/barcode/code/".$barcode;
		
		//$image = file_get_contents($url);

		
		// Echo out a sample image

				$img = $MainFolder."/".$barCodeFile;
				file_put_contents($img, file_get_contents($url));
			}
		$Zones = $Zones->toArray();
		$this->array_sort_by_column($Zones,"Number");
		
		$this->view->assign("BARCODE",$barCodeFile);
		$this->view->assign("DATA",$data);
		$this->view->assign("ZONES",$Zones);
		$this->view->assign("PROFILE",$AccriditationProfile);
		
		
      	$this->_helper->layout->disableLayout();

	$this->_helper->viewRenderer('accreditation/layouts/a5/defualt', null, true);
	}
    
	public function a6Action()
    {
    	
       // $this->_helper->viewRenderer->setNoRender();
       $applydb = new Model_AccreditationsApplications;
	   
	  
	   $request = $this->getRequest();
	   $id = $request->getParam("id");
	    $opt = $request->getParam("opt");
        $data = $applydb->getProfile($id);
		
		
		
		$Accredb = new Model_AccreditationList;
		$Zones = $Accredb->getApplicationZonesView($data["AC"]);
		
		$AccriditationProfile = $Accredb->getProfileByID($data["AC"]);
		
		
		
		//$Accreditation = $Zonedb->getProfileByID($data["AC"]);
		
		$MainFolder = UPLOADS_PATH;
				if(!is_dir($MainFolder))
				  {
				 	mkdir($MainFolder);
				  }
				  
				  
				  $barCodeFile = "";
		if(is_dir($MainFolder)){
			
				//save barcode
				$barCodeFile ="barcode".$id.".jpg";
				$http = "http://";
	if( isset($_SERVER['HTTPS'] ) ) {
            $http = "https://";
        }
	$barcode = $data["Ref"];
	if(!empty($data["Barcode"])){
		$barcode = $data["Barcode"];
	}
        $url = $http.$_SERVER["SERVER_NAME"]."/pdf/barcode/code/".$barcode;
		
		//$image = file_get_contents($url);

// Echo out a sample image

				$img = $MainFolder."/".$barCodeFile;
				file_put_contents($img, file_get_contents($url));
			}
		$Zones = $Zones->toArray();
		$this->array_sort_by_column($Zones,"Number");
		
		$this->view->assign("BARCODE",$barCodeFile);
		$this->view->assign("DATA",$data);
		$this->view->assign("ZONES",$Zones);
		$this->view->assign("PROFILE",$AccriditationProfile);
		
		
      	$this->_helper->layout->disableLayout();
		if($opt==2){
			$this->_helper->viewRenderer('accreditation/layouts/a6/double', null, true);
		}else{
			$this->_helper->viewRenderer('accreditation/layouts/a6/defualt', null, true);
		}
		
	}
  
    public function accreAction()
    {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
        $id = $request->getParam("id");
        $db = new Model_AccreditationList;
        $getData = $db->getProfileByID($id);
        $this->view->assign("DATA",$getData);
        
        
        $applydb = new Model_AccreditationsApplications;
        $getData = $applydb->getAllByID($id);
        $this->view->assign("APPLY",$getData);
        
        
    }
    
    public function tourninjuriesAction()
    {
    	$this->_helper->layout->disableLayout();
         $request = $this->getRequest();
        $tid = $request->getParam("tid");
        $TournDB = new Model_Tournament;
	$Tourn = $TournDB->getTourny($tid);
        $squadDB = new Model_Squad;
	$Squads= $squadDB->getAllByTourn($tid);
        $Injuredplayers = array();
        foreach($Squads as $Squad){
            $playersList = json_decode($Squad["Players"],TRUE);
                                foreach($playersList as $item){
                                    $IjuryDB = new Model_PlayerInjury;
                                    $PlayerFind = $IjuryDB->getInjured($item["ID"],$item["Position"],$Squad["SquadType"]);
                                    if(isset($PlayerFind["UserID"])){
                                        $Injuredplayers[$item["ID"]]=  $PlayerFind->toArray();
                                        $Injuredplayers[$item["ID"]]["SquadName"]=  $Squad["ShortName"];
                                         $Injuredplayers[$item["ID"]]["Jersey"]=  $item["Jersey"];
                                    }
                                   }
        }
        
        $this->array_sort_by_column($Injuredplayers, 'InjuryID',SORT_DESC);
	$this->view->assign("Injuries",$Injuredplayers);
        $this->view->assign("Tourn",$Tourn);
    }
    public function tournlogroundettAction()
    {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
        $tid = $request->getParam("tid");
        $round = $request->getParam("round");
        $dbTourn = new Model_Tournament;
        $ProfileDB = new Model_Profile;
        $Tourn = $dbTourn->getTourny($tid);
        $this->view->assign("Tourn",$Tourn);
        
        $squadDB = new Model_Squad;
        $logsDB = new Model_TournamentLogs;
        $FixtureDB = new  Model_Fixture;
        $Squads= $squadDB->getAllByTourn($tid);
        $Fixturelist = $FixtureDB->getFixturesByDate($tid,$round);
        $listArray = array();
        $listPlayers = array();
       if(count($Fixturelist)>0){
       
        foreach($Fixturelist as $Squad){
            if(!isset($listArray[$Squad["HomeTeam"]]["Won"])){
                $listArray[$Squad["HomeTeam"]]["Won"]=0;
            }
            if(!isset($listArray[$Squad["HomeTeam"]]["Played"])){
                $listArray[$Squad["HomeTeam"]]["Played"]=0;
            }
            if(!isset($listArray[$Squad["HomeTeam"]]["Drow"])){
                $listArray[$Squad["HomeTeam"]]["Drow"]=0;
            }
            if(!isset($listArray[$Squad["HomeTeam"]]["Lost"])){
                $listArray[$Squad["HomeTeam"]]["Lost"]=0;
            }
        
        
				$listArray[$Squad["HomeTeam"]]["ShortName"]		=	$Squad["SquadName1"];
				$listArray[$Squad["HomeTeam"]]["SID"]			=	$Squad["HomeTeam"];
				$listArray[$Squad["HomeTeam"]]["Played"]++;
                                
                                if($Squad["Home_HFS"]>$Squad["Away_HFS"]){
                                    $listArray[$Squad["HomeTeam"]]["Won"]++;
                                }
                                if($Squad["Home_HFS"]==$Squad["Away_HFS"]){
                                    $listArray[$Squad["HomeTeam"]]["Drow"]++;
                                }
                                if($Squad["Home_HFS"]<$Squad["Away_HFS"]){
                                    $listArray[$Squad["HomeTeam"]]["Lost"]++;
                                }
                                
				$listArray[$Squad["HomeTeam"]]["Tries"]			=	@$listArray[$Squad["HomeTeam"]]["Tries"]+$Squad["Home_Total_tries"];
				$listArray[$Squad["HomeTeam"]]["Convertions"]   =	@$listArray[$Squad["HomeTeam"]]["Convertions"]+$Squad["Home_Total_Convertions"];
				$listArray[$Squad["HomeTeam"]]["DropGoals"]		=	@$listArray[$Squad["HomeTeam"]]["DropGoals"]+$Squad["Home_Total_Dropgoals"];
				$listArray[$Squad["HomeTeam"]]["Penalty"]		=	@$listArray[$Squad["HomeTeam"]]["Penalty"]+$Squad["Home_Total_Penalties"];
				$listArray[$Squad["HomeTeam"]]["PF"]			=	@$listArray[$Squad["HomeTeam"]]["PF"]+$Squad["Home_HFS"];
				$listArray[$Squad["HomeTeam"]]["PA"]			=	@$listArray[$Squad["HomeTeam"]]["PA"]+$Squad["Away_HFS"];
				$listArray[$Squad["HomeTeam"]]["PD"]			=	@$listArray[$Squad["HomeTeam"]]["PD"]+$Squad["Home_HFS"]-$Squad["Away_HFS"];

                                
                                //Add Players
                                //$listPlayers
                                $HomePlayers = json_decode($Squad["Home_Score"],true);
                                foreach ($HomePlayers as $player) {
                                    $profile = $ProfileDB->getProfileNoPos($player["UserID"]);
						
						//"UserID":"6264","tries":"","Conversions":"","Penalties":"","DropGoals":""
						$listPlayers[$player["UserID"]]["UserID"]=$player["UserID"];
						$listPlayers[$player["UserID"]]["SID"]=$Squad["HomeTeam"];
						$listPlayers[$player["UserID"]]["SquadName"]=$Squad["SquadName1"];
						$listPlayers[$player["UserID"]]["tries"]= @$listPlayers[$s["UserID"]]["tries"]+$player["tries"];
						$listPlayers[$player["UserID"]]["Conversions"]=@$listPlayers[$s["UserID"]]["Conversions"]+$player["Conversions"];
						$listPlayers[$player["UserID"]]["Penalties"]=@$listPlayers[$s["UserID"]]["Penalties"]+$player["Penalties"];
						$listPlayers[$player["UserID"]]["DropGoals"]=@$listPlayers[$s["UserID"]]["DropGoals"]+$player["DropGoals"];
						$listPlayers[$player["UserID"]]["FirstName"]=$profile["FirstName"];
						$listPlayers[$player["UserID"]]["LastName"]=$profile["LastName"];
						
						$points = ($player["tries"]*$Tourn["Tries"])+ ($player["Conversions"]*$Tourn["Conversion"]) +($player["Penalties"]*$Tourn["Penalties"]) + ($s["DropGoals"]*$Tourn["Dropgoal"]) ;
						
						$listPlayers[$player["UserID"]]["Points"]=$listPlayers[$player["UserID"]]["Points"]+$points;
                                }
                                
                                
                                
                                
                                if(!isset($listArray[$Squad["AwayTeam"]]["Won"])){
                                        $listArray[$Squad["AwayTeam"]]["Won"]=0;
                                    }
                                    if(!isset($listArray[$Squad["AwayTeam"]]["Played"])){
                                        $listArray[$Squad["AwayTeam"]]["Played"]=0;
                                    }
                                    if(!isset($listArray[$Squad["AwayTeam"]]["Drow"])){
                                        $listArray[$Squad["AwayTeam"]]["Drow"]=0;
                                    }
                                    if(!isset($listArray[$Squad["AwayTeam"]]["Lost"])){
                                        $listArray[$Squad["AwayTeam"]]["Lost"]=0;
                                    }
        
        
				$listArray[$Squad["AwayTeam"]]["ShortName"]		=	$Squad["SquadName2"];
				$listArray[$Squad["AwayTeam"]]["SID"]			=	$Squad["AwayTeam"];
				$listArray[$Squad["AwayTeam"]]["Played"]++;
                                
                                if($Squad["Away_HFS"]>$Squad["Home_HFS"]){
                                    $listArray[$Squad["AwayTeam"]]["Won"]++;
                                }
                                if($Squad["Away_HFS"]==$Squad["Home_HFS"]){
                                    $listArray[$Squad["AwayTeam"]]["Drow"]++;
                                }
                                if($Squad["Away_HFS"]<$Squad["Home_HFS"]){
                                    $listArray[$Squad["AwayTeam"]]["Lost"]++;
                                }
                                
				$listArray[$Squad["AwayTeam"]]["Tries"]			=	@$listArray[$Squad["AwayTeam"]]["Tries"]+$Squad["Away_Total_tries"];
				$listArray[$Squad["AwayTeam"]]["Convertions"]           =	@$listArray[$Squad["AwayTeam"]]["Convertions"]+$Squad["Away_Total_Convertions"];
				$listArray[$Squad["AwayTeam"]]["DropGoals"]		=	@$listArray[$Squad["AwayTeam"]]["DropGoals"]+$Squad["Away_Total_Dropgoals"];
				$listArray[$Squad["AwayTeam"]]["Penalty"]		=	@$listArray[$Squad["AwayTeam"]]["Penalty"]+$Squad["Away_Total_Penalties"];
				$listArray[$Squad["AwayTeam"]]["PF"]			=	@$listArray[$Squad["AwayTeam"]]["PF"]+$Squad["Away_HFS"];
				$listArray[$Squad["AwayTeam"]]["PA"]			=	@$listArray[$Squad["AwayTeam"]]["PA"]+$Squad["Home_HFS"];
				$listArray[$Squad["AwayTeam"]]["PD"]                    =	@$listArray[$Squad["AwayTeam"]]["PD"]+$Squad["Away_HFS"]-$Squad["Home_HFS"];
                                
                                $AwayPlayers = json_decode($Squad["Away_Score"],true);
                              
                                foreach ($AwayPlayers as $player) {
                                    $profile = $ProfileDB->getProfileNoPos($player["UserID"]);
						
						//"UserID":"6264","tries":"","Conversions":"","Penalties":"","DropGoals":""
						$listPlayers[$player["UserID"]]["UserID"]=$player["UserID"];
						$listPlayers[$player["UserID"]]["SID"]=$Squad["HomeTeam"];
						$listPlayers[$player["UserID"]]["SquadName"]=$Squad["SquadName1"];
						$listPlayers[$player["UserID"]]["tries"]= @$listPlayers[$s["UserID"]]["tries"]+$player["tries"];
						$listPlayers[$player["UserID"]]["Conversions"]=@$listPlayers[$s["UserID"]]["Conversions"]+$player["Conversions"];
						$listPlayers[$player["UserID"]]["Penalties"]=@$listPlayers[$s["UserID"]]["Penalties"]+$player["Penalties"];
						$listPlayers[$player["UserID"]]["DropGoals"]=@$listPlayers[$s["UserID"]]["DropGoals"]+$player["DropGoals"];
						$listPlayers[$player["UserID"]]["FirstName"]=$profile["FirstName"];
						$listPlayers[$player["UserID"]]["LastName"]=$profile["LastName"];
						
						$points = ($player["tries"]*$Tourn["Tries"])+ ($player["Conversions"]*$Tourn["Conversion"]) +($player["Penalties"]*$Tourn["Penalties"]) + ($s["DropGoals"]*$Tourn["Dropgoal"]) ;
						
						$listPlayers[$player["UserID"]]["Points"]=$listPlayers[$player["UserID"]]["Points"]+$points;
                                }
                                
        }
        }
        
        $this->array_sort_by_column($listArray, 'PD',SORT_DESC);
        
        $this->view->assign("Logs",$listArray);
        
         $this->view->assign("Round",$round);
        
        
			$Points = $listPlayers;
			$tries = $listPlayers;
			$Conversions = $listPlayers;
			$Penalties = $listPlayers;
			
			$this->array_sort_by_column($Points, 'Points',SORT_DESC);
			
			$this->view->assign("Points",$Points);
			
			$this->array_sort_by_column($tries, 'tries',SORT_DESC);
			
			$this->view->assign("tries",$tries);
			
			$this->array_sort_by_column($Conversions, 'Conversions',SORT_DESC);
			
			$this->view->assign("Conversions",$Conversions);
			
			$this->array_sort_by_column($Penalties, 'Penalties',SORT_DESC);
			
			$this->view->assign("Penalties",$Penalties);
        
        
        
       
        //StartDate
        //EndDate
        
    } 
    
    public function tournlogroundAction()
            {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
        $id = $request->getParam("tid");
        $round = $request->getParam("round");
         $this->view->assign("Round",$round);
        $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)
                { 
                    $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){
                    foreach($Officials as $Official){
                    if(@$Official["TA"]==1){
                            $profileDB = new Model_Profile;
                            $Profile = $profileDB->getPerson($Official["UserID"]);
                            $Director = "<a href='/mambers/profile/id/".$Profile["UserID"]."' target='_black'>".  getFullName($Profile)."</a>";
                    }
                    }
                }
                                
                
                
				if($Tournament["Structure"] =="Pool"){
					$FixtureDB->setSquadByScorePool($id,$Tournament);
					$FixtureDB->setSquadByScore($id);
					
				}else{
					$FixtureDB->setSquadByScore($id);
				}
				
						
		$this->view->assign("fixtures",$data);
		
	
		
       $squadsDB = new Model_Squad;
		$Members = $squadsDB->getSquadByTaurnament($id);
		 $this->view->assign("Members",$Members->toArray());
			 
			 
		
		
		 $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"];
                                $playersList = json_decode($Squad["Players"],TRUE);
                                if(count($playersList)>0)
                                {
                                foreach($playersList as $item){
                                    $IjuryDB = new Model_PlayerInjury;
                                    $PlayerFind = $IjuryDB->getByPos($item["ID"],$item["Position"],$Squad["SquadType"]);
                                    if(isset($PlayerFind["UserID"])){
                                        $Injuredplayers[$item["ID"]]=  $PlayerFind->toArray();
                                        $Injuredplayers[$item["ID"]]["SquadName"]=  $Squad["ShortName"];
                                         $Injuredplayers[$item["ID"]]["Jersey"]=  $item["Jersey"];
                                    }
                                   }
				}
                                }
				$i++;
				
				
				
				
				
				$players = json_decode($Squad["Players"],true);
				$totalP = ($totalP + count($players));
				
				$ProfileDB = new Model_Profile;
                                if(count($players)>0){
				foreach ($players as $player) 
                                {
								
                                    $profile = $ProfileDB->getEthnicity($player["ID"]);
                                    $ethinicity = (!empty($profile['Ethnicity']) ? $profile['Ethnicity'] : "");
					
                                    if($ethinicity == "Black" || $ethinicity == "African/Black" || $ethinicity == "African")
                                    {
                                        $black++;
                                    }
                                    else if($ethinicity == "White")
                                    {
                                        $white++;
                                    }
                                    else if($ethinicity == "Indian")
                                    {
                                        $indian++;
                                    }
                                    else if($ethinicity == "Coloured")
                                    {
                                        $coloured++;
                                    }else{
                                        $undefied++;
                                    }
					
				}
                                }
				
			}

			
				$this->array_sort_by_column($listArray, 'PD',SORT_DESC);
			
		
			$this->view->assign("Logs",$listArray);
                        
			
					
					
					
					
					
		$FixtureDB = new Model_Fixture;
		if($Tournament["Structure"]==2){
			$MatchReport = $FixtureDB->getTournReportPool($id);
                }else{
                    $MatchReport = $FixtureDB->getTournReport($id);
                }
		$Players = array();
                
                
                
		foreach ($MatchReport as $MatchReport) {
			$Score = json_decode($MatchReport["Score"],true);
                       
			if(count($Score)>0){
				
			
			foreach ($Score as $s) {
								
				$profile = $ProfileDB->getProfileNoPos($s["UserID"]);
						
						$squad = new Model_Squad;
						$squadDet = $squad->fetchRow("SID ='".$MatchReport["SID"]."'");
						
						$Players[$s["UserID"]]["UserID"]=$s["UserID"];
						$Players[$s["UserID"]]["SID"]=$MatchReport["SID"];
						$Players[$s["UserID"]]["SquadName"]=$squadDet["SquadName"];
						$Players[$s["UserID"]]["tries"]= @$Players[$s["UserID"]]["tries"]+$s["tries"];
						$Players[$s["UserID"]]["Conversions"]=@$Players[$s["UserID"]]["Conversions"]+$s["Conversions"];
						$Players[$s["UserID"]]["Penalties"]=@$Players[$s["UserID"]]["Penalties"]+$s["Penalties"];
						$Players[$s["UserID"]]["DropGoals"]=@$Players[$s["UserID"]]["DropGoals"]+$s["DropGoals"];
						$Players[$s["UserID"]]["FirstName"]=$profile["FirstName"];
						$Players[$s["UserID"]]["LastName"]=$profile["LastName"];
						
						$points = ($s["tries"]*$MatchReport["Tries"])+ ($s["Conversions"]*$MatchReport["Conversion"]) +($s["Penalties"]*$MatchReport["Penalties"]) + ($s["DropGoals"]*$MatchReport["Dropgoal"]) ;
						
						$Players[$s["UserID"]]["Points"]=@$Players[$s["UserID"]]["Points"]+$points;
			}
			}
			
		}
		
                  $Points = $Players;
			$tries = $Players;
			$Conversions = $Players;
			$Penalties = $Players;
			
			$this->array_sort_by_column($Points, 'Points',SORT_DESC);
			
			$this->view->assign("Points",$Points);
			
			$this->array_sort_by_column($tries, 'tries',SORT_DESC);
			
			$this->view->assign("tries",$tries);
			
			$this->array_sort_by_column($Conversions, 'Conversions',SORT_DESC);
			
			$this->view->assign("Conversions",$Conversions);
			
			$this->array_sort_by_column($Penalties, 'Penalties',SORT_DESC);
			
			$this->view->assign("Penalties",$Penalties);  
                        
                         $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);
                         
    }
function removeChar($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
    
 function playerutilityAction()
{
    $this->_helper->layout->disableLayout();
		$FixtureTbl = new Model_Fixture;
		$SquadsTbl = new Model_Squad;
		$MatchReportTbl = new Model_MatchReport;
                $profileDB = new Model_Profile;
                
                
                
		$request = $this->getRequest();  
		$fid =$request->getParam("fid");
                $sid =$request->getParam("sid");
                
                 
                 //GET FIXTURE
                $Fixture = $FixtureTbl->getFixture($fid);
                
                
                $FixtureStat = $FixtureTbl->getUtility($fid,$sid);
                 echo "<pre>";
                print_r($FixtureStat->toArray());
               
                exit;
                
                
                
                $this->view->assign("fixture",$Fixture);
                $squad = $SquadsTbl->getSquadComp($sid);
		$this->view->assign("squad",$squad);
                
                $HomeTeamScore = $MatchReportTbl->getScore($fid, $sid);
                
                
                $HomeTeamScoreLog = array();
                if(count($HomeTeamScore)>0){
                   $HomeTeamScoreLog =@$HomeTeamScore->toArray();
                }
                
                
                
                $homeTeam =array();
                if($sid==$Fixture["HomeTeam"]){
                $listHomeTeam =  json_decode($Fixture["TeamH"],true);
                }
                if($sid==$Fixture["AwayTeam"]){
                $listHomeTeam =  json_decode($Fixture["TeamA"],true);
                }
                
                if(count($listHomeTeam)>0){
                    $PlayersScore = json_decode($HomeTeamScore["Score"],true) ;
                    $PlayersSubstitutions = json_decode($HomeTeamScore["Substitutions"],true) ;
                    echo "<pre>";
               print_r($HomeTeamScore);
               
                    foreach($listHomeTeam as $player){
                        $getProfile = $profileDB->GetPlayersByPositions($player['ID'], $player['Pos']);
                        $Cap ="";
                        if($player["Cap"]==1){
                        $Cap ="(C)";
                        }
                        $Vice ="";
                        if($player["Vice"]==1){
                        $Vice ="(V)";
                        }
                        $IMG = "";
                        
                        $SquadPlayerPhoto = new Model_Squadplayerprofile;
                        
                        
                        $homeTeam[$player['Pos']]["Subs"] = $PlayersSubstitutions;
                        $homeTeam[$player['Pos']]["Cap"] = $Cap;
                        $homeTeam[$player['Pos']]["Vice"] = $Vice;
                        $homeTeam[$player['Pos']]["CapNo"] = $player["Cap"];
                        $homeTeam[$player['Pos']]["ViceNo"] = $player["Vice"];
                        $homeTeam[$player['Pos']]["UserID"] = $getProfile["UserID"];
                        //$homeTeam[$player['Pos']]["Avatar"] = $IMG;
                        $homeTeam[$player['Pos']]["INIT"] = $this->removeChar($getProfile["FirstName"])[0];
			$homeTeam[$player['Pos']]["FirstName"] = $getProfile["FirstName"];
			$homeTeam[$player['Pos']]["LastName"] = $getProfile["LastName"];
                        $homeTeam[$player['Pos']]["PostionNo"] = $player["Pos"];
                        $homeTeam[$player['Pos']]["Postion"] = (!empty($getProfile["POS"]))? $getProfile["POS"] : "POS: not assigned" ;
                        $homeTeam[$player['Pos']]["JerseyNumber"] = (!empty($player["Jersey"]))? $player["Jersey"] : 0;
			$homeTeam[$player['Pos']]["PID"] = $getProfile["PID"];	
                        $homeTeam[$player['Pos']]["tries"] = ($PlayersScore[$getProfile["UserID"]]["tries"]>0)? $PlayersScore[$getProfile["UserID"]]["tries"] : 0; 
                        $homeTeam[$player['Pos']]["Conversions"] = ($PlayersScore[$getProfile["UserID"]]["Conversions"]>0)? $PlayersScore[$getProfile["UserID"]]["Conversions"] : 0;
                        $homeTeam[$player['Pos']]["Penalties"] = ($PlayersScore[$getProfile["UserID"]]["Penalties"]>0)? $PlayersScore[$getProfile["UserID"]]["Penalties"] : 0;
                        $homeTeam[$player['Pos']]["DropGoals"] = ($PlayersScore[$getProfile["UserID"]]["DropGoals"]>0)? $PlayersScore[$getProfile["UserID"]]["DropGoals"] : 0;
                                               
                    }
                }
              echo "<pre>";
               print_r($homeTeam);
                exit;
                $LINEUP = array("HomeTeam"=>$homeTeam);
                $this->view->assign("Players",$LINEUP);
               
             
}
 
    function statsAction(){
        $this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
    }
    
    
    public function tournlogsddAction()
    {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
        $id = $request->getParam("tid");
        
        $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)
                { 
                    $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){
                    foreach($Officials as $Official){
                    if(@$Official["TA"]==1){
                            $profileDB = new Model_Profile;
                            $Profile = $profileDB->getPerson($Official["UserID"]);
                            $Director = "<a href='/mambers/profile/id/".$Profile["UserID"]."' target='_black'>".  getFullName($Profile)."</a>";
                    }
                    }
                }
                                
                
                
				if($Tournament["Structure"] =="Pool"){
					$FixtureDB->setSquadByScorePool($id,$Tournament);
					$FixtureDB->setSquadByScore($id);
					
				}else{
					$FixtureDB->setSquadByScore($id);
				}
				
						
		$this->view->assign("fixtures",$data);
		
	
		
       $squadsDB = new Model_Squad;
		$Members = $squadsDB->getSquadByTaurnament($id);
		 $this->view->assign("Members",$Members->toArray());
			 
			 
		
		
		 $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"];
                                $playersList = json_decode($Squad["Players"],TRUE);
                                if(count($playersList)>0)
                                {
                                foreach($playersList as $item){
                                    $IjuryDB = new Model_PlayerInjury;
                                    $PlayerFind = $IjuryDB->getByPos($item["ID"],$item["Position"],$Squad["SquadType"]);
                                    if(isset($PlayerFind["UserID"])){
                                        $Injuredplayers[$item["ID"]]=  $PlayerFind->toArray();
                                        $Injuredplayers[$item["ID"]]["SquadName"]=  $Squad["ShortName"];
                                         $Injuredplayers[$item["ID"]]["Jersey"]=  $item["Jersey"];
                                    }
                                   }
				}
                                }
				$i++;
				
				
				
				
				
				$players = json_decode($Squad["Players"],true);
				$totalP = ($totalP + count($players));
				
				$ProfileDB = new Model_Profile;
                                if(count($players)>0){
				foreach ($players as $player) 
                                {
								
                                    $profile = $ProfileDB->getEthnicity($player["ID"]);
                                    $ethinicity = (!empty($profile['Ethnicity']) ? $profile['Ethnicity'] : "");
					
                                    if($ethinicity == "Black" || $ethinicity == "African/Black" || $ethinicity == "African")
                                    {
                                        $black++;
                                    }
                                    else if($ethinicity == "White")
                                    {
                                        $white++;
                                    }
                                    else if($ethinicity == "Indian")
                                    {
                                        $indian++;
                                    }
                                    else if($ethinicity == "Coloured")
                                    {
                                        $coloured++;
                                    }else{
                                        $undefied++;
                                    }
					
				}
                                }
				
			}

			
				$this->array_sort_by_column($listArray, 'PD',SORT_DESC);
			
		
			$this->view->assign("Logs",$listArray);
                       
			
					// $this->logs($id);
					
					
					
					
		$FixtureDB = new Model_Fixture;
		if($Tournament["Structure"]==2){
			$MatchReport = $FixtureDB->getTournReportPool($id);
                }else{
                    $MatchReport = $FixtureDB->getTournReport($id);
                }
		$Players = array();
                
                
                
		foreach ($MatchReport as $MatchReport) {
			$Score = json_decode($MatchReport["Score"],true);
                       
			if(count($Score)>0){
				
			
			foreach ($Score as $s) {
								
				$profile = $ProfileDB->getProfileNoPos($s["UserID"]);
						
						$squad = new Model_Squad;
						$squadDet = $squad->fetchRow("SID ='".$MatchReport["SID"]."'");
						
						$Players[$s["UserID"]]["UserID"]=$s["UserID"];
						$Players[$s["UserID"]]["SID"]=$MatchReport["SID"];
						$Players[$s["UserID"]]["SquadName"]=$squadDet["SquadName"];
						$Players[$s["UserID"]]["tries"]= @$Players[$s["UserID"]]["tries"]+$s["tries"];
						$Players[$s["UserID"]]["Conversions"]=@$Players[$s["UserID"]]["Conversions"]+$s["Conversions"];
						$Players[$s["UserID"]]["Penalties"]=@$Players[$s["UserID"]]["Penalties"]+$s["Penalties"];
						$Players[$s["UserID"]]["DropGoals"]=@$Players[$s["UserID"]]["DropGoals"]+$s["DropGoals"];
						$Players[$s["UserID"]]["FirstName"]=$profile["FirstName"];
						$Players[$s["UserID"]]["LastName"]=$profile["LastName"];
						
						$points = ($s["tries"]*$MatchReport["Tries"])+ ($s["Conversions"]*$MatchReport["Conversion"]) +($s["Penalties"]*$MatchReport["Penalties"]) + ($s["DropGoals"]*$MatchReport["Dropgoal"]) ;
						
						$Players[$s["UserID"]]["Points"]=@$Players[$s["UserID"]]["Points"]+$points;
			}
			}
			
		}
		
                  $Points = $Players;
			$tries = $Players;
			$Conversions = $Players;
			$Penalties = $Players;
			
			$this->array_sort_by_column($Points, 'Points',SORT_DESC);
			
			$this->view->assign("Points",$Points);
			
			$this->array_sort_by_column($tries, 'tries',SORT_DESC);
			
			$this->view->assign("tries",$tries);
			
			$this->array_sort_by_column($Conversions, 'Conversions',SORT_DESC);
			
			$this->view->assign("Conversions",$Conversions);
			
			$this->array_sort_by_column($Penalties, 'Penalties',SORT_DESC);
			
			$this->view->assign("Penalties",$Penalties);  
                        
                         $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 tournlogsteAction()
    {
    	$this->_helper->layout->disableLayout();
	}
   public function tournlogsAction()
    {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
        $id = $request->getParam("tid");
        
        $TournDB = new Model_Tournament;
		$ProfileDB = new Model_Profile;
        $Tournament = $TournDB->fetchRow("TID ='".$id."'");
                
        $this->view->assign("data",$Tournament);
		
	
				$FixtureDB = new Model_Fixture;
				$data =$FixtureDB->getFixtures($id)->toArray();
				
			
				
						
		$this->view->assign("fixtures",$data);
		
	
		
		
		
		 $this->view->assign("Tournnament",$Tournament->toArray());
		 $FixtureDB = new Model_Fixture;
		$logsDB = new Model_TournamentLogs;
		$SerieslogsDB = new Model_SeriesLogs;
		
					
		$FixtureDB = new Model_Fixture;
		if($Tournament["Structure"]==2){
			$MatchReport = $FixtureDB->getTournReportPool($id);
                }else{
                    $MatchReport = $FixtureDB->getTournReport($id);
                }
		$Players = array();
		
                
		foreach ($MatchReport as $MatchReport) {
			$Score = json_decode($MatchReport["Score"],true);
                       
			if(count($Score)>0){
				
			
			foreach ($Score as $s) {
								
				$profile = $ProfileDB->getUserProfile($s["UserID"]);
						
						$squad = new Model_Squad;
						$squadDet = $squad->fetchRow("SID ='".$MatchReport["SID"]."'");
						
						$Players[$s["UserID"]]["UserID"]=$s["UserID"];
						$Players[$s["UserID"]]["SID"]=$MatchReport["SID"];
						$Players[$s["UserID"]]["SquadName"]=$squadDet["SquadName"];
						$Players[$s["UserID"]]["tries"]= @$Players[$s["UserID"]]["tries"]+$s["tries"];
						$Players[$s["UserID"]]["Conversions"]=@$Players[$s["UserID"]]["Conversions"]+$s["Conversions"];
						$Players[$s["UserID"]]["Penalties"]=@$Players[$s["UserID"]]["Penalties"]+$s["Penalties"];
						$Players[$s["UserID"]]["DropGoals"]=@$Players[$s["UserID"]]["DropGoals"]+$s["DropGoals"];
						$Players[$s["UserID"]]["FirstName"]=$profile["FirstName"];
						$Players[$s["UserID"]]["LastName"]=$profile["LastName"];
						$Players[$s["UserID"]]["FullName"]=$profile["FullName"];
						
						$points = ($s["tries"]*$MatchReport["Tries"])+ ($s["Conversions"]*$MatchReport["Conversion"]) +($s["Penalties"]*$MatchReport["Penalties"]) + ($s["DropGoals"]*$MatchReport["Dropgoal"]) ;
						
						$Players[$s["UserID"]]["Points"]=@$Players[$s["UserID"]]["Points"]+$points;
			}
			}
			
		}
		
                  $Points = $Players;
			$tries = $Players;
			$Conversions = $Players;
			$Penalties = $Players;
			
			$this->array_sort_by_column($Points, 'Points',SORT_DESC);
			
			$this->view->assign("Points",$Points);
			
			$this->array_sort_by_column($tries, 'tries',SORT_DESC);
			
			$this->view->assign("tries",$tries);
			
			$this->array_sort_by_column($Conversions, 'Conversions',SORT_DESC);
			
			$this->view->assign("Conversions",$Conversions);
			
			$this->array_sort_by_column($Penalties, 'Penalties',SORT_DESC);
			
			$this->view->assign("Penalties",$Penalties);  
                        
                         $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);
        
               $this->logs($Tournament);   
	            
    }

public function logs($Tournament)
    {
    	$LogsDB = new Model_Logs;
		$Logs = $LogsDB->getAllLogs($Tournament);
		$ListLogs = array();
		if(count($Logs)>0){
			$Logs = $Logs->toArray();
			foreach($Logs as $log){
				
					$Pools = json_decode($log["Pools"],true);
					$ListLogs[$log["Pool"]]["PoolName"]=$Pools[$log["Pool"]];
				
					$ListLogs[$log["Pool"]]["teams"][]=$log;
				
				
			}
		}
		
    	$this->view->assign("Logs",$ListLogs);
    	
	}
public function matchreportAction()
    {
    	$this->_helper->layout->disableLayout();
			
			$request = $this->getRequest();
                        $id = $request->getParam("id");
                         $test = $request->getParam("test");
				$dbSquads = new Model_Squad;
				$FixtureDB = new Model_Fixture;
				$comms = new Model_MatchEvents;
				$fixture =$FixtureDB->getFixture($id);
                                $tourn = new Model_Tournament;
                                $Tournamnet = $tourn->getTourny($fixture["TID"]);
                                
                               $this->view->assign("Tourn",$Tournamnet);
							   
					
						   
							   
				$this->view->assign("data",$fixture);
                                
                                $TeamH = json_decode($fixture["TeamH"],true);
                                $TeamA = json_decode($fixture["TeamA"],true);
                                $this->array_sort_by_column($TeamH, "Pos");
                                $this->array_sort_by_column($TeamA, "Pos");
                                $this->view->assign("TeamH",$TeamH);
                                $this->view->assign("TeamA",$TeamA);
                                
				$mactDB = new Model_MatchReport;
				$report1 = $mactDB->fetchRow("FID ='".$id."' AND SID ='".$fixture["HomeTeam"]."'");
				$report2 = $mactDB->fetchRow("FID ='".$id."' AND SID ='".$fixture["AwayTeam"]."'");
				
				
				$this->view->assign("TEAM1Report",$report1);
				$this->view->assign("TEAM2Report",$report2);
				$this->view->assign("TEAM1Tries",$report1["PenaltyTries"]+$report1["Total_tries"]);
				$this->view->assign("TEAM2Tries",$report2["PenaltyTries"]+$report2["Total_tries"]);
				
				
				
                                $CommentrydataData =	$this->commentrylist($id);
                        
                                $Commentrydata = array();
                                if(count($CommentrydataData)>0){
                                foreach($CommentrydataData as $data):
                                    $Commentrydata[$data["SecondHalf"]][]=$data;
                                endforeach;
                                
                                if(isset($Commentrydata[0])){
                                $this->array_sort_by_column($Commentrydata[0],"count");
                                }
                                if(isset($Commentrydata[1])){
                                $this->array_sort_by_column($Commentrydata[1],"count");
                                }
                                
				$this->view->assign("Commentry",$Commentrydata);
				}
				
		}
		private function commentrylist($fid){
		$COMENTSANDCITINGS_DB = new Model_ComentryAndCiting;
			$Data_Line = $COMENTSANDCITINGS_DB->getData($fid);
			if(!$Data_Line){
						$created = $COMENTSANDCITINGS_DB->insertData(array("FID"=>$fid,"DateCreated"=>date("Y-m-d H:i:s")));
						if($created){
							$Data_Line = $COMENTSANDCITINGS_DB->getData($fid);
						}
			}
			if(!empty($Data_Line["Commentry"])){
			$jsonData  = json_decode($Data_Line["Commentry"],true);	
			$newData = array();
			$i =0;
			if(count($jsonData)>0){
				foreach ($jsonData as $comments) {
				$newData[$i]= $comments;
                                
                                $split = explode(":",$comments["times"]);
                                
                                $newData[$i]["min"] = $split[0];
				$newData[$i]["count"] =str_replace(":", "", $comments["times"]);
                                
                                
				$i++;
			}
			}
			
			
			$this->array_sort_by_column($newData,"count",SORT_DESC);
                        
			return $newData;
                        }else{
                            return array();
                        }
			
	}
		
	private function getPerformance($report1,$obj){
		
	//GET TRIES
							$Score1 =  json_decode($report1,true);
                                                       
							$tries1 = 0;
							if(count($Score1)>0){
								foreach($Score1 as $Sc){
						
								
                                                                    if($obj=="tries"){
                                                                        
                                                                        $tries1 = ($tries1 +($Sc[$obj] + $Sc["22Metertries"]) );
                                                                        
                                                                    }
								
								
								}
							}
							
							
							
							return ($tries1) ;
	
	
}	
		
	public function htmlAction()
    {
    	//http://footprintapp.net/scout/allplayers/unionid/undefined/scoutid/undefined/year/2015
    		
			//$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
				@$order = $request->getParam("dir");
				@$column= $request->getParam("column");
				switch ($column) {
					case 0:
						$column = 'U.FirstName';
						break;
					case 1:
						$column = 'O.un_name';
						break;
						case 2:
						$column = 'U.Email';
						break;
						case 3:
						$column = 'T.TypeName';
						break;
						case 4:
						$column = 'U.Mobile';
						break;
						case 5:
						$column = 'C.LastLogin';
						break;
						default:
						$column = 'U.FirstName';
						break;
				}
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				
				$dbUsers = new Model_Profile;
		 		$list = $dbUsers->getAllMembers($order,$column,$searchSQL,$unionFilter);
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				$this->view->assign("Start",$request->getParam("start")+1);
				$this->view->assign("Data",$paginator);
				$this->view->assign("Total",count($list));
		
			
		}
                
               
public function printAction()
    {
    		
			//$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
		$order = $_GET["order"][0]["dir"];
		$column = $_GET["order"][0]["column"];
		switch ($column) {
			case 0 :
				$column = 'FirstName';
				break;
			case 1 :
				$column = 'FirstName';
				break;
			case 2 :
				$column = 'un_name';

				break;
			case 3 :
				$column = 'Email';

				break;
			case 4 :
				$column = 'TypeName';

				break;
			case 5 :
				$column = 'Mobile';
				break;
			default :
				$column = 'FirstName';
				break;
		}
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				
				$type = $request -> getParam("type") ;
				$title = $request -> getParam("title") ;
				$role = $request -> getParam("role") ;
				$dbUsers = new Model_Profile;
				if($title ==2){
			$role=0;
		}
		 		$list = $dbUsers->listUsers($order, $column, $searchSQL, $unionFilter, $type, $title, $role);
				
				
				if($request->getParam("current")==1){
					
				
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				$this->view->assign("Data",$paginator);
				}else{
					$this->view->assign("Data",$list);
				}
				
					$this->view->assign("Start",$request->getParam("start")+1);
				
				$this->view->assign("Total",count($list));
				
				
				if($unionFilter>0){
					$UnionsDB = new Model_Unions;
					$getUnion = $UnionsDB->getName($unionFilter);
					$this->view->assign("Personnel","All Personnel for ".$getUnion["un_name"]);
				}else{
					$this->view->assign("Personnel","All Personnel");
				}
			



			
		}

public function pdfcommentryAction()
    {
    		
			//$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
			 $fid = $request->getParam("fid");
				
					$COMENTSANDCITINGS_DB = new Model_ComentryAndCiting;
				$comments = $COMENTSANDCITINGS_DB->fetchRow("FID ='".$fid."'");
			$commentsArray = json_decode($comments["Commentry"],true);
			if(count($commentsArray)>0){
				asort($commentsArray);
			}
		
			
			$this->view->assign('comms',$commentsArray);
			
		}
public function pdfcitingAction()
    {
    		
			//$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
			 $fid = $request->getParam("fid");
				
					$COMENTSANDCITINGS_DB = new Model_ComentryAndCiting;
				$comments = $COMENTSANDCITINGS_DB->fetchRow("FID ='".$fid."'");
			$commentsArray = json_decode($comments["Citing"],true);
			if(count($commentsArray)>0){
				asort($commentsArray);
			}
		
			
			$this->view->assign('comms',$commentsArray);
			
		}

public function  printscoutAction(){
		$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
				@$order = $request->getParam("dir");
				@$column= $request->getParam("column");
				switch ($column) {
					case 0:
						$column = 'U.FirstName';
						break;
					case 1:
						$column = 'O.un_name';
						break;
						case 2:
						$column = 'U.Email';
						break;
						case 3:
						$column = 'T.TypeName';
						break;
						case 4:
						$column = 'U.Mobile';
						break;
						case 5:
						$column = 'C.LastLogin';
						break;
						default:
						$column = 'U.FirstName';
						break;
				}
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				@$scoutid = $request->getParam("scoutid");
			@$year = $request->getParam("year");
			if(!isset($year)){
			$year = date("Y");	
			}
				$dbUsers = new Model_Profile;
		 		$list = $dbUsers->getAllPlayers($order,$column,$searchSQL,$unionFilter,1,$scoutid,$year);
				
				
				
				if($request->getParam("current")==1){
					
				
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				$this->view->assign("Data",$paginator);
			
				}else{
					$this->view->assign("Data",$list);
				}
				
				$this->view->assign("Start",$request->getParam("start")+1);
				
				$this->view->assign("Total",count($list));
				
				
				if($unionFilter>0){
					$UnionsDB = new Model_Unions;
					$getUnion = $UnionsDB->getName($unionFilter);
					$this->view->assign("Personnel","All Players for ".$getUnion["un_name"]);
				}else{
					$this->view->assign("Personnel","All Players");
				}
			
}




public function playersAction()
    {
    		
			//$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
				@$order = $request->getParam("dir");
				@$column= $request->getParam("column");
				switch ($column) {
					case 0:
						$column = 'U.FirstName';
						break;
					case 1:
						$column = 'O.un_name';
						break;
						case 2:
						$column = 'U.Email';
						break;
						case 3:
						$column = 'T.TypeName';
						break;
						case 4:
						$column = 'U.Mobile';
						break;
						case 5:
						$column = 'C.LastLogin';
						break;
						default:
						$column = 'U.FirstName';
						break;
				}
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				
				$dbUsers = new Model_Profile;
		 		$list = $dbUsers->getAllPlayers($order,$column,$searchSQL,$unionFilter);
				
				
				if($request->getParam("current")==1){
					
				
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				$this->view->assign("Data",$paginator);
				}else{
					$this->view->assign("Data",$list);
				}
				
					$this->view->assign("Start",$request->getParam("start")+1);
				
				$this->view->assign("Total",count($list));
				
				
				if($unionFilter>0){
					$UnionsDB = new Model_Unions;
					$getUnion = $UnionsDB->getName($unionFilter);
					$this->view->assign("Personnel","All Players for ".$getUnion["un_name"]);
				}else{
					$this->view->assign("Personnel","All Players");
				}
			



			
		}

public function excelAction()
    {
    		
			$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
		$order = $_GET["order"][0]["dir"];
		$column = $_GET["order"][0]["column"];
		switch ($column) {
			case 0 :
				$column = 'FirstName';
				break;
			case 1 :
				$column = 'FirstName';
				break;
			case 2 :
				$column = 'un_name';

				break;
			case 3 :
				$column = 'Email';

				break;
			case 4 :
				$column = 'TypeName';

				break;
			case 5 :
				$column = 'Mobile';
				break;
			default :
				$column = 'FirstName';
				break;
		}
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				
				$type = $request -> getParam("type") ;
				$title = $request -> getParam("title") ;
				$role = $request -> getParam("role") ;
				$dbUsers = new Model_Profile;
				if($title ==2){
			$role=0;
		}
		 		$list = $dbUsers->listUsers($order, $column, $searchSQL, $unionFilter, $type, $title, $role);
				
				
				if($request->getParam("current")==1){
					
				
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				
						$this->generateExcel($paginator);
				}else{
						$this->generateExcel($list);
				}
			
			
		}
		
		
		public function excelplayersAction()
    {
    		
			$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
				@$order = $request->getParam("dir");
				@$column= $request->getParam("column");
				switch ($column) {
					case 0:
						$column = 'U.FirstName';
						break;
					case 1:
						$column = 'O.un_name';
						break;
						case 2:
						$column = 'U.Email';
						break;
						case 3:
						$column = 'T.TypeName';
						break;
						case 4:
						$column = 'U.Mobile';
						break;
						case 5:
						$column = 'C.LastLogin';
						break;
						default:
						$column = 'U.FirstName';
						break;
				}
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				
				$dbUsers = new Model_Profile;
		 		$list = $dbUsers->getAllPlayers($order,$column,$searchSQL,$unionFilter);
				
				
				if($request->getParam("current")==1){
					
				
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				
						$this->generateExcel($paginator);
				}else{
						$this->generateExcel($list);
				}
			
			
		}
		
		private function generateExcel($list){
			
			if (PHP_SAPI == 'cli')
					die('This example should only be run from a Web Browser');
				
				/** Include PHPExcel */
				require_once  'Classes/PHPExcel.php';
				
				
				// Create new PHPExcel object
				$objPHPExcel = new PHPExcel();
				
				// Set document properties
				$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
											 ->setLastModifiedBy("Maarten Balliauw")
											 ->setTitle("Office 2007 XLSX Test Document")
											 ->setSubject("Office 2007 XLSX Test Document")
											 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
											 ->setKeywords("office 2007 openxml php")
											 ->setCategory("Test result file");
				
				
				// Add some data
				$objPHPExcel->setActiveSheetIndex(0)
				            ->setCellValue('A1', '#')
				            ->setCellValue('B1', 'Full Name')
				            ->setCellValue('C1', 'Organisation')
				            ->setCellValue('D1', 'E-mail')
										->setCellValue('E1', 'Job Title')
										->setCellValue('F1', 'Mobile')
										;
				# 		 	 	 	 	Last Login
				// Miscellaneous glyphs, UTF-8
				$n =2;
				foreach ($list as $value) {
					$objPHPExcel->setActiveSheetIndex(0)
				            ->setCellValue('A'.$n, $n-1)
				            ->setCellValue('B'.$n, $value["FirstName"].' '.$value["LastName"])
				            ->setCellValue('C'.$n, $value["un_name"])
				            ->setCellValue('D'.$n, $value["Email"])
										->setCellValue('E'.$n, $value["TypeName"])
										->setCellValue('F'.$n, $value["Mobile"])
										;
										$n++;
				}
				
				
				// Rename worksheet
				$objPHPExcel->getActiveSheet()->setTitle('Simple');
				
				
				// Set active sheet index to the first sheet, so Excel opens this as the first sheet
				$objPHPExcel->setActiveSheetIndex(0);
				
				
				// Redirect output to a client’s web browser (Excel5)
				header('Content-Type: application/vnd.ms-excel');
				header('Content-Disposition: attachment;filename="01simple.xls"');
				header('Cache-Control: max-age=0');
				// If you're serving to IE 9, then the following may be needed
				header('Cache-Control: max-age=1');
				
				// If you're serving to IE over SSL, then the following may be needed
				header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
				header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
				header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
				header ('Pragma: public'); // HTTP/1.0
				
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//				$objWriter->save('php://output');
				exit;
		}
 public function profileAction()
       {
                        //$this->_helper->viewRenderer->setNoRender();
                        $this->_helper->layout->disableLayout();
                        $request = $this->getRequest();
			$id = $request->getParam("id");
			$ProfileDB = new Model_Profile;
                        $player = $ProfileDB->getRow($id);
                        $this->view->assign('Profile',$player);
                        
                        
                
       }      
                
 public function passportAction()
       {
     
            //$this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();
            $request = $this->getRequest();
			$id = $request->getParam("id");
			
                        $sid = $request->getParam("sid");
                        $SquadsTbl = new Model_Squad;      
                        $squad = $SquadsTbl->getSquad($sid);
                        $listPlayers = json_decode($squad["Players"],true);
                        
			$ProfileDB = new Model_Profile;
                        $player = $ProfileDB->GetPlayersByPositionsImage($id, $listPlayers[$id]["Position"]);
                        $this->view->assign('Profile',$player);
                        
                        $PROFILEDOC   =0;  // 1  4                     
                  $IDDOC   =0; // 1 1
                  $INDEMNITY   =0; // 5  16
                  //Question when uploading a file do we link it to the squad
                                        $db = new Model_Documents;
             $documents = $db->getForPlayer($id);
             if(count($documents)>0){
                 foreach($documents as $document){
                     if($document["Category"] ==1 && $document["FileType"] == 4){
                         $PROFILEDOC   =1; 
                     }
                     if($document["Category"] ==1 && $document["FileType"] == 1){
                         $IDDOC   =1; 
                     }
                     
                     if($document["Category"] ==5 && $document["FileType"] == 16){
                         $INDEMNITY   =1; 
                     }
                      
                 }
             }
             
                $this->view->assign('Squad',$squad);
             $this->view->assign('DOC',array("PROFILEDOC"=>$PROFILEDOC,"IDDOC"=>$IDDOC,"INDEMNITY"=>$INDEMNITY,));
       }
                
                
        public function squadsheetAction()
       {
            //$this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout(); 
            $request = $this->getRequest();
			$id = $request->getParam("id");
			
			 $SquadDB = new Model_Squad;    
			 if($id>0){
			 	echo "Test";
			 	 $Squad = $SquadDB->getSquadview($id);
				
			
			
			$ProfileDB = new Model_Profile;
                        
                       
                        $name = $Squad['SquadName'];
						
						
						//GET ALL POSITIONS
						
						$PositionsTbl = new Model_Positions;
							$Positions = $PositionsTbl->getPos($Squad["RugbyCode"]);
							$PositionList = array();
							if(count($Positions)>0){
								foreach($Positions as $Position){
									$PositionList[$Position["PID"]]= $Position;
								}
							}
					          
							  
							$UserTypeTbl = new Model_UserType;
							$UserTypes = $UserTypeTbl->fetchAll();
							$TypeList = array();
							if(count($UserTypes)>0){
								foreach($UserTypes as $Type){
									$TypeList[$Type["TypeID"]]= $Type;
								}
							} 
						
						
                        
                        $coaches = json_decode($Squad['Coaches'],true);
                        $players = json_decode($Squad['Players'],true);
                       
						$listCoaches =array();
						$listPlayers =array();
						$listIDs = array();
						
						
						if(count($players)>0){
							foreach($players as $player){
                            	
								$listIDs[$player["ID"]] =$player["ID"];
								$listPlayers[$player["ID"]]=$player;
                       		 }
						}
					
                        $teamMan = 0;
						if(count($coaches)>0){
							
						
                        foreach($coaches as $Caoche){
                            if($Caoche["Position"]==42 ){
                                $teamMan =$Caoche["ID"];
                            }
							$listIDs[$Caoche["ID"]] =$Caoche["ID"];
							$listCoaches[$Caoche["ID"]]=$Caoche;
                        }
                        if($teamMan==0){
                            foreach($coaches as $Caoche){
                            if($Caoche["Position"]==200){
                                $teamMan =$Caoche["ID"];
                            }
                        }
                        }
						}
						
						
						
                        if($teamMan==0){
                         $teamMan =$Squad['TeamManager'];
                        }
                        
						$listSquad = array();
						$listPersonnal = array();
						
                        $Profiles = $ProfileDB->getFullNoImagesProfilesByIDs($listIDs);
						if(count($Profiles)>0){
							 foreach($Profiles->toArray() as $Profile){
							 	//if players
							 	if(isset($listPlayers[$Profile["UserID"]])){
							 		
							 		$listSquad[$Profile["UserID"]]= $Profile;
									$position = $listPlayers[$Profile["UserID"]]["Position"];
									$listSquad[$Profile["UserID"]]["Position"] = $position;
									$listSquad[$Profile["UserID"]]["Rank"] = $listPlayers[$Profile["UserID"]]["Rank"];
									$listSquad[$Profile["UserID"]]["Jersey"] = $listPlayers[$Profile["UserID"]]["Jersey"];
									$listSquad[$Profile["UserID"]]["Captain"] = $listPlayers[$Profile["UserID"]]["Captain"];
									$listSquad[$Profile["UserID"]]["Vice"] = $listPlayers[$Profile["UserID"]]["Vice"];
									$listSquad[$Profile["UserID"]]["positionName"] = $PositionList[$position]["Position"];
									
									
									
									$un_name = $Profile["un_name"];
                            if($player["un_type"]>3 && $Profile["un_type"]!=11){
                                $unionDB = new Model_Unions;
                                $union=$unionDB->fetchRow("un_id ='".$Profile["parentid"]."'");
                                $un_name = $union["un_name"];
                            }
                            $School = $Profile["SecondarySchool"];
                            if($Squad['AgeGroup']<14 && $Squad['AgeGroup']>0){
                                if($Profile["country"]==239 && $Squad['AgeGroup']==13){
                                $School = $Profile["SecondarySchool"];
                                }else{
                                    $School = $Profile["PrimarySchool"];
                                }
                            }else if($Squad['AgeGroup']>13 && $Squad['AgeGroup']<19){
                                $School = $Profile["SecondarySchool"];
                            }
									
								$listSquad[$Profile["UserID"]]["un_name"]  = 	$un_name;
								$listSquad[$Profile["UserID"]]["School"]  = 	$School;
							 	}
							 	//if coaches
							 	
							 	if(isset($listCoaches[$Profile["UserID"]])){
							 		
							 		$listPersonnal[$Profile["UserID"]]= $Profile;
									$position = $listCoaches[$Profile["UserID"]]["Position"];
									$listPersonnal[$Profile["UserID"]]["Position"] = $listCoaches[$Profile["UserID"]]["Position"];
									$listPersonnal[$Profile["UserID"]]["positionName"] = $TypeList[$position]["TypeName"];
							 	}
							 }
						}
						//LOOP COACHES
						
						$this->array_sort_by_column($listSquad, 'Jersey');
						
					$age = ($Squad['AgeGroup']=="0" ? "Senior" : "Under ".$Squad['AgeGroup']);
			
			//$this->view->assign('manager',$managerProfile);
			$this->view->assign('name',$name);
            $this->view->assign('squad',$Squad);
			$this->view->assign('age',$age);
			$this->view->assign('players',$listSquad);
			$this->view->assign('coaches',$listPersonnal);  
            $this->view->assign('AgeGroup',$Squad['AgeGroup']);
                        
                        }       
       }        
        public function squadsheettestAction()
       {
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout(); 
            $request = $this->getRequest();
			$id = $request->getParam("id");
			
			$ProfileDB = new Model_Profile;
                        
                        $SquadDB = new Model_Squad;      
                        $Squad = $SquadDB->getSquad($id);
                        
                        
                        $coaches = json_decode($Squad['Coaches'],true);
                        
                        $teamMan = 0;
                        foreach($coaches as $Caoche){
                            if($Caoche["Position"]==42){
                                $teamMan =$Caoche["ID"];
                            }
                        }
                        if($teamMan==0){
                            foreach($coaches as $Caoche){
                            if($Caoche["Position"]==200){
                                $teamMan =$Caoche["ID"];
                            }
                        }
                        }
                        if($teamMan==0){
                         $teamMan =$Squad['TeamManager'];
                        }
                        
			$name = $Squad['SquadName'];
                        $managerProfile = $ProfileDB->getPlayer($teamMan);
			
                        
			$age = ($Squad['AgeGroup']=="0" ? "Senior" : "Under ".$Squad['AgeGroup']);
			$players = json_decode($Squad['Players'],true);
			$this->array_sort_by_column($players, 'Jersey');
                        $play = array();
			if(!empty($players)):
			
			foreach ($players as $p)
                          {
                            if($p['ID']>0){
                            $player = $ProfileDB->GetPlayersByPositions($p['ID'], $p['Position'],$Squad["RugbyCode"]);
                            $un_name = $player["un_name"];
                            if($player["un_type"]>3 && $player["un_type"]!=11){
                                $unionDB = new Model_Unions;
                                $union=$unionDB->fetchRow("un_id ='".$player["parentid"]."'");
                                $un_name = $union["un_name"];
                            }
                            $School = $player["SecondarySchool"];
                            if($Squad['AgeGroup']<14 && $Squad['AgeGroup']>0){
                                if($Squad["Country"]==239 && $Squad['AgeGroup']==13){
                                $School = $player["SecondarySchool"];
                                }else{
                                    $School = $player["PrimarySchool"];
                                }
                            }else if($Squad['AgeGroup']>13 && $Squad['AgeGroup']<19){
                                $School = $player["SecondarySchool"];
                            }
                            
               if($Squad["SquadType"]>2  ){
                   $p['Jersey'] =($p['Rank']>0)?$p['Rank']:0;
               }
               		if($player){				
                $play[] = array("Age"=>$this->age($player["DateOfBirth"]),"Org"=>$un_name,
                    "Captain"=>$p['Captain'],"Vice"=>$p['Vice'],"School"=>$School,
                    "height"=>$player["height"],"height"=>$player["height"],"weight"=>$player["weight"],
                    "name"=>$player['FirstName'],"SANumber"=>$player['SARugbyPlayerNo'],
                    "surname"=>$player['LastName'],"Jersey"=>$p['Jersey'],
                    "POS"=>$p['Position'],
                    "position"=>(!empty($player["POS"]))? $player["POS"] : "" ,
                    "ethnicity"=>$player["Ethnicity"],"dob"=>$player["DateOfBirth"]);
                        }
                          }
                        }
			endif;
                        
            $coch = array();
	if(!empty($coaches)):
			foreach ($coaches as $coach)
            {
            	
                $Profile = $ProfileDB->GetPesonnalByPositions($coach['ID'],$coach["Position"]);
                if($Profile){
                $coch[] = array("boksmart"=>$Profile['boksmart'],"name"=>$Profile['FirstName'],"SANumber"=>$Profile['SARugbyPlayerNo'],"surname"=>$Profile['LastName']
                        ,"position"=>$Profile["POS"],"dob"=>$Profile["DateOfBirth"],"email"=>$Profile["Email"]);
                }
                
                }
			endif;
			
                        $this->array_sort_by_column($play, 'Jersey');
			$this->view->assign('manager',$managerProfile);
			$this->view->assign('name',$name);
                        $this->view->assign('squad',$Squad);
			$this->view->assign('age',$age);
			$this->view->assign('players',$play);
			$this->view->assign('coaches',$coch);  
                        $this->view->assign('AgeGroup',$Squad['AgeGroup']);
                        echo "<pre>";
                        print_r($players);
                        print_r($play);

                        
       }
        function age($birthday)
	{
	     $DateOfBirth = date("Y",strtotime($birthday));
        $Month = date("m",strtotime($birthday));
        $day = date("d",strtotime($birthday));
        if($Month>date("m",date("Y-m-d"))){
            $year_diff =(date("Y")-$DateOfBirth);
        }else if($Month==date("m",date("Y-m-d"))){
            if($day>=date("d",date("Y-m-d"))){
                $year_diff =(date("Y")-$DateOfBirth);
            }else{
                $year_diff =(date("Y")-$DateOfBirth);
                $year_diff = $year_diff-1;
            }
            
        }else{
            $year_diff =(date("Y")-$DateOfBirth);
                $year_diff = $year_diff-1;
        }
	     return $year_diff;

	}        
                
       public function squadsheetoldAction()
       {
            //$this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout(); 
            $request = $this->getRequest();
			$id = $request->getParam("id");
			
			$ProfileDB = new Model_Profile;	
			
                        $SquadDB = new Model_Squad;
			$Squad = $SquadDB->getSquad($id);
                        
                        $coaches = json_decode($Squad['Coaches'],true);
                        
                        $teamMan = 0;
                        foreach($coaches as $Caoche){
                            if($Caoche["Position"]==42){
                                $teamMan =$Caoche["ID"];
                            }
                        }
                        if($teamMan==0){
                            foreach($coaches as $Caoche){
                            if($Caoche["Position"]==200){
                                $teamMan =$Caoche["ID"];
                            }
                        }
                        }
                        if($teamMan==0){
                         $teamMan =$Squad['TeamManager'];
                        }
                        
			$name = $Squad['ShortName'];
			
			$managerProfile = $ProfileDB->getPlayer($teamMan);
			
			$age = ($Squad['AgeGroup']=="0" ? "Senior" : "Under ".$Squad['AgeGroup']);
			$players = json_decode($Squad['Players'],true);
			$this->array_sort_by_column($players, 'Jersey');
			
			
			$play = array();
			if(!empty($players)):
			
			foreach ($players as $p)
            {
                $player = $ProfileDB->getPlayer($p['ID']);
                $pos = new Model_Positions;
                $ppos = $pos->getRowCode($p['Position'],$Squad["RugbyCode"]);
								
                $play[] = array("name"=>$player['FirstName'],"SANumber"=>$player['SARugbyPlayerNo'],"surname"=>$player['LastName'],"Jersey"=>$p['Jersey'],"position"=>$ppos['Position'],"ethnicity"=>$player["Ethnicity"],"dob"=>$player["DateOfBirth"]);
            }
			endif;
			
			
                $coch = array();
	if(!empty($coaches)):
			foreach ($coaches as $coach)
            {
            	$ProfileDB = new Model_Profile;
                $Profile = $ProfileDB->GetPesonnalByPositions($coach['ID'],$coach["Position"]);
                $coch[] = array("name"=>$Profile['FirstName'],"SANumber"=>$Profile['SARugbyPlayerNo'],"surname"=>$Profile['LastName'],"position"=>$Profile["POS"],"dob"=>$Profile["DateOfBirth"],"email"=>$Profile["Email"]);
            }
			endif;
			
			$this->view->assign('manager',$managerProfile);
			$this->view->assign('name',$name);
			$this->view->assign('age',$age);
			$this->view->assign('players',$play);
			$this->view->assign('coaches',$coch);
			//print_r($play);
       }


private function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    if(count($arr)>0){
    
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }
	
    array_multisort($sort_col, $dir, $arr);
	}
}



       public function squadsheetxlsAction()
       {
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout(); 
            $request = $this->getRequest();
            $id = $request->getParam("id");
            
            $ProfileDB = new Model_Profile;         
            $SquadDB = new Model_Squad;
            $Squad = $SquadDB->getSquad($id);
            $name = $Squad['SquadName'];
            $age = ($Squad['AgeGroup']=="0" ? "Senior" : "Under ".$Squad['AgeGroup']);
            $players = json_decode($Squad['Players']);
            $coaches = json_decode($Squad['Coaches']);
            $managers = json_decode($Squad['Managers']);
            $medical = json_decode($Squad['Medical']);
            $team = array();
            $team[0] = array('Type','Position','Name','Surname','Ethnicity','Jersey #','Registration #','Date of Birth','Email');
            $team[1] = array('','','','','','','','','');
            $play = array();
            $x = 2;
            if(!empty($players)):
            foreach ($players as $player)
            {
                $player = $ProfileDB->getPlayer($player->ID);
                $play[] = array("name"=>$player['FirstName'],"surname"=>$player['LastName'],"position"=>$player["Position"],"ethnicity"=>$player["Ethnicity"],"dob"=>$player["DateOfBirth"]);
                $team[$x] = array("Player",$player["Position"],$player['FirstName'],$player['LastName'],$player["Ethnicity"],"Not Available","Not Available",$player["DateOfBirth"],"");
                $x++;
            }
            endif;
            $coch = array();
            if(!empty($coaches)):
            foreach ($coaches as $coach)
            {
                $coach = $ProfileDB->getMember($coach->ID);
                $coch[] = array("name"=>$coach['FirstName'],"surname"=>$coach['LastName'],"position"=>$coach["TypeName"],"dob"=>$coach["DateOfBirth"],"email"=>$coach["Email"]);
                $team[$x] = array("Coach",$coach["Position"],$coach['FirstName'],$coach['LastName'],$coach["Ethnicity"],"Not Available","Not Available",$coach["DateOfBirth"],$coach["Email"]);
                $x++;
            }
            endif;
            $management = array();          
            if(!empty($management)):
            foreach ($managers as $man)
            {
                $man = $ProfileDB->getMember($man->ID);
                $management[] = array("name"=>$man['FirstName'],"surname"=>$man['LastName'],"position"=>$man["TypeName"],"dob"=>$man["DateOfBirth"],"email"=>$man["Email"]);
                $team[$x] = array("Management",$man["Position"],$man['FirstName'],$man['LastName'],$man["Ethnicity"],"Not Available","Not Available",$man["DateOfBirth"],$man["Email"]);
                $x++;
            }
            endif;
            $meds = array();
            if(!empty($meds)):
            foreach ($medical as $med)
            {
                $med = $ProfileDB->getMember($med->ID);
                $meds[] = array("name"=>$med['FirstName'],"surname"=>$med['LastName'],"position"=>$med["TypeName"],"dob"=>$med["DateOfBirth"],"email"=>$med["Email"]);
                $team[$x] = array("Medical",$med["Position"],$med['FirstName'],$med['LastName'],$med["Ethnicity"],"Not Available","Not Available",$med["DateOfBirth"],$med["Email"]);
                $x++;
            }
            endif;
            // $this->view->assign('name',$name);
            // $this->view->assign('age',$age);
            // $this->view->assign('players',$play);
            // $this->view->assign('coaches',$coch);
            // $this->view->assign('managers',$management);
            // $this->view->assign('medical',$meds);
       }
       
       public function tournyAction()
       {
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout(); 
       }
			 
			 public function teamAction()
				{
			//$this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout(); 
		
				$this->_helper->layout->disableLayout(); 
        $request = $this->getRequest();
				$fid = $request->getParam("fid");
				$sid = $request->getParam("sid");
				
				$dbSquads = new Model_Squad;
			$fixtureDB = new Model_Fixture;
			$tourn = new Model_Tournament;
			$playersDB = new Model_Profile;
			$fix = $fixtureDB->getRow($fid);
			$type = "HomeTeam";
			if($fix["AwayTeam"]==$sid){
				$type = "AwayTeam";
			}
			
			$fixturesList = $fixtureDB->getFixtureLineUp22($fid,$sid,$type);
			
				
				
			
				$Tournament = $tourn->fetchRow("TID ='".$fix["TID"]."'");
				
				$this->array_sort_by_column($fixturesList,"Pos");
				
				
				
				
				//GET STUFF
				$staff = array();
			
			$officials = json_decode($fix['MatchOfficials'],true);
			
			foreach( $officials as $ref )
			{
				if(@$ref['ID']>0 && $ref['Pos']>0 ){
				$profile = $playersDB->getMember($ref['ID']);
				$staff[$ref['Pos']] = array("name"=>$profile['FirstName']." ".$profile['LastName'],"boksmart"=>$profile['boksmart']);
				}
				
			}
			
			$tpic = $Tournament['TournImage']; 
			
			$homeSquad = $dbSquads->getSquad($fix['HomeTeam']);
			$homeName = $homeSquad['SquadName'];
			$homeImage = !empty($homeSquad['SquadImage']) ? $homeSquad['SquadImage'] : $tpic;
			
			$awaySquad = $dbSquads->getSquad($fix['AwayTeam']);
			$awayName = $awaySquad['SquadName'];
			$awayImage = !empty($awaySquad['SquadImage']) ? $awaySquad['SquadImage'] : $tpic;
			
			
			
			$teamMan = $homeSquad['TeamManager'];
				$teamMan = $playersDB->getMember($teamMan);
				
				$tm = array("name"=>$teamMan['FirstName']." ".$teamMan['LastName'],"email"=>$teamMan['Email'],"cell"=>$teamMan['Mobile']);
				
				$coaches = json_decode($homeSquad['Coaches'],true);
				if(!empty($coaches)):
				foreach ($coaches as $coach)
	            {	            	
	                $coach = $playersDB->getMember($coach['ID']);
									
	                $coch[] = array("name"=>$coach['FirstName']." ".$coach['LastName'],"boksmart"=>$coach['boksmart']);
	            }
				endif;
				
				
			
				$this->view->assign('pic',$tpic);
				$this->view->assign("away",$fixturesList);
				$this->view->assign("Tourn",$Tournament);
				$this->view->assign('stuff',$staff);
					
			
			$this->view->assign('dates',date("d/m/Y",strtotime($fix['FixtureDate'])));
			$this->view->assign('tm',$tm);
			$this->view->assign('fix',$fix);
			$this->view->assign('day',date("l",strtotime($fix['FixtureDate'])));
			$this->view->assign('times',$fix['StartTime']);
			$this->view->assign('place',$fix['Location']);
			$this->view->assign('pic',$tpic);
			$this->view->assign('age',$Tournament['AgeGroup']);
			$this->view->assign('coaches',$coch);
			
			$this->view->assign('squadH',$homeName);
			$this->view->assign('squadA',$awayName);	
		
			}
       
			 
			 
			 public function teamsheet_0ldAction()
       {
           	//$this->_helper->viewRenderer->setNoRender();
          $this->_helper->layout->disableLayout(); 
		
				$this->_helper->layout->disableLayout(); 
        $request = $this->getRequest();
				$fid = $request->getParam("fid");
				$sid = $request->getParam("sid");
				
				$dbSquads = new Model_Squad;
			
			$tourn = new Model_Tournament;
			$playersDB = new Model_Profile;
			
			$fixtureDB = new Model_Fixture;
			$fix = $fixtureDB->getRow($fid);
			
			$this->view->assign('Code',$fix["Code"]);
			
			$positionsDB = new Model_Positions;
				$this->view->assign("Playerspositions",$positionsDB->getPos($fix["Code"]));
			
			$type = "HomeTeam";
			if($fix["AwayTeam"]==$sid){
				$type = "AwayTeam";
			}
			
			$fixturesList = $fixtureDB->getFixtureLineUp($fid,$sid,$type);
				
				
			
				$Tournament = $tourn->fetchRow("TID ='".$fix["TID"]."'");
				
				//$this->array_sort_by_column($fixturesList,"Pos");
				
				
				
				
				//GET STUFF
				$staff = array();
			
			$officials = json_decode($fix['MatchOfficials'],true);
			if(count($officials)>0){
			foreach( $officials as $ref )
			{
				if(@$ref['ID']>0 && $ref['Pos']>0 ){
				$profile = $playersDB->getMember($ref['ID']);
				$staff[$ref['Pos']] = array("name"=>$profile['FirstName']." ".$profile['LastName'],"boksmart"=>$profile['boksmart']);
				}
				
			}
			
			}
			$tpic = $Tournament['TournImage']; 
			
			$homeSquad = $dbSquads->getSquad($fix['HomeTeam']);
			$this->view->assign("squad",$homeSquad);
			$homeName = $homeSquad['SquadName'];
			$homeImage = !empty($homeSquad['SquadImage']) ? $homeSquad['SquadImage'] : $tpic;
			
			$awaySquad = $dbSquads->getSquad($fix['AwayTeam']);
			$awayName = $awaySquad['SquadName'];
			$awayImage = !empty($awaySquad['SquadImage']) ? $awaySquad['SquadImage'] : $tpic;
			
			
			if($type =="HomeTeam"){
				$teamMan = $homeSquad['TeamManager'];
			}else{
				$teamMan = $awaySquad['TeamManager'];
			}
			
			$teamMan = $playersDB->getMember($teamMan);
				
				$tm = array("name"=>$teamMan['FirstName']." ".$teamMan['LastName'],"email"=>$teamMan['Email'],"cell"=>$teamMan['Mobile']);
				
				$coaches = json_decode($homeSquad['Coaches'],true);
				if(!empty($coaches)):
					if(count($coaches)>0){
				foreach ($coaches as $coach)
	            {	            	
	                $coach = $playersDB->getMember($coach['ID']);
									
	                $coch[] = array("name"=>$coach['FirstName']." ".$coach['LastName'],"boksmart"=>$coach['boksmart']);
	            }
					}
				endif;

				
				
			
				$this->view->assign('pic',$tpic);
				$this->view->assign("away",$fixturesList);
				$this->view->assign("Tourn",$Tournament);
				$this->view->assign('stuff',$staff);
					
			
		$this->view->assign('dates',date("d/m/Y",strtotime($fix['FixtureDate'])));
			$this->view->assign('tm',$tm);
			$this->view->assign('day',date("l",strtotime($fix['FixtureDate'])));
			$this->view->assign('times',$fix['StartTime']);
			$this->view->assign('place',$fix['Location']);
			$this->view->assign('pic',$tpic);
			$this->view->assign('age',$Tournament['AgeGroup']);
			$this->view->assign('coaches',$coch);
			
			
			if($type =="HomeTeam"){
				$this->view->assign('squadH',$homeName);
			$this->view->assign('squadA',$awayName);
			}else{
				$this->view->assign('squadH',$awayName);
			$this->view->assign('squadA',$homeName);
			}
				
			
			
			
       }
			 
			 
		
public function teamsheetpicAction()
    {
    $this->_helper->layout->disableLayout();
		$FixtureTbl = new Model_Fixture;
		
                
                
		$request = $this->getRequest();  
		$fid =$request->getParam("fid");
        $sid =$request->getParam("sid");
        //GET FIXTURE
        $Fixture = $FixtureTbl->getNewFixtureLineUp($fid,$sid);
		
		
		$this->view->assign("Players",$Fixture["Players"]);
		$this->view->assign("Team",$Fixture["Team"]);
       	$this->view->assign("fixture",$Fixture["Fixture"]);
		$this->view->assign("Coaches",$Fixture["Coaches"]);
		$this->view->assign("Officials",$Fixture["Officials"]);
		
}
	
	
		
	
public function teamsheetAction()
    {
    $this->_helper->layout->disableLayout();
		$FixtureTbl = new Model_Fixture;
		$SquadsTbl = new Model_Squad;
		$MatchReportTbl = new Model_MatchReport;
                $profileDB = new Model_Profile;
                
                
                
		$request = $this->getRequest();  
		$fid =$request->getParam("fid");
                $sid =$request->getParam("sid");
                
                 
                 //GET FIXTURE
                $Fixture = $FixtureTbl->getFixture($fid);
                $this->view->assign("fixture",$Fixture);
               
                if(!$sid){
                    $sid = $Fixture["HomeTeam"];
                }
                $squad = $SquadsTbl->getSquadComp($sid);
                
                $SquadPlayers = json_decode($squad["Players"],true);
              
                
		$this->view->assign("squad",$squad);
                $this->view->assign("SID",$sid);
                $this->view->assign("FID",$fid);
                
                if($sid==$Fixture["HomeTeam"]){
                    $listHomeTeam =  json_decode($Fixture["TeamH"],true);
                    
                }
                if($sid==$Fixture["AwayTeam"]){
                    $listHomeTeam =  json_decode($Fixture["TeamA"],true);
                }
				$this->view->assign("squadH",$Fixture["ShortName1"]);
                $this->view->assign("squadA",$Fixture["ShortName2"]);
                
                //GET STUFF
				$staff = array();
			
			$officials = json_decode($Fixture['MatchOfficials'],true);
			if(count($officials)>0){
			foreach( $officials as $ref )
			{
				if(@$ref['ID']>0 && $ref['Pos']>0 ){
				$profile = $profileDB->getMember($ref['ID']);
				$staff[$ref['Pos']] = array("name"=>$profile['FirstName']." ".$profile['LastName'],"boksmart"=>$profile['boksmart']);
				}
				
			}
			
			}
              $this->view->assign('stuff',$staff);
              
			
			$teamMan = $profileDB->getMember($squad['TeamManager']);
			$coch = array();
                        $personaal = array();
			$tm = array("name"=>$teamMan['FirstName']." ".$teamMan['LastName'],"email"=>$teamMan['Email'],"cell"=>$teamMan['Mobile']);
			$this->view->assign('tm',$tm);	
		$coaches = json_decode($squad['Coaches'],true);
				if(!empty($coaches)):
					if(count($coaches)>0){
		foreach ($coaches as $coah)
	            {	            	
	                
                        $userType = new Model_UserType;
                        $Role = $userType->fetchRow("TypeID ='".$coah['Position']."'");
                        if($Role["parent"]==3){
                            $coach = $profileDB->getMember($coah['ID']);
                            $coch[$coah['Position']] = array("name"=>$coach['FirstName']." ".$coach['LastName'],"boksmart"=>$coach['boksmart'],"role"=>$Role['TypeName']);
                        }
									
	                $personaal[] = array("name"=>$coah['FirstName']." ".$coah['LastName'],"boksmart"=>$coah['boksmart']);
	            }
					}
				endif;
                                asort($coch);
              $this->view->assign('coaches',$coch);
              
              
              
              
              
                $homeTeam =array();
                
                if(count($listHomeTeam)>0){
                   
                    foreach($listHomeTeam as $player){
                        if($player['ID']>0){
                        $getProfile = $profileDB->GetPlayersByPositions($player['ID'], $player['Pos']);
                        
                        $homeTeam[$player['Pos']]["UserID"] = $getProfile["UserID"];
                        $homeTeam[$player['Pos']]["Cap"] = $player["Cap"];
                        $homeTeam[$player['Pos']]["Vice"] = $player["Vice"];
			$homeTeam[$player['Pos']]["FirstName"] = $getProfile["FirstName"];
			$homeTeam[$player['Pos']]["LastName"] = $getProfile["LastName"];
                        $homeTeam[$player['Pos']]["PostionNo"] = $player["Pos"];
                        $homeTeam[$player['Pos']]["Postion"] = (!empty($getProfile["POS"]))? $getProfile["POS"] : "POS: not assigned" ;
                        $homeTeam[$player['Pos']]["JerseyNumber"] = (!empty($player["Jersey"]))? $player["Jersey"] : 0;
			$homeTeam[$player['Pos']]["PID"] = $getProfile["PID"];
                        $homeTeam[$player['Pos']]["Ethnicity"] = $getProfile["Ethnicity"];
                        $homeTeam[$player['Pos']]["IDNumber"] = $getProfile["IDNumber"];
                         $homeTeam[$player['Pos']]["DateOfBirth"] = $getProfile["DateOfBirth"];  
                        }
                    }
                }
                $positionsDB = new Model_Positions;
                $listPositions = $positionsDB->getPos($squad["RugbyCode"]);
                $Positions =array();
                if(count($listPositions)>0){
                   
                    foreach($listPositions as $pos){
                    $Positions[$pos["PID"]] = $pos;
                    }
                }
                
                $this->view->assign("positions",$Positions);
                $this->view->assign("lineup",$homeTeam);
                $playersDB = new Model_Profile;
                $play = array();
                $count = 1;
                if(count($SquadPlayers)>0){
			            foreach ($SquadPlayers as $p)
			            {
			                $player = $playersDB->getPlayerProfile($p["ID"]);
					$play[$count] = array("UserID"=>$player['UserID'],"Jersey"=>$p['Jersey'],"Position"=>$p['Position'],"LastName"=>$player['LastName'],"Name"=>$this->clean($player['LastName']).", ".$this->clean($player['FirstName']));
					$count++;
				}
                
                }
                
              $this->array_sort_by_column($play,"LastName");
            $this->view->assign("players",$play);
             
}
	function clean($string) {
			
			return $string;
			exit;
   $string = str_replace(' ', ' ', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', ' ', $string); // Replaces multiple hyphens with single one.
}		 
	public function teamsheetallAction()
{
    $this->_helper->layout->disableLayout();
		$FixtureTbl = new Model_Fixture;
		$SquadsTbl = new Model_Squad;
		$MatchReportTbl = new Model_MatchReport;
                $profileDB = new Model_Profile;
                
                
                
		$request = $this->getRequest();
		$sid =$request->getParam("sid");  
		$fid =$request->getParam("fid");
                
                //GET SQUADS
                 $squad = $SquadsTbl->getSquadComp($sid);
		$this->view->assign("squad",$squad);
                 
                 //GET FIXTURE
                $Fixture = $FixtureTbl->getFixture($fid);
                $this->view->assign("fixture",$Fixture);
                
                $HomeTeamScore = $MatchReportTbl->getScore($fid, $Fixture["HomeTeam"]);
                $AwayTeamScore = $MatchReportTbl->getScore($fid, $Fixture["AwayTeam"]);
                
                
                
                
                $this->view->assign("Scores",array("HScore"=>$HomeTeamScore->toArray(),"AScore"=>$AwayTeamScore->toArray()));
                $homeTeam =array();
                $listHomeTeam =  json_decode($Fixture["TeamH"],true);
                if(count($listHomeTeam)>0){
                    $PlayersScore = json_decode($HomeTeamScore["Score"],true) ;
                    $PlayersSubstitutions = json_decode($HomeTeamScore["Substitutions"],true) ;
                    
                    foreach($listHomeTeam as $player){
                        $getProfile = $profileDB->GetPlayersByPositions($player['ID'], $player['Pos']);
                        $Cap ="";
                        if($player["Cap"]==1){
                        $Cap ="(C)";
                        }
                        $Vice ="";
                        if($player["Vice"]==1){
                        $Vice ="(V)";
                        }
                        $IMG = "";
                        $Image = "/IMGS/no-image.jpg";
                        $SquadPlayerPhoto = new Model_Squadplayerprofile;
                                        $PlayerPhoto = $SquadPlayerPhoto->fetchRow("UserID ='".$player['ID']."' AND SID ='".$sid."'");
                                        if($PlayerPhoto["File"]==null || !isset($PlayerPhoto)) {
                                            if(empty($getProfile["Avatar"]) || $getProfile["Avatar"]=="null"){
                                            $PlayerPhoto["Thumb"]=$Image;
                                            }else{
                                                $PlayerPhoto["Thumb"]=$getProfile["Avatar"];
                                            }
                                            
                                        }
                        
                        if(!empty($PlayerPhoto["Thumb"])){
                           $IMG =  "<div class='list-group list-group-contacts'>"
                                   . "<div class='list-group-item d-rm-border'>"
                                   . "<img src='".$PlayerPhoto["Thumb"]."' /></div></div>";
                        }
                        $homeTeam[$player['Pos']]["Subs"] = $PlayersSubstitutions;
                        $homeTeam[$player['Pos']]["Cap"] = $Cap;
                        $homeTeam[$player['Pos']]["Vice"] = $Vice;
                        $homeTeam[$player['Pos']]["CapNo"] = $player["Cap"];
                        $homeTeam[$player['Pos']]["ViceNo"] = $player["Vice"];
                        $homeTeam[$player['Pos']]["UserID"] = $getProfile["UserID"];
                        $homeTeam[$player['Pos']]["Avatar"] = $IMG;
                        $homeTeam[$player['Pos']]["INIT"] = $this->clean($getProfile["FirstName"])[0];
			$homeTeam[$player['Pos']]["FirstName"] = $getProfile["FirstName"];
			$homeTeam[$player['Pos']]["LastName"] = $getProfile["LastName"];
                        $homeTeam[$player['Pos']]["PostionNo"] = $player["Pos"];
                        $homeTeam[$player['Pos']]["Postion"] = (!empty($getProfile["POS"]))? $getProfile["POS"] : "POS: not assigned" ;
                        $homeTeam[$player['Pos']]["JerseyNumber"] = (!empty($player["Jersey"]))? $player["Jersey"] : 0;
			$homeTeam[$player['Pos']]["PID"] = $getProfile["PID"];	
                        $homeTeam[$player['Pos']]["tries"] = ($PlayersScore[$getProfile["UserID"]]["tries"]>0)? $PlayersScore[$getProfile["UserID"]]["tries"] : 0; 
                        $homeTeam[$player['Pos']]["Conversions"] = ($PlayersScore[$getProfile["UserID"]]["Conversions"]>0)? $PlayersScore[$getProfile["UserID"]]["Conversions"] : 0;
                        $homeTeam[$player['Pos']]["Penalties"] = ($PlayersScore[$getProfile["UserID"]]["Penalties"]>0)? $PlayersScore[$getProfile["UserID"]]["Penalties"] : 0;
                        $homeTeam[$player['Pos']]["DropGoals"] = ($PlayersScore[$getProfile["UserID"]]["DropGoals"]>0)? $PlayersScore[$getProfile["UserID"]]["DropGoals"] : 0;
                                               
                    }
                }
               $PlayersSubstitutions = json_decode($AwayTeamScore["Substitutions"],true) ;
                $AwayTeam =array();
                $listAwayTeam =  json_decode($Fixture["TeamA"],true);
                if(count($listAwayTeam)>0){
                    $PlayersScore = json_decode($AwayTeamScore["Score"],true) ;
                    
                    
                    foreach($listAwayTeam as $player){
                        $getProfile = $profileDB->GetPlayersByPositions($player['ID'], $player['Pos']);
                        $Cap ="";
                        if($player["Cap"]==1){
                        $Cap ="(C)";
                        }
                        $Vice ="";
                        if($player["Vice"]==1){
                        $Vice ="(V)";
                        }
                        $AwayTeam[$player['Pos']]["Subs"] = $PlayersSubstitutions;
                        $AwayTeam[$player['Pos']]["Cap"] = $Cap;
                        $AwayTeam[$player['Pos']]["Vice"] = $Vice;
                        $AwayTeam[$player['Pos']]["CapNo"] = $player["Cap"];
                        $AwayTeam[$player['Pos']]["ViceNo"] = $player["Vice"];
                        $AwayTeam[$player['Pos']]["UserID"] = $getProfile["UserID"];
                        $AwayTeam[$player['Pos']]["Avatar"] = $PlayerPhoto["Thumb"];
                        $AwayTeam[$player['Pos']]["INIT"] = $this->clean($getProfile["FirstName"])[0];
			$AwayTeam[$player['Pos']]["FirstName"] = $getProfile["FirstName"];
			$AwayTeam[$player['Pos']]["LastName"] = $getProfile["LastName"];
                        $AwayTeam[$player['Pos']]["PostionNo"] = $player["Pos"];
                        $AwayTeam[$player['Pos']]["JerseyNumber"] = (!empty($player["Jersey"]))? $player["Jersey"] : 0;
			$AwayTeam[$player['Pos']]["PID"] = $getProfile["PID"];	
                        $AwayTeam[$player['Pos']]["tries"] = ($PlayersScore[$getProfile["UserID"]]["tries"]>0)? $PlayersScore[$getProfile["UserID"]]["tries"] : 0; 
                        $AwayTeam[$player['Pos']]["Conversions"] = ($PlayersScore[$getProfile["UserID"]]["Conversions"]>0)? $PlayersScore[$getProfile["UserID"]]["Conversions"] : 0;
                        $AwayTeam[$player['Pos']]["Penalties"] = ($PlayersScore[$getProfile["UserID"]]["Penalties"]>0)? $PlayersScore[$getProfile["UserID"]]["Penalties"] : 0;
                        $AwayTeam[$player['Pos']]["DropGoals"] = ($PlayersScore[$getProfile["UserID"]]["DropGoals"]>0)? $PlayersScore[$getProfile["UserID"]]["DropGoals"] : 0;
                                               
                    }
                }
                $n=1;
                $blank = array();
                while($n<$squad["NumbersOfPlayers"]+1){
                    
                    $DB = new Model_Positions;
                    $POS = $DB->getRow($n);
                    
                    $blank[$n]["LastName"] = "Not Assigned";
                    $blank[$n]["JerseyNumber"] = 0;
                    $blank[$n]["Postion"] = $POS["Position"];
                    $n++;
                }
                
                if(count($homeTeam)==0){
                    $homeTeam=$blank;
                }
                if(count($AwayTeam)==0){
                    $AwayTeam=$blank;
                }
                
                $this->view->assign("Players",array("HomeTeam"=>$homeTeam,"AwayTeam"=>$AwayTeam));
               if($request->getParam("page")==1){
                    $this->_helper->viewRenderer('fixtures/myteam', null, true);
               }
               
}		 
			 
       public function teamsheetttoldAction()
       {
           	//$this->_helper->viewRenderer->setNoRender();
          $this->_helper->layout->disableLayout(); 
		
				$this->_helper->layout->disableLayout(); 
        $request = $this->getRequest();
				$fid = $request->getParam("fid");
				
				
				$dbSquads = new Model_Squad;
			
			$tourn = new Model_Tournament;
			$playersDB = new Model_Profile;
			
			$fixtureDB = new Model_Fixture;
			$fix = $fixtureDB->getRow($fid);
			
			$this->view->assign("fix",$fix);
			
			$this->view->assign('Code',$fix["Code"]);
			
			$positionsDB = new Model_Positions;
				$this->view->assign("Playerspositions",$positionsDB->getPos($fix["Code"]));
			
		
			$sid = $fix["HomeTeam"];
			$fixturesList = $fixtureDB->getFixtureLineUp($fid,$fix["HomeTeam"],"HomeTeam");
			$fixturesList2 = $fixtureDB->getFixtureLineUp($fid,$fix["AwayTeam"],"AwayTeam");
			
			
			$Tournament = $tourn->fetchRow("TID ='".$fix["TID"]."'");
				
				//$this->array_sort_by_column($fixturesList,"Pos");
				
				//GET STUFF
				$staff = array();
				
			
			$officials = json_decode($fix['MatchOfficials'],true);
			if(count($officials)>0){
			foreach( $officials as $ref )
			{
				if(@$ref['ID']>0 && $ref['Pos']>0 ){
				$profile = $playersDB->getMember($ref['ID']);
				$staff[$ref['Pos']] = array("name"=>$profile['FirstName']." ".$profile['LastName'],"boksmart"=>$profile['boksmart']);
				}
				
			}
			
			}
			$tpic = $Tournament['TournImage']; 
			
			$homeSquad = $dbSquads->getSquad($fix['HomeTeam']);
			
			$homeName = $homeSquad['SquadName'];
			$homeImage = !empty($homeSquad['SquadImage']) ? $homeSquad['SquadImage'] : $tpic;
			
			$awaySquad = $dbSquads->getSquad($fix['AwayTeam']);
			$awayName = $awaySquad['SquadName'];
			$awayImage = !empty($awaySquad['SquadImage']) ? $awaySquad['SquadImage'] : $tpic;
			
			
			
			
			
			$teamMan = $playersDB->getMember($teamMan);
				
				$tm = array("name"=>$teamMan['FirstName']." ".$teamMan['LastName'],"email"=>$teamMan['Email'],"cell"=>$teamMan['Mobile']);
				
				$coaches = json_decode($homeSquad['Coaches'],true);
				if(!empty($coaches)):
					if(count($coaches)>0){
				foreach ($coaches as $coach)
	            {	            	
	                $coach = $playersDB->getMember($coach['ID']);
									
	                $coch[] = array("name"=>$coach['FirstName']." ".$coach['LastName'],"boksmart"=>$coach['boksmart']);
	            }
					}
				endif;

				
				
			
				$this->view->assign('pic',$tpic);
				$this->view->assign("awayList",$fixturesList2);
				$this->view->assign("homeList",$fixturesList);
				
				
				
				
				
				$this->view->assign("Tourn",$Tournament);
				$this->view->assign('stuff',$staff);
					
			
		$this->view->assign('dates',date("d/m/Y",strtotime($fix['FixtureDate'])));
			$this->view->assign('tm',$tm);
			$this->view->assign('day',date("l",strtotime($fix['FixtureDate'])));
			$this->view->assign('times',$fix['StartTime']);
			$this->view->assign('place',$fix['Location']);
			$this->view->assign('pic',$tpic);
			$this->view->assign('age',$Tournament['AgeGroup']);
			$this->view->assign('coaches',$coch);
			
			
			
				
			
			
       }

 public function squadstatsAction()
    {
    	//$this->_helper->viewRenderer->setNoRender();
      $this->_helper->layout->disableLayout();
				
    	$request = $this->getRequest(); 
			
        	
					$SID = $request->getParam("SID");
					$FilterBypos = $request->getParam("pos");
					
					
					$squadsDB = new Model_Squad;
					$DATA = $squadsDB->getSquad($SID);
					$this->view->assign("squad",$DATA);
					$ProfileDB = new Model_Profile;
					$TournName = "";
					
					$PlayersArray = json_decode($DATA["Players"],true);
                                        $ConfirmedPlayers = json_decode($DATA["ConfirmedPlayers"],true);
						
						$PLAYERSLIST = array();
						$COUNT =0;
						$TotalCOUNT =0;
						$DEMOGRAPHICS["African"] =0;
						$DEMOGRAPHICS["Coloured"] =0;
						$DEMOGRAPHICS["Indian"] =0;
						$DEMOGRAPHICS["White"] =0;
						$DEMOGRAPHICS["Undefined"] =0;
						
						
						
						if(count($PlayersArray)>0){
							if(isset($PlayersArray["Jersey"])){
								$this->array_sort_by_column($PlayersArray, 'Jersey');
							}
							
					
							foreach($PlayersArray as $d){
								
								$Profile = $ProfileDB->getProfileWithCareer($d["ID"],$d["Position"],$DATA["RugbyCode"]);
								
								
								
								
								
								if($Profile["UserID"]>0){
									$Profile2["Position"]= 	$Profile["Position"];
										
									$Profile["Json"]= json_decode($Profile["Json"],true);
							
								
								$Profile2["Started"]=0;
								$Profile2["Benched"]=0;
								$Profile2["tries"]=0;
								$Profile2["Conversions"]=0;
								$Profile2["Penalties"]=0;
								$Profile2["DropGoals"]=0;
								$Profile2["GameTime"]=0;
								$Profile2["YellowCard"]=0;
								$Profile2["RedCard"]=0;
								
								if(count($Profile["Json"][$SID])>0){
									//$Profile["Json"]=$Profile["Json"][$SID];
						
									foreach($Profile["Json"][$SID] as $fixtureJso){
										
									$Profile2["GameTime"]=@$Profile2["GameTime"]+$fixtureJso["GameTime"];
									$Profile2["YellowCard"]=@$Profile2["YellowCard"]+$fixtureJso["YellowCard"];
									$Profile2["RedCard"]=@$Profile2["RedCard"]+$fixtureJso["RedCard"];
								
										
										if($fixtureJso["Position"]<16){
										$Profile2["Started"]++;
										}
								if($fixtureJso["Position"]>15){
										$Profile2["Benched"]++;
										}
									if(isset($fixtureJso["DATA"])){
										$Profile2["tries"]=$Profile2["tries"]+$fixtureJso["DATA"]["tries"];
									$Profile2["Conversions"]=$Profile2["Conversions"]+$fixtureJso["DATA"]["Conversions"];
									$Profile2["Penalties"]=$Profile2["Penalties"]+$fixtureJso["DATA"]["Penalties"];
									$Profile2["DropGoals"]=$Profile2["DropGoals"]+$fixtureJso["DATA"]["DropGoals"];
									}
									
									
									
									}
								
								}
								
									
									
									
									$PlayerInjury = new Model_PlayerInjury;	
									$getIngetRy= $PlayerInjury->fetchRow("UserID ='".$d["ID"]."' AND ReturnToPlay > '".date("Y-m-d")."'");
									$injury = 0;
									if($getIngetRy){
										
                                                                                if($getIngetRy["ReturnToTraining"] <= date("Y-m-d")){
                                                                                $injury = 1;
                                                                                }else{
                                                                                        $injury = 2;
                                                                                }
                                                                        }




						
									
										
                                                                            $Profile = $Profile->toArray();
                                                                                $un_name = $Profile["un_name"];
                                                                                if($DATA['AgeGroup']<14 && $DATA['AgeGroup']>0){
                                                                                    $un_name = $Profile["PrimarySchool"];
                                                                                }else if($DATA['AgeGroup']>13 && $DATA['AgeGroup']<18){
                                                                                    $un_name = $Profile["SecondarySchool"];
                                                                                }
                                                                        
                                                                         
                                                                       
                                                                      $Profile["CONFIRMED"]           = $Confirmed;
                                                                        $Profile["Update"]              = ($Profile["DateModified"] !="0000-00-00 00:00:00")? 1 : 0 ;
                                                                        $Profile["PROFILEDOC"]          = $PROFILEDOC;
                                                                        $Profile["IDDOC"]               = $IDDOC;
                                                                        $Profile["INDEMNITY"]           = $INDEMNITY;
                                                                        
                                                                        $Profile["PROFILEDOCLink"]      = $PROFILEDOCFile;
                                                                        $Profile["IDDOCLink"]           = $IDDOCFile;
                                                                        $Profile["INDEMNITYLink"]       = $INDEMNITYFile;
                                                                        
									$Profile["un_name"]             = $un_name;	
									$Profile["PositionNo"]          = $d["Position"];
									$Profile["SID"]                 = $SID;
									$Profile["Jersey"]              = $d["Jersey"];
									$Profile["Rank"]                = $d["Rank"];
									$Profile["ReturnToTraining"]    = $injury;
                                                                        $Profile["Captain"] = (!empty($d["Captain"]))? $d["Captain"] : 0;;
                                                                        $Profile["Vice"] = (!empty($d["Vice"]))? $d["Vice"] : 0;;
                                                
									$Profile["DATA"] = $Profile2;
									$PLAYERSLIST[] = $Profile;
									
									
									
									
									$TotalCOUNT++;
									
									$COUNT++;
								}
								
							}
						
						}
					
                                                
                                                
					$squadlineup =	array("Players"=>$PLAYERSLIST);
					$this->view->assign("lineup",$squadlineup);
					
					//echo "<pre>";
				//					print_r($PLAYERSLIST);
		}

      
       
    public function teamsheetttposAction()
       {
           	//$this->_helper->viewRenderer->setNoRender();
          $this->_helper->layout->disableLayout(); 
		
				$this->_helper->layout->disableLayout(); 
        $request = $this->getRequest();
				$fid = $request->getParam("fid");
				
				
				$dbSquads = new Model_Squad;
			
			$tourn = new Model_Tournament;
			$playersDB = new Model_Profile;
			
			$fixtureDB = new Model_Fixture;
			$fix = $fixtureDB->getRow($fid);
			
			$this->view->assign("fix",$fix);
			
			$this->view->assign('Code',$fix["Code"]);
			
			$positionsDB = new Model_Positions;
				$this->view->assign("Playerspositions",$positionsDB->getPos($fix["Code"]));
			
		
			$sid = $fix["HomeTeam"];
                        
                        
                        
                        
                        
			$fixturesListSS = $fixtureDB->getFixtureLineUp($fid,$fix["HomeTeam"],"HomeTeam");
                        $fixturesList = array();
                        foreach($fixturesListSS as $listHome ){
                            $fixturesList[$listHome["Pos"]]=$listHome;
                        }
			$fixturesList2SS = $fixtureDB->getFixtureLineUp($fid,$fix["AwayTeam"],"AwayTeam");
                        $fixturesList2 = array();
                        foreach($fixturesList2SS as $listHome ){
                            $fixturesList2[$listHome["Pos"]]=$listHome;
                        }
                        
			
			$Tournament = $tourn->fetchRow("TID ='".$fix["TID"]."'");
				
				//$this->array_sort_by_column($fixturesList,"Pos");
				
				//GET STUFF
				$staff = array();
				
			
			$officials = json_decode($fix['MatchOfficials'],true);
			if(count($officials)>0){
			foreach( $officials as $ref )
			{
				if(@$ref['ID']>0 && $ref['Pos']>0 ){
				$profile = $playersDB->getMember($ref['ID']);
				$staff[$ref['Pos']] = array("name"=>$profile['FirstName']." ".$profile['LastName'],"boksmart"=>$profile['boksmart']);
				}
				
			}
			
			}
			$tpic = $Tournament['TournImage']; 
			
			$homeSquad = $dbSquads->getSquad($fix['HomeTeam']);
			
			$homeName = $homeSquad['SquadName'];
			$homeImage = !empty($homeSquad['SquadImage']) ? $homeSquad['SquadImage'] : $tpic;
			
			$awaySquad = $dbSquads->getSquad($fix['AwayTeam']);
			$awayName = $awaySquad['SquadName'];
			$awayImage = !empty($awaySquad['SquadImage']) ? $awaySquad['SquadImage'] : $tpic;
			
			
			$hometSquad = $dbSquads->getSquad($fix['HomeTeam']);
                        
			$Homecoaches = json_decode($hometSquad['Coaches'],true);
			$HeadCaochHome = null;
			if(count($Homecoaches)>0){
				foreach ($Homecoaches as $Homecoache) {
					if($Homecoache["Position"]==10){
						$HeadCaochHome = $playersDB->getMember($Homecoache["ID"]);
					}
				}
			}
			
			
			$awaytSquad = $dbSquads->getSquad($fix['AwayTeam']);
			$Awaycoaches = json_decode($awaytSquad['Coaches'],true);
			$HeadCaochAway = null;
			if(count($Awaycoaches)>0){
				foreach ($Awaycoaches as $Awaycoache) {
					if($Awaycoache["Position"]==10){
						$HeadCaochAway = $playersDB->getMember($Awaycoache["ID"]);
					}
				}
			}
			
			$this->view->assign("homeHeadCaoche",$HeadCaochHome);
			$this->view->assign("awayHeadCaoche",$HeadCaochAway);
			
			
			
			
			$teamMan = $playersDB->getMember($teamMan);
				
				$tm = array("name"=>$teamMan['FirstName']." ".$teamMan['LastName'],"email"=>$teamMan['Email'],"cell"=>$teamMan['Mobile']);
				
				

				
				
			
				$this->view->assign('pic',$tpic);
				$this->view->assign("awayList",$fixturesList2);
				$this->view->assign("homeList",$fixturesList);
				
				
				
				
				
				$this->view->assign("Tourn",$Tournament);
				$this->view->assign('stuff',$staff);
					
			
		$this->view->assign('dates',date("d/m/Y",strtotime($fix['FixtureDate'])));
			$this->view->assign('tm',$tm);
			$this->view->assign('day',date("l",strtotime($fix['FixtureDate'])));
			$this->view->assign('times',$fix['StartTime']);
			$this->view->assign('place',$fix['Location']);
			$this->view->assign('pic',$tpic);
			$this->view->assign('age',$Tournament['AgeGroup']);
			$this->view->assign('coaches',$coch);
			
			
			
				
			
			
       }   
       
       
       
       
       
  public function teamsheetttAction()
       {
           	//$this->_helper->viewRenderer->setNoRender();
          $this->_helper->layout->disableLayout(); 
		
				$this->_helper->layout->disableLayout(); 
        $request = $this->getRequest();
				$fid = $request->getParam("fid");
				
				
				$dbSquads = new Model_Squad;
			
			$tourn = new Model_Tournament;
			$playersDB = new Model_Profile;
			
			$fixtureDB = new Model_Fixture;
			$fix = $fixtureDB->getRow($fid);
			
			$this->view->assign("fix",$fix);
			
			$this->view->assign('Code',$fix["Code"]);
			
			$positionsDB = new Model_Positions;
				$this->view->assign("Playerspositions",$positionsDB->getPos($fix["Code"]));
			
		
			$sid = $fix["HomeTeam"];
                        
                        
                        
                        
                        
			$fixturesListSS = $fixtureDB->getFixtureLineUp($fid,$fix["HomeTeam"],"HomeTeam");
                        $fixturesList = array();
                        foreach($fixturesListSS as $listHome ){
                            $fixturesList[$listHome["Pos"]]=$listHome;
                        }
			$fixturesList2SS = $fixtureDB->getFixtureLineUp($fid,$fix["AwayTeam"],"AwayTeam");
                        $fixturesList2 = array();
                        foreach($fixturesList2SS as $listHome ){
                            $fixturesList2[$listHome["Pos"]]=$listHome;
                        }
                        
			
			$Tournament = $tourn->fetchRow("TID ='".$fix["TID"]."'");
				
				//$this->array_sort_by_column($fixturesList,"Pos");
				
				//GET STUFF
				$staff = array();
				
			
			$officials = json_decode($fix['MatchOfficials'],true);
			if(count($officials)>0){
			foreach( $officials as $ref )
			{
				if(@$ref['ID']>0 && $ref['Pos']>0 ){
				$profile = $playersDB->getMember($ref['ID']);
				$staff[$ref['Pos']] = array("name"=>$profile['FirstName']." ".$profile['LastName'],"boksmart"=>$profile['boksmart']);
				}
				
			}
			
			}
			$tpic = $Tournament['TournImage']; 
			
			$homeSquad = $dbSquads->getSquad($fix['HomeTeam']);
			
			$homeName = $homeSquad['SquadName'];
			$homeImage = !empty($homeSquad['SquadImage']) ? $homeSquad['SquadImage'] : $tpic;
			
			$awaySquad = $dbSquads->getSquad($fix['AwayTeam']);
			$awayName = $awaySquad['SquadName'];
			$awayImage = !empty($awaySquad['SquadImage']) ? $awaySquad['SquadImage'] : $tpic;
			
			
			$hometSquad = $dbSquads->getSquad($fix['HomeTeam']);
                        
			$Homecoaches = json_decode($hometSquad['Coaches'],true);
			$HeadCaochHome = null;
			if(count($Homecoaches)>0){
				foreach ($Homecoaches as $Homecoache) {
					if($Homecoache["Position"]==10){
						$HeadCaochHome = $playersDB->getMember($Homecoache["ID"]);
					}
				}
			}
			
			
			$awaytSquad = $dbSquads->getSquad($fix['AwayTeam']);
			$Awaycoaches = json_decode($awaytSquad['Coaches'],true);
			$HeadCaochAway = null;
			if(count($Awaycoaches)>0){
				foreach ($Awaycoaches as $Awaycoache) {
					if($Awaycoache["Position"]==10){
						$HeadCaochAway = $playersDB->getMember($Awaycoache["ID"]);
					}
				}
			}
			
			$this->view->assign("homeHeadCaoche",$HeadCaochHome);
			$this->view->assign("awayHeadCaoche",$HeadCaochAway);
			
			
			
			
			$teamMan = $playersDB->getMember($teamMan);
				
				$tm = array("name"=>$teamMan['FirstName']." ".$teamMan['LastName'],"email"=>$teamMan['Email'],"cell"=>$teamMan['Mobile']);
				
				

				
				
			
				$this->view->assign('pic',$tpic);
				$this->view->assign("awayList",$fixturesList2);
				$this->view->assign("homeList",$fixturesList);
				
				
				
				
				
				$this->view->assign("Tourn",$Tournament);
				$this->view->assign('stuff',$staff);
					
			
		$this->view->assign('dates',date("d/m/Y",strtotime($fix['FixtureDate'])));
			$this->view->assign('tm',$tm);
			$this->view->assign('day',date("l",strtotime($fix['FixtureDate'])));
			$this->view->assign('times',$fix['StartTime']);
			$this->view->assign('place',$fix['Location']);
			$this->view->assign('pic',$tpic);
			$this->view->assign('age',$Tournament['AgeGroup']);
			$this->view->assign('coaches',$coch);
			
			
			
				
			
			
       }

	public function assessmentAction()
	{
		//$this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout(); 
		
		$ProfileDB = new Model_Profile;
		$accessDB = new Model_TemplateAccess;
		$criteriaDB = new Model_Criteria;
		$assessedDB = new Model_Assessd; 
		
		$request = $this->getRequest();
		$aid = $request->getParam("id");
		$uid = $request->getParam("uid");
		$assessor = $request->getParam("aid");
		
		$player = $ProfileDB->getPlayer($uid);
		$senior = $ProfileDB->getPerson($assessor);
				
		$access = $accessDB->myAccess($aid);
		$access = $access->toArray();
		
		$heading = array();
		foreach ($access as $me) 
		{
			$find = explode(',', $me['assessor']);
			foreach($find as $ass_id)
			{
				if($ass_id == $assessor)
				{
					$heading[] = $me['criteriaID'];
				}
			}
		}
		
		$final = array();
		$x=0;
		foreach($heading as $head)
		{
			$criteria = $criteriaDB->nameCriteria($head);
			$criteria = $criteria->toArray();
			
			$final[$x]['head'] = $criteria['CriteriaName'];
			$i=0;
			$body = $criteriaDB->bodyCriteria($criteria['ACID']);
			$body = $body->toArray();
			$p = false;
			foreach($body as $crit)
			{
				$value = $assessedDB->getValue($aid,$crit['ACID'],$assessor,$uid);
				if($value !== null){
					$final[$x]['body'][$i] = array("id"=>$crit['ACID'],"name"=>$crit['CriteriaName'],"value"=>$value['value']);
					$i++;
					$p = true;
				}
			}
			if($p==false)
			{
				$x--;
			}			
			$x++;
		}
		$AssessmentDB = new Model_Assessment;
		$assess = $AssessmentDB->getAssessment($aid);
		$assess = $assess['AssessmentName'];
		//echo "<pre>"; print_r($player); exit;
		$this->view->assign("criteria",$final);
		$this->view->assign("aid",$senior);
		$this->view->assign("uid",$player);
		$this->view->assign("assess",$assess);
	}


	public function viewersAction()
	{
		$this->_helper->layout->disableLayout();
		$ProfileDB = new Model_Profile;
		$accessDB = new Model_TemplateAccess;
		$criteriaDB = new Model_Criteria;
		$assessdDB = new Model_Assessd; 
		$AssessmentDB = new Model_Assessments;
		 
		$request = $this->getRequest();
		$aid = $request->getParam("id");
		$uid = $request->getParam("uid");
		$assessor = $request->getParam("aid");
		
		$player = $ProfileDB->getPlayer($uid);
		$senior = $ProfileDB->getPerson($assessor);
		
		$asd = $assessdDB->getScore($aid,$uid,$assessor);
		$score = json_decode( $asd['AssessmentScores'],true );
		$com = json_decode( $asd['comments'],true );
		$filez= json_decode( $asd['Files'],true );
		//print_r( $player['DateOfBirth'] ); exit;
		//$files = $this->assessFiles->getFiles($aid,$uid,$assessor);
		
		$asmt = $AssessmentDB->getAssessment($aid);
		$ass = json_decode($asmt['Access'],true);
		$tmp = $asmt['TemplateID'];
		$age = $asmt['AgeGroup'];
		
		$to = $senior['FirstName'].' '.$senior['LastName'];
		$email = $senior['Email'];
		$event = $asmt['AssessmentName']; 
		$why = "Player";
		$who = $player['FirstName'].' '.$player['LastName'];
		//$this->email($to,$email,$event,$why,$who);
		
		$asss = array();
		$sep = "";
		foreach( $ass as $person )
		{			
			if( !in_array($person, $asss) && $person['aid'] == $assessor ){ $asss[] = $person; $heading[] = $person['cid']; }
		}
				
		$final = array();
		$x=0;
		if(!empty($heading)):
		foreach($heading as $head)
		{
			$criteria = $criteriaDB->nameCriteria($head);
			$criteria = $criteria->toArray();
			
			//if($age !== "senior")
			if( $tmp == 18 )
			{
				$scr = 0;
				$cm = "No Comment Available";
				$fyl = "No Files Available"; 
				foreach($score as $sc)
				{
					if($sc['CID'] == $head || $sc['criteriaID'] == $head)
					{
						if($sc['Value']){ $scr = $sc['Value']; }else{ $scr = $sc['value']; }
						
						if(!empty( $com ))
						{
							foreach($com as $comm)
							{
								if($comm['hid'] == $head || $comm['hid'] == $criteria['criteriaID']){ $cm = $comm['comm']; }
							}
						}
						if(!empty( $filez ) && sizeof($filez) > 3)
						{
							foreach($filez as $fl)
							{
								if($fl['hid'] == $head){ $fyl = '<a href="#" data-fl="'.$fl['fname'].'" data-id="'.$head.'" class="dlf" >'.$fl['fname'].'</a>'; }
							}
						}
					}
				}
				$final[$x]['head'] = array( "cid"=>$criteria['criteriaID'], "criteria"=>$criteria['CriteriaName'], "score"=>$scr, "comment"=>$cm, "files"=>$fyl );	
				$sep = "doing";
			}
			else 
			{
				$final[$x]['head'] = $criteria['CriteriaName'];
				$final[$x]['cid'] = $criteria['ACID'];
				$i=0;
				$body = $criteriaDB->bodyCriteria($criteria['ACID']);
				$body = $body->toArray();
				$ave = 0;
				$cm = "No Comment Available";
				$fyl = "No Files Available"; 
				foreach($body as $crit)
				{
					$scr = 0;	
					$fyl = "";				
					foreach($score as $sc)
					{
						//print_r($sc); exit;
						//print_r($crit); exit;						
						if($sc['CID'] == $crit['ACID'])
						{							
							$scr = $sc['Value'];
							
							if(!empty( $com ) && sizeof($com) > 3)
							{
								foreach($com as $comm)
								{
									if($comm['hid'] == $head){ $cm = $comm['comm']; }
								}
							}
							if(!empty( $filez ) && sizeof($filez) > 3)
							{
								foreach($filez as $fl)
								{
									if($fl['hid'] == $head){ $fyl .= $fl['fname']; }
								}
							}
						}
					}
					
					//$value = $this->assessedDB->getValue($aid,$crit['ACID'],$assessor,$uid);
					$final[$x]['body'][$i] = array("id"=>$crit['ACID'],"name"=>$crit['CriteriaName'],"value"=>$scr);
					$i++;
					$ave = $ave + $scr;
				}
				
				$ave = round(($ave / $i)*2,0)/2;
				$final[$x]['average'] = $ave;
				$final[$x]['comment'] = $cm;
				$final[$x]['files'] = $fyl; 
				$final[$x]['cnt'] = $i;
			}
			$x++;
		}
		endif;
		$this->view->assign("sep",$sep);
		$this->view->assign("criteria",$final);
		$this->view->assign("ass",$assessor);
		$this->view->assign("aid",$senior);
		$this->view->assign("uid",$player);
		$this->view->assign("userid",$uid);
		$this->view->assign("asid",$aid);
	}

	public function assessmentcAction()
	{
		//$this->_helper->viewRenderer->setNoRender();
		
		$this->_helper->layout->disableLayout(); 
		
		$ProfileDB = new Model_Profile;
		$accessDB = new Model_TemplateAccess;
		$criteriaDB = new Model_Criteria;
		$assessedDB = new Model_Assessed; 
		
		$request = $this->getRequest();
		$aid = $request->getParam("id");
		$uid = $request->getParam("uid");
		$assessor = $request->getParam("aid");
		
		$player = $ProfileDB->getPlayer($uid);
		$senior = $ProfileDB->getPerson($assessor);
				
		$access = $accessDB->myAccess($aid);
		$access = $access->toArray();
		
		$heading = array();
		foreach ($access as $me) 
		{
			$find = explode(',', $me['assessor']);
			foreach($find as $ass_id)
			{
				if($ass_id == $assessor)
				{
					$heading[] = $me['criteriaID'];
				}
			}
		}
		
		$final = array();
		$x=0;
		foreach($heading as $head)
		{
			$criteria = $criteriaDB->nameCriteria($head);
			$criteria = $criteria->toArray();
			
			$final[$x]['head'] = $criteria['CriteriaName'];
			$i=0;
			$body = $criteriaDB->bodyCriteria($criteria['ACID']);
			$body = $body->toArray();
			$p = false;
			foreach($body as $crit)
			{
				$value = $assessedDB->getValue($aid,$crit['ACID'],$assessor,$uid);
				if($value !== null)
				{
							$final[$x]['body'][$i] = array("id"=>$crit['ACID'],"name"=>$crit['CriteriaName'],"value"=>$value['value']);
							$i++;
							$p = true;
				}
			}
			
			
			
			if($p==false)
			{
							$x--;
			}			
							$x++;
		}
		$AssessmentDB = new Model_Assessment;
		$assess = $AssessmentDB->getAssessment($aid);
		$assess = $assess['AssessmentName'];
		//echo "<pre>"; print_r($player); exit;
		$this->view->assign("criteria",$final);
		$this->view->assign("aid",$senior);
		$this->view->assign("uid",$player);
		$this->view->assign("assess",$assess);
	}


public function scoutedexcelAction(){
			
			$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			if (PHP_SAPI == 'cli')
					die('This example should only be run from a Web Browser');
				
				/** Include PHPExcel */
				require_once  'Classes/PHPExcel.php';
				
				
				
			$request = $this->getRequest();
				
				$unionFilter = $request->getParam("unionid");
				
				@$order = $request->getParam("dir");
				@$column= $request->getParam("column");
					switch ($column) {
					case 1:
						$column = 'U.DateCreated';
						break;
					
						case 3:
						$column = 'U.FirstName';
						break;
						case 4:
						$column = 'T.PID';
						break;
						case 5:
						$column = 'U.Ranked';
						break;
						case 6:
						$column = 'U.Age';
						break;
						case 7:
						$column = 'U.Ethnicity';
						break;
						default:
						$column = 'U.DateCreated';
						break;
				}
					
					$column = 'U.Ranked';
			
				$searchSQL = null;
				@$search = $request->getParam("search");
				if($search){
					$searchSQL = $search;
				}
				
				$dbUsers = new Model_Profile;
		 		$list = $dbUsers->getAllScoutsPlayers($unionFilter,$scoutid,$order,$column);
				
				
				if($request->getParam("current")==1){
					
				
				$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
				$paginator->setCurrentPageNumber($request->getParam("page")+1);
				$paginator->setItemCountPerPage($request->getParam("length"));
				
						$list=$paginator;
				}
				
				// Create new PHPExcel object
				$objPHPExcel = new PHPExcel();
				
				// Set document properties
				$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
											 ->setLastModifiedBy("Maarten Balliauw")
											 ->setTitle("Office 2007 XLSX Test Document")
											 ->setSubject("Office 2007 XLSX Test Document")
											 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
											 ->setKeywords("office 2007 openxml php")
											 ->setCategory("Test result file");
				
				
				// Add some data
				$objPHPExcel->setActiveSheetIndex(0)
				            ->setCellValue('A1', '#')
										->setCellValue('B1', 'Full Name')
				            ->setCellValue('C1', 'Rank')
				            ->setCellValue('D1', 'Organisation')
				            ->setCellValue('E1', 'E-mail')
										->setCellValue('F1', 'Position')
										->setCellValue('G1', 'Mobile')
										;
				# 		 	 	 	 	Last Login
				// Miscellaneous glyphs, UTF-8
				$n =2;
				foreach ($list as $value) {
					$objPHPExcel->setActiveSheetIndex(0)
				            ->setCellValue('A'.$n, $n-1)
										->setCellValue('B'.$n, $value["Ranked"])
				            ->setCellValue('C'.$n, $value["FirstName"].' '.$value["LastName"])
				            ->setCellValue('D'.$n, $value["un_name"])
				            ->setCellValue('E'.$n, $value["Email"])
										->setCellValue('F'.$n, $value["Position"])
										->setCellValue('G'.$n, $value["Mobile"])
										;
										$n++;
				}
				
				
				// Rename worksheet
				$objPHPExcel->getActiveSheet()->setTitle('Simple');
				
				
				// Set active sheet index to the first sheet, so Excel opens this as the first sheet
				$objPHPExcel->setActiveSheetIndex(0);
				
				
				// Redirect output to a client’s web browser (Excel5)
				header('Content-Type: application/vnd.ms-excel');
				header('Content-Disposition: attachment;filename="01simple.xls"');
				header('Cache-Control: max-age=0');
				// If you're serving to IE 9, then the following may be needed
				header('Cache-Control: max-age=1');
				
				// If you're serving to IE over SSL, then the following may be needed
				header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
				header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
				header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
				header ('Pragma: public'); // HTTP/1.0
				
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
				$objWriter->save('php://output');
				exit;
		}

	public function berometerAction()
	{
		//$this->_helper->viewRenderer->setNoRender();
    	$this->_helper->layout->disableLayout();
				$request = $this->getRequest();
				$tid = $request->getParam("tid");
				
				$PositionDB = new Model_Positions;
			$llPosition = $PositionDB->getAll();
			
			$this->view->assign("Position",$llPosition);
			
			$n =1;
			$i =0;
			$arrayList = array();
			
			$arrayList["Demographics"]["African"] =0;
			$arrayList["Demographics"]["Coloured"] =0;
			$arrayList["Demographics"]["Indian"] =0;
			$arrayList["Demographics"]["White"] =0;
			foreach ($llPosition as $position) {
						
					
				$arrayList["List"][$i]["Position"]=$position["Position"];
				$arrayList["List"][$i]["PositionNumber"]=$position["PID"];
				
				
				$BeromiterDB = new Model_Berometer;
				//$players = $BeromiterDB->getByQuary("TID ='".$tid."' AND Pos ='".$n."' AND  Rank > 0");
				$players = $BeromiterDB->getByQuary("TID ='".$tid."' AND Pos ='".$n."' ");
				$p =0;
				
				foreach ($players as $player) {
					$db = new Model_Profile;
					$profile = $db->getProfileForPDF($player["ID"],$player["Pos"]);
					$arrayList["List"][$i]["Players"][$p]["FirstName"]=$profile["FirstName"];
					$arrayList["List"][$i]["Players"][$p]["LastName"]=$profile["LastName"];
					$arrayList["List"][$i]["Players"][$p]["DateOfBirth"]=$profile["DateOfBirth"];
					$arrayList["List"][$i]["Players"][$p]["Organisation"]=$profile["un_name"];
					$arrayList["List"][$i]["Players"][$p]["weight"]=$profile["weight"];
					$arrayList["List"][$i]["Players"][$p]["height"]=$profile["height"];
					$arrayList["List"][$i]["Players"][$p]["Ethnicity"]=$profile["Ethnicity"];
					$arrayList["List"][$i]["Players"][$p]["Rank"]=$player["Rank"];
					$arrayList["Demographics"][$profile["Ethnicity"]] = $arrayList["Demographics"][$profile["Ethnicity"]]+1;
					$p++;
				}
				$n++;
				
				$i++;
			}
/*
			
 */
 $TournDB = new Model_Tournament;
 $Tourn = $TournDB->fetchRow("TID ='".$tid."'");
 
		$this->view->assign("Data",$arrayList);	
		$this->view->assign("Tourn",$Tourn);	
		
	}


public function logsAction()
    {
    		
			//$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				
			 $tid = $request->getParam("tid");
			 
			 
			 $FixtureDB = new Model_Fixture;
				$data =$FixtureDB->getFixtures($tid)->toArray();
				
				foreach ($data as $fix) {
					if($fix["closed"]==1){
						$FixtureDB->setSquadByScore($fix["FID"]);
					}
					
				}
			 $TournDB = new Model_Tournament;
		$Tournament = $TournDB->fetchRow("TID ='".$tid."'");
		
		
			 $this->view->assign("Tournament",$Tournament);
			 
			 	$logsDB = new Model_TournamentLogs;
			
			$squadDB = new Model_Squad;
			 
			$Squads= $squadDB->fetchAll("TournamentID ='".$tid."'");
			$listArray = array();
			$i =0;
			foreach($Squads as $Squad){
				$States = $logsDB->getRow($Squad["TournamentID"],$Squad["SID"]);
				$listArray[$i]["ShortName"]		=	$Squad["ShortName"];
				$listArray[$i]["SID"]					=	$Squad["SID"];
				$listArray[$i]["Played"]			=	$States["Played"];
				$listArray[$i]["Won"]					=	$States["Won"];
				$listArray[$i]["Drow"]				=	$States["Drow"];
				$listArray[$i]["Lost"]				=	$States["Lost"];
				$listArray[$i]["Tries"]				=	$States["Tries"];
				$listArray[$i]["Convertions"]	=	$States["Convertions"];
				$listArray[$i]["DropGoals"]		=	$States["DropGoals"];
				$listArray[$i]["Penalty"]			=	$States["Penalty"];
				$listArray[$i]["PF"]					=	$States["PF"];
				$listArray[$i]["PA"]					=	$States["PA"];
				$listArray[$i]["PD"]					=	$States["PF"]-$States["PA"];
				
				$i++;
			}
			$this->array_sort_by_column($listArray, 'PD',SORT_DESC);
			$this->view->assign("Logs",$listArray);
			
				
			
		}


public function zipaccreAction(){
		$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        
        $request = $this->getRequest(); 
		$id = $request->getParam("id"); 
		
		
		require_once("dompdf/dompdf_config.inc.php");
        
		$http = "http";
		if( isset($_SERVER['HTTPS'] ) ) 
		{
            $http = "https";
        }
        $url = $http."://".$_SERVER["SERVER_NAME"]."/pdf/a6/id/".$id;
		
        $html = file_get_contents($url);
        $dompdf = new DOMPDF();
		
        $dompdf->load_html($html);
		
		$applydb = new Model_AccreditationsApplications;
	   
        $data = $applydb->getByID($id);
		
		$Zonedb = new Model_AccreditationList;
		$Zones = $Zonedb->getApplicationZones($data["AC"]);
	
                                  
                                
		$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");
       // 
       
       echo "<pre>";
	   print_r($data->toArray());
       
       // folder
       $folder = IMG_PATH."/accre/pdfs/";
	   $Accrefolder = $folder."/".$data["AC"];
	   if(!is_dir($Accrefolder)){
	   	 mkdir($Accrefolder);
	   	 
	   }
	   //Craete Category
	   $CategoryFolder = $Accrefolder."/".$data["Category"];
	   
	   if(!is_dir($CategoryFolder)){
	   	 mkdir($CategoryFolder);
	   	 
	   }
	   // if teams 
	   $TeamsFolder = $CategoryFolder."/".$data["SquadID"];
	   if($data["SquadID"]>0){
	   	 if(!is_dir($TeamsFolder)){
	   	 mkdir($TeamsFolder);
	   	 
	   	}
		 
		 $CategoryFolder = $TeamsFolder;
	   }
	   
	   
	   //ZipFOlder
	   
	   
	   file_put_contents($CategoryFolder."/".$data["FirstName"]."_".$data["Surname"].".pdf", $dompdf->output());
	   
	   
	   
	   // Get real path for our folder
$rootPath = $CategoryFolder;

// Initialize archive object
$zip = new ZipArchive();
$zip->open($Accrefolder.'/file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();
	   
	   
	   
	}

 public function getassessmentAction()
                {
                   		
                       
						$this->_helper->layout->disableLayout();
                        $request = $this->getRequest();
                        $fid = $request->getParam("fid");
						$uid = $request->getParam("uid");
						
						$AssoDb = new Model_RefereeAssessors;
						$Assor = $AssoDb->getRowByQuery("FID ='".$fid."' AND UID ='".$uid."'");
						$this->view->assign("Data",$Assor);
						
						$positionsDB = new Model_MatchOfficialPositions;
						$positions = $positionsDB->fetchAll();
						$ProfileDb = new Model_Profile;
						$MatchOfficials = json_decode($Assor["MatchOfficials"],true);
						$list_positions =array();
						if(count($positions)>0){
							$positions = $positions->toArray();
							foreach($positions as $position){
								$list_positions[$position["PID"]]= $position;
							}
						}
						
						
						
						
						$IDS = array();
						$Officials = array();
						if(count($MatchOfficials)>0){
							
							foreach($MatchOfficials as $MatchOfficial){
								$IDS[] = $MatchOfficial["ID"];
								$Officials[$MatchOfficial["ID"]]= $MatchOfficial;
							}
							
							
							
						}
						
						$posArray = array(1,3,4,7);
						$MatchOfficialsProfile = array();
						if(count($IDS)>0){
							$OfficialsProfile = $ProfileDb->getProfileByIds($IDS);
							if(count($OfficialsProfile)>0){
								$n =0;
								foreach ($OfficialsProfile as $Profile) {
									if(in_array($Officials[$Profile["UserID"]]["Pos"], $posArray)){
									$MatchOfficialsProfile[$Profile["UserID"]]["FullName"]= $Profile["FullName"];
									$MatchOfficialsProfile[$Profile["UserID"]]["Position"]=$list_positions[$Officials[$Profile["UserID"]]["Pos"]]["Position"] ;
									$MatchOfficialsProfile[$Profile["UserID"]]["Pos"]=$list_positions[$Officials[$Profile["UserID"]]["Pos"]]["PID"] ;
									$ModelDB = new Model_RefCrateria;
									$all = $ModelDB->fetchAll(" gr ='".$Officials[$Profile["UserID"]]["Pos"]."' ")->toArray();
									$MatchOfficialsProfile[$Profile["UserID"]]["Criteria"]=$all;
									$n++;
									}
								}
							}
						}
						
						$this->array_sort_by_column($MatchOfficialsProfile, "Pos");
						$this->view->assign("MatchOfficials",$MatchOfficialsProfile);
						
						$Assessments = json_decode($Assor["Assessment"],true);
						$criteria = array();
						foreach ($Assessments as $key=>$val) {
							$criteria[$key]=$val;
						}
						
						$this->view->assign("Criteria",$criteria);
					
			
						
                        
                        
              }

public function matchscoresheetAction()
    {
    	
		
		
    	//$this->_helper->viewRenderer->setNoRender();
      $this->_helper->layout->disableLayout();
	  	$FixtureTbl = new Model_Fixture;
		$SquadsTbl = new Model_Squad;
		$MatchReportTbl = new Model_MatchReport;
        $ProfileDB = new Model_Profile;
        $profileDB = new Model_Profile;
                
		$request = $this->getRequest();
		$sid =$request->getParam("sid");  
		$fid =$request->getParam("id");
                
                //GET SQUADS
        		$squad = $SquadsTbl->getSquadComp($sid);
				$this->view->assign("squad",$squad);
          //GET FIXTURE
                $Fixture = $FixtureTbl->getFixture($fid);
                
                $this->view->assign("fixture",$Fixture);
				
               $MatchOfficials = json_decode($Fixture["MatchOfficials"],true);
              
              
             
              
                //MATCH OFFICIALS
			$Officials = array();
			
			if(count($MatchOfficials)>0)
             {
             	
				foreach ($MatchOfficials as $p)
                {
                	if($p['ID']>0){
                		$player = $ProfileDB->getPlayerProfile($p['ID']);
						$Officials[] = array("UserID"=>$player['UserID'],"boksmart"=>$player['boksmart'],"Name"=>$this->clean($player['FirstName'])." ".$this->clean($player['LastName']));
					}
				}
			}
					
				
                $this->view->assign("Officials",$Officials);
				
				 //GET SQUADS
                 $squad = $SquadsTbl->getSquadComp($sid);
		$this->view->assign("squad",$squad);
                 
                 //GET FIXTURE
                $Fixture = $FixtureTbl->getFixture($fid);
                $this->view->assign("fixture",$Fixture);
                
                
                 $listHomeTeam =  json_decode($Fixture["TeamH"],true); 
				 $listAwayTeam =  json_decode($Fixture["TeamA"],true);  
               
                if(count($listHomeTeam)>0){
                   
                    
                    foreach($listHomeTeam as $player){
                        $getProfile = $profileDB->GetPlayersByPositions($player['ID'], $player['Pos']);
                        
                        
                        
                        $Cap ="";
                        if($player["Cap"]==1){
                        $Cap ="(C)";
                        }
                        $Vice ="";
                        if($player["Vice"]==1){
                        $Vice ="(V)";
                        }
                       
                        $homeTeam[$player['Pos']]["Cap"] = $Cap;
                        $homeTeam[$player['Pos']]["Vice"] = $Vice;
                        $homeTeam[$player['Pos']]["CapNo"] = $player["Cap"];
                        $homeTeam[$player['Pos']]["ViceNo"] = $player["Vice"];
                        $homeTeam[$player['Pos']]["UserID"] = $getProfile["UserID"];
                        $homeTeam[$player['Pos']]["INIT"] = $this->clean($getProfile["FirstName"])[0];
						$homeTeam[$player['Pos']]["FirstName"] = $getProfile["FirstName"];
						$homeTeam[$player['Pos']]["LastName"] = $getProfile["LastName"];
                        $homeTeam[$player['Pos']]["PostionNo"] = $player["Pos"];
                        $homeTeam[$player['Pos']]["Postion"] = (!empty($getProfile["POS"]))? $getProfile["POS"] : "POS: not assigned" ;
                        $homeTeam[$player['Pos']]["JerseyNumber"] = (!empty($player["Jersey"]))? $player["Jersey"] : 0;
						$homeTeam[$player['Pos']]["PID"] = $getProfile["PID"];	
                       	                         
                    }
                }
               
                if(count($listAwayTeam)>0){
                    
                    foreach($listAwayTeam as $player){
                        $getProfile = $profileDB->GetPlayersByPositions($player['ID'], $player['Pos']);
                        
                        $Cap ="";
                        if($player["Cap"]==1){
                        $Cap ="(C)";
                        }
                        $Vice ="";
                        if($player["Vice"]==1){
                        $Vice ="(V)";
                        }
                       
                        $AwayTeam[$player['Pos']]["Cap"] = $Cap;
                        $AwayTeam[$player['Pos']]["Vice"] = $Vice;
                        $AwayTeam[$player['Pos']]["CapNo"] = $player["Cap"];
                        $AwayTeam[$player['Pos']]["ViceNo"] = $player["Vice"];
                        $AwayTeam[$player['Pos']]["UserID"] = $getProfile["UserID"];
                        $AwayTeam[$player['Pos']]["Avatar"] = $PlayerPhoto["Thumb"];
                        $AwayTeam[$player['Pos']]["INIT"] = $this->clean($getProfile["FirstName"])[0];
						$AwayTeam[$player['Pos']]["FirstName"] = $getProfile["FirstName"];
						$AwayTeam[$player['Pos']]["LastName"] = $getProfile["LastName"];
                        $AwayTeam[$player['Pos']]["PostionNo"] = $player["Pos"];
                        $AwayTeam[$player['Pos']]["JerseyNumber"] = (!empty($player["Jersey"]))? $player["Jersey"] : 0;
						$AwayTeam[$player['Pos']]["PID"] = $getProfile["PID"];	
                                                  
													
                    }
                }
                $n=1;
                $blank = array();
                while($n<$squad["NumbersOfPlayers"]+1){
                    
                    $DB = new Model_Positions;
                    $POS = $DB->getRow($n);
                    
                    $blank[$n]["LastName"] = "Not Assigned";
                    $blank[$n]["JerseyNumber"] = 0;
                    $blank[$n]["Postion"] = $POS["Position"];
                    $n++;
                }
                
                if(count($homeTeam)==0){
                    $homeTeam=$blank;
                }
                if(count($AwayTeam)==0){
                    $AwayTeam=$blank;
                }
                
                $this->view->assign("Players",array("HomeTeam"=>$homeTeam,"AwayTeam"=>$AwayTeam));
                
			
				
			
              
	}


}
