<?php

date_default_timezone_set('Africa/Johannesburg');
class Union_MembersController extends Zend_Controller_Action
{

	protected $identity ;

    public function init()
    {
         
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
        {
        	
            $this->_redirect('/');
        }
        $user = $auth->getIdentity();
        $db = new Model_Profile;
        $this->identity = $db->getRow($user->UserID);
        if($this->identity->Status ==0){
            $this->_redirect('/first');
	}
        
        $this->view->assign("UserDetails",$this->identity->toArray());
        $this->view->assign("getControllerName",$this->getRequest()->getControllerName());
        $this->view->assign("getActionName",$this->getRequest()->getActionName());
		
    }
    
    
    public function indexAction()
    {
    	
		$DropDownarray = array(array("ID"=>1,"Text"=>"Players"),array("ID"=>2,"Text"=>"Personnel"));
    $this->view->assign("DropDown",$DropDownarray);   

	
		
		
		
		
		}
	


	public function profileAction()
	{
		$FixtureTbl = new Model_Fixture;
		$SquadsTbl = new Model_Squad;
		
		
		$InstTypeDB = new Model_OrganizationTypes;
		$Conditions = new Model_PlayersHistory;
	
		
		$DocumentsDB = new Model_Documents;
		
		
		$ProfileDB = new Model_Profile;
		$PositionsDB = new Model_Positions;
		$CountryDB = new Model_Country;
		$EthnicityDB = new Model_Ethnicity;
		$TitleDB = new Model_Title;
		$RelationDB = new Model_RelationshipStatus;
		
		$request = $this->getRequest();
		$id =$request->getParam("id");  
                
                if($this->identity->JobType ==2 && $this->identity->UserID !=$id){
                    $this->_redirect('/union/members/profile/id/'.$id);
                }
                
                
                
		$PlayerCareerDB = new Model_PlayerCareer;
		$PlayerCareer = $PlayerCareerDB->fetchRow("UserID ='".$id."'");
		$InstType = $InstTypeDB->getAll();
		$OrgType = 	$InstTypeDB->getTypes($id);
		/*
		$squads = json_decode($PlayerCareer["Squads"],true);
		$mySquads = array();
		foreach($squads as $squad){
		$mySquads[]=$squad;
		}
		*/
                		
		//Conditioning Info
		$Player_Condition = $Conditions->fetchRow($id);
		$jConditions = json_decode($Player_Condition["Condition"], true);
		$aConditions = array();
		foreach($jConditions as $cond){
		$aConditions[]=$cond;
		}
		
		//Country
		$Country = $CountryDB->getAll();
		//Accreditation
		$Accr = $ProfileDB->getAccredByID($id);
		//Title
		$Title = $TitleDB->getAll();
		//Relationship
		$RelStatus = $RelationDB->getAll();
		//Docs
		$Documents = $DocumentsDB->getForMember($id);
		//Get User Datails
		$UserProfile = $ProfileDB->getFullProfile($id);
                if($UserProfile["JobType"]==2){
   $posDB = new Model_Positions;
   $pos = $posDB ->getPosByPOS($UserProfile["p_code"],$UserProfile["Player_Prim_Pos"]);
   if(isset($pos["Position"])){
   $this->view->assign("POS",$pos["Position"]);
   }else{
       $this->view->assign("POS","N/A");
   }
   }
		//Get Positions 1-24
		$AllPos = $PositionsDB->getAll();
		//Ethnicity
		$Ethnicity = $EthnicityDB->getAll();
		
		$UserProfile["UserID"] = $id;
                
                $Edit =0;
                
                if($UserProfile["JobType"]!=2){
                    if($UserProfile["UserID"]==$this->identity->UserID)
                    {
                       $Edit= 1;
                    }
                    
                }else if($UserProfile["JobType"]==2 && $this->identity->UserID !=$UserProfile["UserID"])
                    {
                    
                    $ProfileSquads = json_decode($PlayerCareer["Squads"],true);
                   // print_r($ProfileSquads);
                    $this->view->assign("ProfileSquads",$ProfileSquads);
                    
                    $SquadsDB = new Model_Squad;
                    if(count($ProfileSquads)>0){
                        foreach($ProfileSquads as $ProfileSquad){
                            $mysquad = $SquadsDB->getCoaches($ProfileSquad["SID"]);
                            
                           
                            
                            if($mysquad){
                                $COACHES = json_decode($mysquad["Coaches"],true);
                               
                             if(count($COACHES)>0){
                                 foreach($COACHES as $COACHE){
                                     if($COACHE["ID"]==$this->identity->UserID)
                                        {
                                            $Edit= 1;
                                        }
                                 }
                             
                             }
                            }
                        }
                    }
                    
                   
                }else if($this->identity->UserID ==$UserProfile["UserID"]){
                    $Edit= 1;
                }
                
                
                
                
                
                
                
                
                
                $this->view->assign("EDIT",$Edit);
		//$this->view->assign("CurrrentSquad",$mySquads[count($mySquads)-1]);
		
		
		$this->view->assign("Profile",$UserProfile);
		$this->view->assign("getCareer",$PlayerCareer);
		$this->view->assign("Hist",@$mySquads);
		$this->view->assign("Positions", $AllPos);
		$Accred = $ProfileDB->getAccredByID($id);
		$this->view->assign("Accred", $Accred);
		$this->view->assign("InstType", $InstType);
		$this->view->assign("OrgType", $OrgType);
		$this->view->assign("PlayerCond", $aConditions);
		$this->view->assign("Country", $Country);
		$this->view->assign("Accr", $Accr);
		$this->view->assign("Title", $Title);
		$this->view->assign("RelStatus", $RelStatus);
		$this->view->assign("Documents", $Documents);
		$this->view->assign("Ethnicity", $Ethnicity);
                
               
                
                if($UserProfile["JobType"]==2){
                    
                    $this->_helper->viewRenderer('members/viewmyprofileplayer', null, true);
                }else{
                    $this->_helper->viewRenderer('members/viewmyprofile', null, true);
                }
                
                
	}

public function quickviewAction()
	{
               // $this->_helper->viewRenderer->setNoRender();
                $this->_helper->layout->disableLayout();
				$ProfileDB = new Model_Profile;
				$request = $this->getRequest();
                $id=$request->getParam("id");
                $sid=$request->getParam("sid");
				$UserProfile = $ProfileDB->getQuick($id);
                $SquadsTbl = new Model_Squad;
                $squad = $SquadsTbl->getSquad($sid);
                $EthnicityDB = new Model_Ethnicity;
                $Ethnicity = $EthnicityDB->getAll();
                $this->view->assign("Ethnicity", $Ethnicity);
		
                $PositionsDB = new Model_Positions;
				$AllPos = $PositionsDB->getPos($squad["RugbyCode"]);
                $this->view->assign("PositionsList", $AllPos);
                
                $Profile = $UserProfile->toArray();
                $this->view->assign("Profile", $Profile);
               
                
                
                
                $jsonData = json_decode($squad["Players"],true);
                
               // print_r($jsonData[$id]);
                $this->view->assign("SquadType", $squad["SquadType"]);
                $this->view->assign("SID", $squad["SID"]);
				$this->view->assign("SquadData", $squad);
		$this->view->assign("Squad", $jsonData[$id]);
		
                
		     
	}
   
        
  public function quickviewmemberAction()
	{
               // $this->_helper->viewRenderer->setNoRender();
                $this->_helper->layout->disableLayout();
		$ProfileDB = new Model_Profile;
		$request = $this->getRequest();
                $id=$request->getParam("id");
                $sid=$request->getParam("sid");
		$UserProfile = $ProfileDB->getQuick($id);
                
                $EthnicityDB = new Model_Ethnicity;
                $Ethnicity = $EthnicityDB->getAll();
                $this->view->assign("Ethnicity", $Ethnicity);
		
                $DB = new Model_UserType;
                $user_types = $DB->getForSquadsdrop();
                $this->view->assign("UsertTypes", $user_types);
                
                $Profile = $UserProfile->toArray();
                $this->view->assign("Profile", $Profile);
               
                $SquadsTbl = new Model_Squad;
                $squad = $SquadsTbl->getSquad($sid);
                
                
                $jsonData = json_decode($squad["Coaches"],true);
                
               // print_r($jsonData[$id]);
                $this->view->assign("SquadType", $squad["SquadType"]);
                $this->view->assign("SID", $squad["SID"]);
		$this->view->assign("Squad", $jsonData[$id]);
                
		     
	}      
        
 public function quickviewsaveAction()
	{
                $this->_helper->viewRenderer->setNoRender();
                $this->_helper->layout->disableLayout();
		$ProfileDB = new Model_Profile;
		$request = $this->getRequest();
                $id=$request->getParam("id");
                $sid=$request->getParam("sid");
		if($request->isPost()){
                    $data=$request->getParam("data");
                    $squadata=$request->getParam("squad");
                    
                    $ProfileDB->updateProfile($data, $id);
                    
                    $SquadsTbl = new Model_Squad;
                    $squad = $SquadsTbl->getSquad($sid);
                    $jsonData = json_decode($squad["Players"],true);
                    
                    $newPlayers = array();
                    
                    foreach($jsonData as $PLAYER){
                        if($PLAYER["ID"]!=$id){
                            $Captain = @$PLAYER["Captain"];
                            $Vice =@$PLAYER["Vice"];
                            if($squadata["Captain"]>0 && isset($squadata["Captain"]) ){
                                $Captain = 0;
                            }
                            if($squadata["Vice"]>0 && isset($squadata["Captain"]) ){
                                $Vice = 0;
                            }
                            
                            $newPlayers[$PLAYER["ID"]]["ID"]=$PLAYER["ID"];
                    $newPlayers[$PLAYER["ID"]]["Position"]=@$PLAYER["Position"];
                    $newPlayers[$PLAYER["ID"]]["Rank"]=@$PLAYER["Rank"];
                    $newPlayers[$PLAYER["ID"]]["Jersey"]=@$PLAYER["Jersey"];
                    $newPlayers[$PLAYER["ID"]]["Captain"]=$Captain;
                    $newPlayers[$PLAYER["ID"]]["Vice"]=$Vice;
                        }else{
                            $Jersey = @$PLAYER["Jersey"];
                           
                            $Rank = @$PLAYER["Rank"];
                            $Captain = 0;
                            $Vice =0;
                            if(isset($squadata["Jersey"])){
                                 $Jersey= $squadata["Jersey"];
                            }
                            if(isset($squadata["Rank"])){
                                $Rank = $squadata["Rank"];
                            }
                            if(isset($squadata["Captain"]) && $squadata["Captain"]>0){
                                $Captain = $squadata["Captain"];
                            }
                            if(isset($squadata["Vice"]) && $squadata["Vice"]>0){
                                $Vice = $squadata["Vice"];
                            }
                            $newPlayers[$id]["ID"]=$id;
                            $newPlayers[$id]["Position"]=$squadata["Positions"];
                            $newPlayers[$id]["Rank"]=$Rank;
                            $newPlayers[$id]["Jersey"]=$Jersey;
                            $newPlayers[$id]["Captain"]=$Captain;
                            $newPlayers[$id]["Vice"]=$Vice;
                        }
                    }
                    
                   
                    
                    $SquadsTbl->update(array("Players"=>json_encode($newPlayers,true)),"SID ='".$sid."'");
                    
                    $historyPlayerDb = new Model_PlayersHistory;
                    $historyPlayer = $historyPlayerDb->getHistory($id);
                    $errro ="";
                    if(isset($historyPlayer["UserID"])){
                        $History = json_decode($historyPlayer["History"],true);
                        
                         $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Updated this profile "); 
                         
                         $Details = json_decode($historyPlayer["Details"],true);
                         $Details[] = array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$data); 
                        $historyPlayerDb->updateData(array("History"=>  json_encode($History),"Details"=>  json_encode($Details)),$id);
                   $errro = "None";
                        
                        
                    }else{
                       
                         $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Updated this profile "); 
                         ;
                         $Details[] = array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$data); 
                        $historyPlayerDb->insertData(array("UserID"=>$id,"History"=>  json_encode($History),"Details"=>  json_encode($Details)));
                    
                    }
                  echo json_encode(array("OK"=>1,"ERROR"=>$errro));
                   $SquadsTbl = new Model_Squad;
           $SquadsTbl->updateSquad(array("DateModified"=> date("Y-m-d H:i:s")), $sid); 
                }
		     
	}       
    public function quickviewsavememberAction()
	{
                $this->_helper->viewRenderer->setNoRender();
                $this->_helper->layout->disableLayout();
		$ProfileDB = new Model_Profile;
		$request = $this->getRequest();
                
                $id=$request->getParam("id");
                $sid=$request->getParam("sid");
                
		if($request->isPost()){
                    $data=$request->getParam("data");
                    $squadata=$request->getParam("squad");
                    
                    $ProfileDB->updateProfile($data, $id);
                    
                    $SquadsTbl = new Model_Squad;
                    $squad = $SquadsTbl->getSquad($sid);
                    $jsonData = json_decode($squad["Coaches"],true);
                    $newList = array();
                    if(count($jsonData)>0){
                        foreach($jsonData as $d){
                            if($d["ID"]!=$id){
                                $newList[$d["ID"]]["ID"]=$d["ID"];
                                $newList[$d["ID"]]["Position"]=$d["Position"];
                            }else{
                               $newList[$id]["ID"]=$id;
                                $newList[$id]["Position"]=$squadata["Positions"]; 
                            }
                        }
                    }
                   
                    $SquadsTbl->update(array("Coaches"=>json_encode($newList,true)),"SID ='".$sid."'");
                    
                    $historyPlayerDb = new Model_PlayersHistory;
                    $historyPlayer = $historyPlayerDb->getHistory($id);
                    $errro ="";
                    if(isset($historyPlayer["UserID"])){
                        $History = json_decode($historyPlayer["History"],true);
                        
                         $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Updated this profile "); 
                         
                         $Details = json_decode($historyPlayer["Details"],true);
                         $Details[] = array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$data); 
                        $historyPlayerDb->updateData(array("History"=>  json_encode($History),"Details"=>  json_encode($Details)),$id);
                   $errro = "None";
                        
                        
                    }else{
                       
                         $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Updated this profile "); 
                         ;
                         $Details[] = array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$data); 
                        $historyPlayerDb->insertData(array("UserID"=>$id,"History"=>  json_encode($History),"Details"=>  json_encode($Details)));
                    
                    }
                  echo json_encode(array("OK"=>1,"ERROR"=>$errro));
                  $SquadsTbl = new Model_Squad;
           $SquadsTbl->updateSquad(array("DateModified"=> date("Y-m-d H:i:s")), $sid); 
                }
		     
	}      
        
public function uploadsAction()
    {
       //$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
				
				$id=$request->getParam("id");
				
                                $this->view->assign("UserID", $id);
                                
                                
                                $PlayerCareerDB = new Model_PlayerCareer;
		$PlayerCareer = $PlayerCareerDB->fetchRow("UserID ='".$id."'");
		
                
		if($this->identity->UserID ==1){
                    $ProfileSquads = json_decode($PlayerCareer["Squads"],true);
                   // print_r($ProfileSquads);
                    $this->view->assign("ProfileSquads",$ProfileSquads);
                   
                }
    }
public function passwordAction()
    {
   
				$request = $this->getRequest();
				$id = $this->identity->UserID;
				$this->view->assign("UserID",$id);
				
				$db = new Model_Profile;
				$dbC = new Model_Credentials;
				if($request->isPost()){
					$password = $request->getParam("pass");
					
					$save = $dbC->update(array("Password"=>md5($password)),"UserID ='".$id."'");
					$Data = $db->getRow($id)->toArray();
					$EmailContent = new PG_Controller_Plugin_EmailLayout;
					
					$EmailContent->EmailTemplate($Data["Email"],$id,1,4,$password);
								
					$this->_helper->viewRenderer->setNoRender();
      		$this->_helper->layout->disableLayout();
				}
		
	}
public function newmemberAction()
    {
       //$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
				
				$id=$request->getParam("id");
				$ProfileDB = new Model_GirProfile;
			
				//Get User Datails
		
		if($request->isPost()){
			$data=$request->getParam("data");
			//$ProfileDB->updateProfile($data,$id);
		}
		
		
		
		}

                
                public function updateAction()
    {
       
       @$this->view->assign("Back",$_SERVER['HTTP_REFERER']);
       
        $request = $this->getRequest();
				
				$id=$request->getParam("id");
				$ProfileDB = new Model_Profile;
		$PositionsDB = new Model_Positions;
			$CountryDB = new Model_Country;
			$EthnicityDB = new Model_Ethnicity;
			$TitleDB = new Model_Title;
		$RelationDB = new Model_RelationshipStatus;
		$InstTypeDB = new Model_OrganizationTypes;		
				//Get User Datails
		$UserProfile = $ProfileDB->getRow($id);
                
                $UserProfile["UserID"]=$id;
                
                 $Edit =0;
                
                if($UserProfile["JobType"]!=2){
                    if($id==$this->identity->UserID){
                       $Edit= 1;
                    }
                    
                }else if($UserProfile["JobType"]==2 && $this->identity->UserID !=$id){
                    
                    $PlayerCareerDB = new Model_PlayerCareer;
		$PlayerCareer = $PlayerCareerDB->fetchRow("UserID ='".$this->identity->UserID."'");
                    $ProfileSquads = json_decode($PlayerCareer["Squads"],true);
                   // print_r($ProfileSquads);
                    $this->view->assign("ProfileSquads",$ProfileSquads);
                    
                    $SquadsDB = new Model_Squad;
                    if(count($ProfileSquads)>0){
                        foreach($ProfileSquads as $ProfileSquad){
                            $mysquad = $SquadsDB->getCoaches($ProfileSquad["SID"]);
                            
                           
                               
                              
                        
                            
                            if(count($mysquad)>0){
                               
                                $Players= json_decode($mysquad["Players"],true);
                             if(count($Players)>0){
                                 
                                 
                                 foreach($Players as $Player){
                                     if($Player["ID"]==$id)
                                        {
                                            $Edit= 1;
                                        }
                                 }
                             
                             }
                            }
                        }
                        
                    }
                    
                   
                }else if($this->identity->UserID ==$UserProfile["UserID"]){
                    $Edit= 1;
                }
                
                
                
                
                if($Edit==0){
                   
                      
                        $this->_redirect('/union/members/profile/id/'.$UserProfile["UserID"]);
                    
                }
                
                
                
                $this->view->assign("EDIT",$Edit);
                
                
		$Country = $CountryDB->getAll();
		//Accreditation
		$Accr = $ProfileDB->getAccredByID($id);
		//Title
		$Title = $TitleDB->getAll();
		//Relationship
		//$RelStatus = $RelationDB->getAll();
		//Docs
		//Get Positions 1-24
		$AllPos = $PositionsDB->getAll();
		//Ethnicity
		$Ethnicity = $EthnicityDB->getAll();
		$RelStatus = $RelationDB->getAll();
		$this->view->assign("RelStatus", $RelStatus);
		
		$OrgType = 	$InstTypeDB->getTypes($id);
		$UserProfile["UserID"]=$id;
		$this->view->assign("Profile",$UserProfile);
				
				
		$this->view->assign("Positions", $AllPos);
		$this->view->assign("Accr", $Accr);
			$this->view->assign("Country", $Country);
		$this->view->assign("Title", $Title);
		$this->view->assign("Ethnicity", $Ethnicity);
		
		
		$this->view->assign("OrgType", $OrgType);
                
                
                $UnionsDb = new Model_Unions;
                
                $UnionsTypes = new Model_IntuitutionTypes;
		if($this->identity["UnionType"]== 12 || $this->identity["UnionType"] <3){
			
			
			$this->view->assign("listTypesUnions",$UnionsTypes->fetchAll("type_id >1 "));
		}else{
                        $this->view->assign("listTypesUnions",$UnionsTypes->fetchAll("type_id >2 AND type_id!=11"));
                       
		}
                $unions = $UnionsDb->getAllDropnew();
				 $this->view->assign("listUnions",$unions);
		$StatusDB = new Model_RelationshipStatus;
				$this->view->assign("StatusList",$StatusDB->getAll());
                                $RelationshipDB = new Model_Relationship;
				$this->view->assign("Relationship",$RelationshipDB->getAll());
		if($UserProfile["JobType"]==2){
                    
                    $this->_helper->viewRenderer('members/editmyprofileplayer', null, true);
                }else{
                    $this->_helper->viewRenderer('members/editmyprofile', null, true);
                }
        
        
    }
public function saveAction()
    {
       $this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
	$id=$request->getParam("id");
	$ProfileDB = new Model_Profile;
        if($request->isPost()){
            $Data = $request->getParam("data");
            $birth = $request->getParam("birth");
			
			$Data["DateOfBirth"] = date('d-m-Y',strtotime($birth["year"]."-".$birth["month"]."-".$birth["day"]));
			
		if(strlen($birth["year"])==2){
			$year = "20".$birth["year"];
			if($year>date("Y")){
				$year = "19".$birth["year"];
			}
			$Data["DateOfBirth"]= date("d-m-Y",strtotime($birth["year"]."-".$birth["month"]."-".$year));
		}	
			
			
           
           $Data["PassportExpireDate"] = date('Y-m-d',strtotime($birth["xyear"]."-".$birth["xmonth"]."-".$birth["xday"]));
           
           $Data['DateModified'] = date("Y-m-d H:s:i");
					$Data["FirstName"] =ucfirst($Data["FirstName"] );
					$Data["LastName"] =ucfirst($Data["LastName"] );
					$Data["FullName"] =ucfirst($Data["FirstName"] )." ".ucfirst($Data["LastName"] );
                                        
                                        if(empty($Data["NickName"])){
                                            $NickName = explode( " ", $Data["FirstName"]);
                                            $Data["NickName"] = $NickName[0];
                                        }
				$insert = $ProfileDB-> updateProfile($Data,$id);
					$dbCredentials = new Model_Credentials;
                                        $find = $dbCredentials->fetchRow("UserID ='".$id."'");
                                        if($find["UserID"] ==$id){
                                            $insertToDb = $dbCredentials->updateData(array("Username"=>$Data["Email"]),$id);
                                        }
					
        }
    }
    
  public function memberAction()
    {
       //$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
	$id=$request->getParam("id");
	$ProfileDB = new Model_Profile;
                                
                                if($request->isPost()){
                                    
                                    $this->_helper->viewRenderer->setNoRender();
                                    
                                    $this->_helper->layout->disableLayout();
                                    
                                    $Data = $request->getParam("data");
                                   
                                    $birth = $request->getParam("birth");
                                    if(isset($birth["year"]) && isset($birth["month"]) && isset($birth["day"])){
                                    	
                                    $Data["DateOfBirth"] = date('d-m-Y',strtotime($birth["year"]."-".$birth["month"]."-".$birth["day"]));
										
										
									if(strlen($birth["year"])==2){
			$year = "20".$birth["year"];
			if($year>date("Y")){
				$year = "19".$birth["year"];
			}
			$Data["DateOfBirth"]= date("d-m-Y",strtotime($birth["year"]."-".$birth["month"]."-".$year));
		}	
				
										
										
                                    }
                                    
                                    if(isset($birth["xyear"]) && isset($birth["xmonth"]) && isset($birth["xday"])){
                                    $Data["PassportExpireDate"] = date('Y-m-d',strtotime($birth["xyear"]."-".$birth["xmonth"]."-".$birth["xday"]));
                                    }
				
                                    $Data['Status']   =   1;
                                    $Data['DateModified']   =   date("Y-m-d H:s:i");
                                    $Data["FirstName"]      =   ucfirst($Data["FirstName"] );
                                    $Data["LastName"]       =   ucfirst($Data["LastName"] );
                                    $Data["FullName"]       =   ucfirst($Data["FirstName"] )." ".ucfirst($Data["LastName"] );
                                    $Data["modifiedBy"]=$this->identity->UserID; 
                                    $insert = $ProfileDB-> updateProfile($Data,$id);
                                    
                                    //$dbCredentials = new Model_Credentials;
                                    //$insertToDb = $dbCredentials->updateData(array("Username"=>$Data["Email"]),$id);
                                    
                                    $Age = $this->getage($Data["DateOfBirth"]);
                                    $mail = $Data["Email"];
                                    if($Age<19){
                                       $mail = $Data["parent_Email"]; 
                                    }
                                    	
                                    $historyPlayerDb = new Model_PlayersHistory;
                                $historyPlayer = $historyPlayerDb->getHistory($id);
                                $errro ="";
                                if(isset($historyPlayer["UserID"])){
                                    $History = json_decode($historyPlayer["History"],true);

                                     $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Updated this profile "); 

                                     $Details = json_decode($historyPlayer["Details"],true);
                                     $Details[] = array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$Data); 
                                    $historyPlayerDb->updateData(array("History"=>  json_encode($History),"Details"=>  json_encode($Details)),$id);
                               $errro = "None";


                                }else{

                                     $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Updated this profile "); 
                                     ;
                                     $Details[] = array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$Data); 
                                    $historyPlayerDb->insertData(array("UserID"=>$id,"History"=>  json_encode($History),"Details"=>  json_encode($Details)));

                                }
                                    $mail = trim($mail);
                                    $CredentialsDB = new Model_Credentials;
                
                                    $password = $this->getPassword();
                                    $CheckEmail = $CredentialsDB->fetchRow("Username='".$mail."' AND UserID !='".$id."'");
                                     $activeAccount =0;
                                    if($mail !="" && !isset($CheckEmail["UserID"])){
                                    try{
                                        $dataCre = array("Username"=>$mail,"Password"=>md5($password),"UserID"=>$id,"FPLogin"=>1);
                                        $CredentialsDB->insert($dataCre);
                                        $activeAccount =0;
                                        echo "Email Created";
                                    } catch (Exception $ex) {
                                        
                                        $CheckCre = $CredentialsDB->fetchRow("UserID='".$id."'");
                                        if($CheckCre["Username"] != $mail  ){
                                            $activeAccount =0;
                                            $dataCre = array("Username"=>$mail,"Password"=>md5($password),"UserID"=>$id,"FPLogin"=>1);
                                            $CredentialsDB->update($dataCre,"UserID='".$id."'");
                                            echo "Email Updated";
                                        }else{
                                           $activeAccount =1; 
                                        }
                                    }
                                    if($activeAccount==0){
                                            $PlayerCareerDB  = new Model_PlayerCareer;
                                            $PlayerCareer = $PlayerCareerDB->getRow($id);

                                            $SquadsLis = json_decode($PlayerCareer["Squads"],true);
                                            end($SquadsLis);         // move the internal pointer to the end of the array
                                           $key = key($SquadsLis);
                                           $squadDetails = $SquadsLis[$key];
                                           $sqddb = new Model_Squad;
                                           $SquadD = $sqddb->getSquad($squadDetails["SID"]);
                                           if($SquadD["SquadType"]<3){
                                         if($Age<19){  
                                            $EmailContent = new PG_Controller_Plugin_EmailLayout;
                                            $EmailContent->EmailTemplate2(15,$this->identity->UserID,$id,$squadDetails["SID"],$password);
                                         }else{
                                             $EmailContent = new PG_Controller_Plugin_EmailLayout;
                                            //$EmailContent->EmailTemplateAddedToSquad($mail,19,$id,$squadDetails["SID"],$password,$squadDetails["Pos"]);
                                         }
                                          
                                         
                                        echo "Email Sent";
                                         }
                                    }else{
                                        
                                    }
                                    }else{
                                        echo "Email Error";
                                    }
                                    
                                
                                }
                                
                                
		$UserTypeDB = new Model_UserType;
                $CountryDB = new Model_Country;
                $EthnicityDB = new Model_Ethnicity;
                $TitleDB = new Model_Title;
		$RelationDB = new Model_RelationshipStatus;
		$InstTypeDB = new Model_OrganizationTypes;		
				//Get User Datails
		$UserProfile = $ProfileDB->getRow($id);
		
		$Country = $CountryDB->getAll();
		//Accreditation
		$Accr = $ProfileDB->getAccredByID($id);
		//Title
		$Title = $TitleDB->getAll();
		//Relationship
		$RelStatus = $RelationDB->getAll();
		//Docs
		//Get Positions 1-24
		$AllPos = $UserTypeDB->getAll();
		//Ethnicity
		$Ethnicity = $EthnicityDB->getAll();
		$RelStatus = $RelationDB->getAll();
		
		$InstType = $InstTypeDB->getAll();
		$OrgType = 	$InstTypeDB->getTypes($id);
		$UserProfile["UserID"]=$id;
		$this->view->assign("Profile",$UserProfile);
		$this->view->assign("RelStatus", $RelStatus);
		$this->view->assign("Positions", $AllPos);
		$this->view->assign("Accr", $Accr);
		$this->view->assign("Country", $Country);
		$this->view->assign("Title", $Title);
		$this->view->assign("Ethnicity", $Ethnicity);
		$this->view->assign("InstType", $InstType);
		$this->view->assign("OrgType", $OrgType);
                
                $UnionsDb = new Model_Unions;
                
                $UnionsTypes = new Model_IntuitutionTypes;
		if($this->identity["UnionType"]== 12 || $this->identity["UnionType"] <3){
		$this->view->assign("listTypesUnions",$UnionsTypes->fetchAll("type_id >1 "));
		}else{
                $this->view->assign("listTypesUnions",$UnionsTypes->fetchAll("type_id >2 AND type_id!=11"));     
		}
                $unions = $UnionsDb->getAllDropnew();
		$this->view->assign("listUnions",$unions);
    }
    
    
    private function getPassword(){
			$alpha = "abcdefghijklmnopqrstuvwxyz";
			$alpha_upper = strtoupper($alpha);
			$numeric = "0123456789";
			$special = ".-+=_,!@$#*%<>[]{}";
			$chars = "";
			
			$chars = $alpha . $alpha_upper . $numeric;
			    $length = 7;
			$len = strlen($chars);
			$pw = '';
			 
			for ($i=0;$i<$length;$i++)
			        $pw .= substr($chars, rand(0, $len-1), 1);
			 
			// the finished password
			return $pw = str_shuffle($pw);

	}
    function getage($birthday)
	{
		if(!empty($birthday)){
			
		$birthday = date("Y-m-d",strtotime($birthday));
	     list($year,$month,$day) = explode("-",$birthday);
	     $year_diff  = date("Y") - $year;
	     $month_diff = date("m") - $month;
	     $day_diff   = date("d") - $day;
	     if ($day_diff < 0 && $month_diff==0){$year_diff--;}
	     if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
	     return $year_diff. ' ' . 'years old';
		}else{
			return "";
		}
	}
    
        public function uploadimageAction(){
			$this->_helper->viewRenderer->setNoRender();
      $this->_helper->layout->disableLayout();
			$request = $this->getRequest();
				$id = $request->getParam("id");
			if($request->isPost()){
				
				
				$IMGBASE64 = str_replace(" ", "+", $request->getParam("Avatar"));
						if(!empty($IMGBASE64)){
						$fileName = uniqid();
						
						$data = $IMGBASE64;
			 			list($type, $data) = explode(';', $data);
						list(, $data)      = explode(',', $data);
						$data = base64_decode($data);

						if(file_put_contents(IMG_PATH.'/'.$fileName.'.jpg', $data)){
						$imgDB = new Model_Images;
						$update = $imgDB->updateData(array("File"=>$IMGBASE64,"UserID"=>$id,"thumb"=>$this->thumbnail_data_uri(IMG_PATH.'/'.$fileName.'.jpg',100,100)),$id);
						if(!$update){
							$done = $imgDB->insertData(array("File"=>$IMGBASE64,"UserID"=>$id,"thumb"=>$this->thumbnail_data_uri(IMG_PATH.'/'.$fileName.'.jpg',100,100)));
	       			if($done){
	       				unlink(IMG_PATH.'/'.$fileName.'.jpg');
	       			}
						}else{
							unlink(IMG_PATH.'/'.$fileName.'.jpg');
						}
						
						
						}
					}
				
			}
				

}
 
function thumbnail_data_uri($filename,$width=0,$height=0) 
			{
			 
			 // Get Image Header Type
			      $image_info = getimagesize($filename);
			      $image_type = $image_info[2];
			
			 // Check the Size is Specified
			 if($width!=0 and $height!=0)
			 {
			      if( $image_type == IMAGETYPE_JPEG ) {
			         $image = imagecreatefromjpeg($filename);
			      } elseif( $image_type == IMAGETYPE_GIF ) {
			         $image = imagecreatefromgif($filename);
			      } elseif( $image_type == IMAGETYPE_PNG ) {
			         $image = imagecreatefrompng($filename);
			   imagealphablending($image, true);
			
			      } 
			
			 $new_image = imagecreatetruecolor($width, $height);
			 imagealphablending($new_image, false);
			 imagesavealpha($new_image, true);     
			      imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, imagesx($image),imagesy($image));
			      $image = $new_image; 
			   
			 ob_start();
			      if( $image_type == IMAGETYPE_JPEG ) {
			         imagejpeg($image);
			      } elseif( $image_type == IMAGETYPE_GIF ) {
			         imagegif($image);         
			      } elseif( $image_type == IMAGETYPE_PNG ) {
			         imagepng($image);
			      } 
			 $content=ob_get_clean();   
			   
			   
			 }else
			 $content=file_get_contents($filename,true);
			 
			 
			 
			 $base64 = base64_encode($content); 
			 return "data:$image_type;base64,$base64";
			}



public function editAction()
    {
       //$this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
				
				$id=$request->getParam("id");
				$ProfileDB = new Model_Profile;
		;
			$CountryDB = new Model_Country;
			
			$TitleDB = new Model_Title;
		$RelationDB = new Model_RelationshipStatus;
		$InstTypeDB = new Model_OrganizationTypes;		
				//Get User Datails
		$UserProfile = $ProfileDB->getRow($id);
		
		$Country = $CountryDB->getAll();
		//Accreditation
		$Accr = $ProfileDB->getAccredByID($id);
		//Title
		$Title = $TitleDB->getAll();
		//Relationship
		$RelStatus = $RelationDB->getAll();
		//Docs
                $EthnicityDB = new Model_Ethnicity;
                $Ethnicity = $EthnicityDB->getAll();
                $this->view->assign("Ethnicity", $Ethnicity);
		//Get Positions 1-24
                $PositionsDB = new Model_Positions;
		$AllPos = $PositionsDB->getAll();
                $this->view->assign("Positions", $AllPos);
		
		
		$RelStatus = $RelationDB->getAll();
		
		
		$OrgType = 	$InstTypeDB->getTypes($id);
		$UserProfile["UserID"]=$id;
		$this->view->assign("Profile",$UserProfile);
				
				$this->view->assign("RelStatus", $RelStatus);
		
		$this->view->assign("Accr", $Accr);
			$this->view->assign("Country", $Country);
		$this->view->assign("Title", $Title);
		
		
		
		$this->view->assign("OrgType", $OrgType);
                
                
                $UnionsDb = new Model_Unions;
                
                $UnionsTypes = new Model_IntuitutionTypes;
		if($this->identity["UnionType"]== 12 || $this->identity["UnionType"] <3){
			
			
			$this->view->assign("listTypesUnions",$UnionsTypes->fetchAll("type_id >1 "));
		}else{
                        $this->view->assign("listTypesUnions",$UnionsTypes->fetchAll("type_id >2 AND type_id!=11"));
                       
		}
                $unions = $UnionsDb->getAllDropnew();
				 $this->view->assign("listUnions",$unions);
		
		}




public function transferAction()
    {
    	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
				
				$id=$request->getParam("id");
    	
		}

public function gettableAction()
    {
       $this->_helper->viewRenderer->setNoRender();
      	$this->_helper->layout->disableLayout();
        $request = $this->getRequest();
				
				$type=$request->getParam("type");
				$columns = array( 
				// datatable column index  => database column name
						0 =>'U.LastName',
				    1 =>'PI.ReturnToTraining', 
				    3 => 'U.LastName',
				   	4=> 'T.Position',
				    5=> 'U.Ethnicity',
				    6=> 'U.height',
				    7=> 'U.weight'
				);
				$requestData= $_REQUEST;
				
					$unionID  =$this->identity->UnionID;
	if($this->identity->UnionType <3){
            $unionID  =0;
        }
	
		$db = new Model_Profile;
		
		
	
		$list = $db->getAllMembersUnion(strtoupper($requestData['order'][0]['dir']),$columns[$requestData['order'][0]['column']],$requestData['search']['value'],$unionID,$type );
		
		
		$total = count($list->toArray());
		
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list->toArray()));
		$paginator->setCurrentPageNumber(($requestData["start"]/$requestData["length"])+1);
		$paginator->setItemCountPerPage($requestData["length"]);
		
		
		$DataTable = $this->datatable($paginator,$requestData,$total);
		echo $DataTable;
				
			
		}
private function datatable($dataArray,$requestData,$total){
	
$data = array();
$i=1+$requestData['start'];





foreach( $dataArray as $row) {
	
	
	
	$status = '<div class="list-group-status status-online  " style="margin-top:-10px;"></div>';
if(isset($row["ReturnToTraining"]) ){
								if($row["ReturnToTraining"] <= date("Y-m-d")){
								$status = '<div class="list-group-status status-away  " style="margin-top:-10px;"></div>';
								}else{
									$status = '<div class="list-group-status status-online  " style="margin-top:-10px;"></div>';
								}
							}
	
	  //preparing an array
	  
	  
	  
	  
	  
	  
	  
    $nestedData=array(); 
    $nestedData[] = $i ;
		$nestedData[] = $status;
		$nestedData[] = '<img src="'.$row["Avatar"].'" width="30" style="float: left; margin-right: 20px" />';
		
 		$nestedData[] = '<a   data-toggle="tooltip" data-placement="top" title="View Profile"   href="/union/members/profile/id/'.$row["UserID"].'">'.$row['LastName'].", ".$row['FirstName'].'</a>';
		$nestedData[] = $row['Position'];
    $nestedData[] = $row['Ethnicity'];
		$nestedData[] = $row['height'];
 		$nestedData[] = $row['weight'];
		
		$nestedData[] = 0;//need to fix caps
		$nestedData[] = '<div class="btn-group">
                              <a href="#" data-toggle="dropdown" class="btn btn-default dropdown-toggle">
                              	<span class="fa fa-plus"></span>
                              <span class="caret"></span></a>
                              <ul class="dropdown-menu" role="menu" style="min-width: 0px;">
                                 <li><a href="#"    onclick="LoadOtherPage(\'/union/members/edit/id/'.$row["UserID"].'\')"><i class="fa fa-pencil"></i></a></li>
                                 <li><a href="#"><i class="fa fa-search"></i></a></li>
                                 <li><a href="/union/members/profile"><i class="fa fa-picture-o" ></i></a></li>
                                 <li><a href="#"><i class="fa fa-trash-o" ></i></a>
                                 </li>
                              </ul>
                           </div>';
   $data[] = $nestedData;
   $i++; 
	 
}
 
$json_data = array(
						
						"search" => $requestData["search"]["value"],
						"column" => $requestData["order"][0]["column"],	
						"dir" => intval( $requestData["order"][0]["dir"]),	
						"start" => intval( $requestData['start']),	
						"page" => intval( $requestData["start"]/$requestData["length"]),	
						
						"length" => intval( $requestData['length']),	
            "draw"            => intval( $requestData['draw']+1),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
            "recordsTotal"    => intval( $total ),  // total number of records
            "recordsFiltered" => intval( $total ), // total number of records after searching, if there is no searching then totalFiltered = totalData
            "data"            => $data   // total data array
            );
 
echo json_encode($json_data);  // send data as json format
}	






public function getmembersAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		
		$reQuest = $this->getRequest();
		if($reQuest->isPost()){
			
		//	$uid = $this->identity->UnionID; //change to this
		$uid = 1; 
		$type = $reQuest->getParam("type");
		}
		
	}
		
	
        function deletefileAction(){
            
            
            $this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		
		$reQuest = $this->getRequest();
                $UserID = $reQuest->getParam("id");
                $DID = $reQuest->getParam("did");
		if($reQuest->isPost()){
			
		$db = new Model_Documents;
                $file = $db->fetchRow("DID ='".$DID."'");
						 		
                 @unlink(UPLOADS_PATH."/documents/".$file["File"]);                                
		$db->delete("DID ='".$DID."'");
                    $historyPlayerDb = new Model_PlayersHistory;
                                $historyPlayer = $historyPlayerDb->getHistory($UserID);
                                $errro ="";
                                if(isset($historyPlayer["UserID"])){
                                    $History = json_decode($historyPlayer["History"],true);

                                     $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Delete the file (".$file["Title"].") from your profile "); 

                                    $historyPlayerDb->updateData(array("History"=>  json_encode($History)),$UserID);
                               $errro = "None";


                                }else{

                                      $History[] = array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$this->identity->FirstName." ".$this->identity->FirstName." Delete the file (".$file["Title"].") from your profile "); 
                                    $historyPlayerDb->insertData(array("UserID"=>$UserID,"History"=>  json_encode($History)));

                                }
                                
                }
        }
		
	public function checkidAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		
		$reQuest = $this->getRequest();
		if($reQuest->isPost()){
		$ProfileDB = new Model_Profile;	
		$id = $reQuest->getParam("id");
                $idNum = $reQuest->getParam("idNum");
                $Found = $ProfileDB->fetchAll("IDNumber ='".$idNum."' AND UserID !='".$id."'");
                
                    echo json_encode(array("found"=>count($Found)));
		
		}
		
	}	
}

