<?php
ini_set("memory_limit", "800M");

class MembersController extends Zend_Controller_Action {
	private $identity;
	private $AccessDB;
	private $AccessRights;

	public function init() {
		//$this->_helper->layout->disableLayout();
		$auth = Zend_Auth::getInstance();
		if (!$auth -> hasIdentity()) {
			$this -> _redirect('/login/');
		}

		setcookie('FootPrintApp', 'FootPrintApp', time() + 86400, '/');
		$user = $auth -> getIdentity();
		$this -> identity = $user;
		if ($this -> identity -> UnionType > 2) {

			if ($this -> identity -> Administrator == 1) {
			} else {
				$author = $db -> getRow($this -> identity -> author);
				if ($author["UnionType"] < 3) {
					$this -> _redirect('/union/first');
				} else {
					$this -> _redirect('/union/');
				}
			}
		}
		if ($this -> identity -> Status < 0) {
			$this -> _redirect('/first');
		}

		$this -> AccessRights = json_decode($this -> identity -> Role, true);
		$this -> view -> assign("AccessRoles", $this -> AccessRights);
		$this -> view -> assign("UserDetails", $this -> identity);
		$this -> view -> assign("getControllerName", $this -> getRequest() -> getControllerName());
		$this -> view -> assign("getActionName", $this -> getRequest() -> getActionName());
		$this -> AccessDB = new Model_AccessControl;

	}

	private function getInstitutionType() {

		$Instdb = new Model_IntuitutionTypes;
		$UnionsDB = new Model_Unions;
		//$union = $UnionsDB->GetUnion($this->identity->UnionID);

		$this -> view -> assign("Institution", $Instdb -> listInstByUserLogin($this -> identity));
		$this -> view -> assign("Unions", $UnionsDB -> listUnionsByUserLogin($this -> identity));

	}
	
	public function indexAction() {
		$this -> AccessControll();
		$request = $this -> getRequest();
		//list Unions
		$UnionsDB = new Model_Unions;
		$UnionsList = $UnionsDB -> listUnionsByUserLogin();
		$this -> view -> assign("Unions", $UnionsList);

		$unionID = 0;
		$uid = $request -> getParam("union");
		if ($uid) {
			$unionID = $uid;
		}
		$this -> view -> assign("unionID", $uid);
		if ($this -> identity -> Active == 0) {
			$this -> _redirect("/");
		}

		$this -> view -> assign("UnionType", $this -> identity -> UnionType);
		//List Types
		$IntuitutionTypesDB = new Model_IntuitutionTypes;
		$this -> view -> assign("UnionTypes", $IntuitutionTypesDB -> list_For_Table_Dropdown());
		//List User Types
		$JobTitleDB = new Model_UserType;
		$this -> view -> assign("TitleType", $JobTitleDB -> getAllTyopes());
	}
	
	public function profileAction() {
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$gir = $request -> getParam("gir");

		if ($gir == 1) {
			$UserProfileDB = new Model_GirProfile;
			$UserProfile = $UserProfileDB -> getFullProfile($id);

		} else {
			$UserProfileDB = new Model_Profile;
			$UserProfile = $UserProfileDB -> getFullProfileDetails($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");
			}
		}

		$this -> view -> assign("profile", $UserProfile);
		$Age = $UserProfile["Age"];
		$ShowTabs = array("Parent" => 0);
		if ($Age > 18) {
			$ShowTabs["Parent"] = 1;
		}
		$this -> view -> assign("ShowTabs", $ShowTabs);


		$ModelDB = new Model_Models;
		$this -> view -> assign("Models", $ModelDB -> fetchAll() -> toArray());
	

		//Roles
		$ROLES = json_decode($UserProfile["Role"], true);

		if (count($ROLES) > 0) {
			$this -> view -> assign("role", $ROLES);
		}

		//$this -> getPlayersCareer($id);
		//Get Careeer
		$SquadsDB = new Model_Squad;
		$UserSquad = $SquadsDB->GetMySquads_Of_User($id);
		$this -> view -> assign("Participations", $UserSquad);
		
		//$CurrentUserSquad = $SquadsDB->GetCurrent_Squads_Of_User($id);
		//$this -> view -> assign("CurrentSquads", $CurrentUserSquad);

		$FixturesDB = new Model_Fixture;
		//$UserFixtures = $FixturesDB->GetMyFixture($id);
		//$this -> view -> assign("MyFixtures", $UserFixtures);
		
	}

private function getPlayersCareer($id) {
		$DB = New Model_Profile;
		$SquadsDB = new Model_Squad;
		$Report = $DB -> getReport($id);
		$FixturesCareer = json_decode($Report["Json"], true);

		$SquadsHistory = json_decode($Report["Squads"], true);

		$FixtureList = array();
		$FixtureIDs = array();
		$SquadsIDs = array();
		if (count($FixturesCareer) > 0) {
			//if there are fixtures played show the career
			foreach ($FixturesCareer as $squad) {
				//for each squad show fixtures

				if (count($squad) > 0) {
					foreach ($squad as $fixture) {

						$FixtureList[$fixture["FID"]] = $fixture;
						$FixtureIDs[] = $fixture["FID"];
					}
				}
			}
		}
		if (count($SquadsHistory) > 0) {
			//if there are fixtures played show the career
			foreach ($SquadsHistory as $squad) {

				$SquadsIDs[] = $squad["SID"];

			}
		}

		if (count($FixtureIDs) > 0) {
			$FixtureReport = $DB -> getFixtures($FixtureIDs);

			$this -> view -> assign("Career", $FixtureReport -> toArray());
			$this -> view -> assign("GameStats", $FixtureList);

		}

		if (count($SquadsIDs) > 0) {

			$SquadParticipation = $SquadsDB -> getAllSquadsParticipation($SquadsIDs);
			$this -> view -> assign("Participation", $SquadParticipation);

		}

	}
	
	//////////////////////////   SORTED   ///////////////////////////


	public function addAction() {
		$this -> getInstitutionType();
		$EthnicityDB = new Model_Ethnicity;
		$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());

		$AccreditationsDB = new Model_Accreditation;
		$this -> view -> assign("AccreditationsList", $AccreditationsDB -> getAll());

		$CountryDB = new Model_Country;
		$this -> view -> assign("Country", $CountryDB -> getAll());

		$RelationshipDB = new Model_Relationship;
		$this -> view -> assign("Relationship", $RelationshipDB -> getAll());

		$ProvinceDB = new Model_Province;
		$this -> view -> assign("Province", json_encode($ProvinceDB -> getAll() -> toArray()));
		//$this->view->assign("Province",$ProvinceDB->getAll());

		$JobTitleDB = new Model_UserType;
		$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());

		$SportCodeDB = new Model_SportsCode;
		$this -> view -> assign("SportCode", $SportCodeDB -> getAll());

	}

	public function accountAction() {
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$UserProfileDB = new Model_Profile;
		$UserProfile = $UserProfileDB -> getFullProfile($id);

		if ($UserProfile["JobType"] == 2) {
			$posDB = new Model_Positions;
			$pos = $posDB -> getPosByPOS($UserProfile["p_code"], $UserProfile["Player_Prim_Pos"]);

			$this -> view -> assign("POS", $pos["Position"]);
		}

		$this -> view -> assign("profile", $UserProfile);
		$Age = $this -> age($UserProfile["DateOfBirth"]);
		$ShowTabs = array("Parent" => 0);
		if ($Age > 18) {
			$ShowTabs["Parent"] = 1;
		}
		$this -> view -> assign("ShowTabs", $ShowTabs);

		$SquadsDB = new Model_Squad;
		$Squads = $SquadsDB -> getUserSessionSquads($id);

		$this -> view -> assign("SquadsThisSession", $Squads);

		$ModelDB = new Model_Models;
		$this -> view -> assign("Models", $ModelDB -> fetchAll() -> toArray());

		//Roles
		$ROLES = json_decode($UserProfile["Role"], true);

		if (count($ROLES) > 0) {
			$this -> view -> assign("role", $ROLES);
		}

	}

	

	

	public function mysquadsAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$SquadsDB = new Model_Squad;
		echo $year = date("Y");
		$Squads = $SquadsDB -> getUserSessionSquadsByYear($id, $year);
		print_r($Squads);
	}

	public function loadprofileAction() {
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$page = $request -> getParam("page");
		$UserProfileDB = new Model_Profile;
		$UserProfile = $UserProfileDB -> getFullProfile($id);
		$this -> view -> assign("profile", $UserProfile);

		$CountryDB = new Model_Country;
		$this -> view -> assign("Country", $CountryDB -> getAll());

		if ($page == "personaldetails") {
			$EthnicityDB = new Model_Ethnicity;
			$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());
			$RelationshipDB = new Model_Relationship;
			$this -> view -> assign("Relationship", $RelationshipDB -> getAll());
			$StatusDB = new Model_RelationshipStatus;
			$this -> view -> assign("StatusList", $StatusDB -> getAll());
		}

		if ($page == "contactsdetails") {
			$ProvinceDB = new Model_Province;
			$this -> view -> assign("Province", $ProvinceDB -> getAll());
			$CityDB = new Model_Cities;
			$this -> view -> assign("City", $CityDB -> getAllData());

		}
		if ($page == "organisationdetails") {
			$this -> getInstitutionType();
			$JobTitleDB = new Model_UserType;
			$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());
			$SportCodeDB = new Model_SportsCode;
			$this -> view -> assign("SportCode", $SportCodeDB -> getAll());

			$PositionDB = new Model_Positions;
			$this -> view -> assign("Positions", $PositionDB -> getPos(15));

			$this -> view -> assign("SevensPositions", $PositionDB -> getPos(7));

		}
		if ($page == "guardian") {
			$RelationshipDB = new Model_Relationship;
			$RelStatus = $RelationshipDB -> getAll();
			$this -> view -> assign("RelStatus", $RelStatus);
		}

		/*
		 $AccreditationsDB = new Model_Accreditation;
		 $this->view->assign("AccreditationsList",$AccreditationsDB->getAll());

		 */

		$this -> _helper -> viewRenderer('members/profile/' . $page, null, true);
	}

	function age($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;
	}

	public function newmemberAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$data["data"] = $request -> getParam("data");
		$birth["birth"] = $request -> getParam("birth");
		$data["data"]["PassportExpireDate"] = $birth["birth"]["xyear"] . "-" . $birth["birth"]["xmonth"] . "-" . $birth["birth"]["xday"];

		$data["data"]["DateOfBirth"] = date("d-m-Y", strtotime($birth["birth"]["day"] . "-" . $birth["birth"]["month"] . "-" . $birth["birth"]["year"]));

		if (!empty($data["data"]["DateOfBirth"])) {
			$data["DateOfBirth"] = date("d-m-Y", strtotime($data["data"]["DateOfBirth"]));
			$dateOfbirth = explode("-", $data["data"]["DateOfBirth"]);
			if (strlen($dateOfbirth[2]) == 2) {
				$year = "20" . $dateOfbirth[2];
				if ($year > date("Y")) {
					$year = "19" . $dateOfbirth[2];
				}
				$data["data"]["DateOfBirth"] = date("d-m-Y", strtotime($dateOfbirth[0] . "-" . $dateOfbirth[1] . "-" . $year));
			}
		}
		

		$data["data"]["boksmartExpiryDate"] = $birth["birth"]["byear"] . "-" . $birth["birth"]["bmonth"] . "-" . $birth["birth"]["bday"];
		if (empty($data["data"]["NickName"])) {
			$data["data"]["NickName"] = $data["data"]["LastName"];
		}
		if ($data["data"]["ClubID"] =="") {
			$data["data"]["ClubID"] = 0;
		}
		if ($data["data"]["SocietyID"] =="") {
			$data["data"]["SocietyID"] = 0;
		}
		if ($data["data"]["JobType"] ==2) {
			$data["data"]["JobTitle"] = 0;
		}
		
		$data["data"]["author"] = $this->identity->UserID;
		$data["data"]["DateCreated"] = date("Y-m-d H:i:s");
		$UserProfileDB = new Model_Profile;
		$UserProfile = $UserProfileDB -> insert($data["data"]);
		$response = array("OK" => 1);
		if ($UserProfile > 0) {
			$response = array("OK" => 0, "ID" => $UserProfile);
		}

		echo json_encode($response);
	}

	public function saveaccountAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$data = $request -> getParam("data");
		$id = $request -> getParam("id");

		$UserProfileDB = new Model_Profile;

		$data["Email"] = preg_replace('/\s+/', '', $data["Email"]);
		if (!empty($data["DateOfBirth"])) {
			$data["DateOfBirth"] = date("d-m-Y", strtotime($data["DateOfBirth"]));
			$dateOfbirth = explode("-", $data["DateOfBirth"]);
			if (strlen($dateOfbirth[2]) == 2) {
				$year = "20" . $dateOfbirth[2];
				if ($year > date("Y")) {
					$year = "19" . $dateOfbirth[2];
				}
				$data["DateOfBirth"] = date("d-m-Y", strtotime($dateOfbirth[0] . "-" . $dateOfbirth[1] . "-" . $year));
			}
		}
		if ($data["ClubID"] =="") {
			$data["ClubID"] = 0;
		}
		if ($data["SocietyID"] =="") {
			$data["SocietyID"] = 0;
		}
		if ($data["JobType"] ==2) {
			$data["JobTitle"] = 0;
		}
		foreach ($data as $key=>$value) {
			if($value==""){
				unset($data[$key]);
			}
		}

		$UserProfile = $UserProfileDB -> updateProfile($data, $id);

		$response = array("OK" => 1);
		if ($UserProfile > 0) {
			$response = array("OK" => 0, "ID" => $UserProfile);
		}

		if (isset($data["Email"])) {

			$DB = new Model_Profile;
			$profile = $DB -> getUsername($id);
			if (isset($profile["CID"])) {

				if ($profile["Email"] != $profile["Username"]) {
					//save email
					$pcDB = new Model_Credentials;
					$save = $pcDB -> updateData(array("Username" => $data["Email"]), $id);
				}

			}
		}

		echo json_encode($response);
	}

	public function transferdetailsAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$id = $this -> getRequest() -> getParam("id");
		$DB = new Model_TransferRequest();
		$data = $DB -> getRequest($id);
		echo "<p>A transfer request was made by:" . $data["AuthorFname"] . " " . $data["AuthorLname"] . "</p>";
		echo "<p>To transfer (" . $data["FirstName"] . " " . $data["LastName"] . ") from  " . $data["FromUnion"] . " to " . $data["ToUnion"] . "</p>";
		echo "<p>To transfer this account to the new organisation, please click the transfer now button!</p>";
	}

	public function transfernowAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$id = $this -> getRequest() -> getParam("id");
		$status = $this -> getRequest() -> getParam("status");
		$DB = new Model_TransferRequest();
		$data = $DB -> getRequest($id);
		if ($status == 10) {
			$DB -> updateData(array("Status" => 10, "DateCompleted" => date("Y-m-d H:i:s"), "CompletedBy" => $this -> identity -> UserID), $id);
			echo "<p>The transfer request was succesfully deleted </p>";
		} elseif ($status == 2) {
			$DB -> updateData(array("Status" => 2, "DateCompleted" => date("Y-m-d H:i:s"), "CompletedBy" => $this -> identity -> UserID), $id);
			echo "<p>The transfer request was succesfully declined </p>";
		} else {

			$ProfileDb = new Model_Profile;
			$Profile = $ProfileDb -> updateProfile(array("UnionID" => $data["ToUnionID"], "UnionType" => $data["ToUnionType"]), $data["UserID"]);
			$DB -> updateData(array("Status" => 0, "DateCompleted" => date("Y-m-d H:i:s"), "CompletedBy" => $this -> identity -> UserID), $id);
			echo "<p>The account was succesfully transfered to the new Organisation</p>";
		}
	}

	public function getmembersAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$unionFilter = $request -> getParam("unionid");
		$type = $request -> getParam("type");
		$title = $request -> getParam("title");
		$role = $request -> getParam("role");
		if ($this -> identity -> UnionType > 2 && ($unionFilter == 0 || $unionFilter == "")) {
			$unionFilter = $this -> identity -> 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 (@strlen($search) > 0) {
			$searchSQL = $search;
		}
		if ($this -> identity -> JobTitle == 55) {
			$title = 8;
		}
		if($title ==2){
			$role=0;
		}
		$dbUsers = new Model_Profile;
		$list = $dbUsers -> listUsers($order, $column, $searchSQL, $unionFilter, $type, $title, $role);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list -> toArray()));
		$paginator -> setCurrentPageNumber(($_GET["start"] / $_GET["length"]) + 1);
		$paginator -> setItemCountPerPage($_GET["length"]);

		$this -> datatable($paginator, $_GET, count($list -> toArray()));

	}

	private function datatable($dataArray, $requestData, $total) {

		$data = array();
		$i = 1 + $requestData['start'];
		foreach ($dataArray as $row) {

			$c = ",";
			if ($i == 0) {
				$c = "";
			}
			$green = '';
			if ($data["CID"] > 0) {
				$row = 'green';
			}

			$action = '';
			$link = '';
			if (isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"]["edit"])) {
				//$action ='<a  target="_blank" class="btn tipb" href="/'.$this->getRequest()->getControllerName().'/edit/id/'.$row["UserID"].'/"  data-placement="top" title="Edit" ><span class=isw-edit></span></a>';
			}

			$action .= '<a   class="btn tipb"  id="' . $row["UserID"] . '" onclick="Quickview(this)"  data-placement="top" title="View" ><span class=isw-zoom></span></a>';

			if (isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"]["profile"])) {
				$link = ' target="_blank" href="/' . $this -> getRequest() -> getControllerName() . '/profile/id/' . $row["UserID"] . '"';
				$action .= '<a  target="_blank" href="/' . $this -> getRequest() -> getControllerName() . '/profile/id/' . $row["UserID"] . '/" class="btn tipb" title="Profile" ><span class=isw-picture></span></a>';
			}
			if (isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"]["delete"])) {
				$action .= '<a  class="btn-danger tipb"  id="' . $row["UserID"] . '" onclick="delete_acc(this)"  data-placement="top" title="Delete"><span class=isw-delete></span></a>';
			}
			$link_Company = "";
			if (isset($this -> AccessRights["organisations"]["Actions"]["profile"])) {
				$link_Company = " href='/organisations/view/id/" . $row['un_id'] . "'";
			}
			//preparing an array

			
			$nestedData = array();
			$nestedData[] = $i;
			$nestedData[] = '<a ' . $link . ' > ' . $this -> string_clear($row["FirstName"]) . ' ' . $this -> string_clear($row["LastName"]) . '</a>';
			$nestedData[] = "<a target='_blank' " . $link_Company . " >" . $row['un_name'] . "</a>";
			$nestedData[] = $this -> string_clear($row['Email']);
			$nestedData[] = $row["TypeName"];
			$nestedData[] = $this -> string_clear($row['Mobile']);
			$nestedData[] = $row['LastLogin'];
			$nestedData[] = '<span class=buttons>' . $action . '</span>';
			$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

	}

	function string_clear($string) {
		if (empty($string)) {
			return "N/A";
		} else {
			return strtoupper($string);
		}
	}

	function clean($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.
	}

public function updateleagueAction() {
		//$this->AccessControll();

		$this->_helper->viewRenderer->setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		if($request->isPost()){
			$option = $request -> getParam("opt");
			$id = $request -> getParam("id");
			$data["UserID"] = $id;
			if($option==1){
				$data["LeagueID"] = $request -> getParam("lid");
			}
			if($option==2){
				$data["PanelID"] = $request -> getParam("pid");
			}
			$dbUsers = new Model_Profile;
			$dbUsers->updateProfile($data,$id);
		}
}
	public function getmemberAction() {
		//$this->AccessControll();

		//$this->_helper->viewRenderer->setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$id = $request -> getParam("id");

		$dbUsers = new Model_Profile;
		$member = $dbUsers -> getRow($id);
		$member["UserID"] = $id;
		$UnionID = $member["un_id"];
		if($member["un_type"]>3){
			$UnionID = $member["parentid"];
		}
		$avator = $member["Avatar"];
		if (!$member["Avatar"]) {
			$member["Avatar"] = "/img/user_default.jpg";
		}
		$this -> view -> assign("member", $member);
		$this -> view -> assign("access_Role", $this -> AccessRights);
		$this -> view -> assign("listleague", $this -> listleagues($UnionID));
		
		$DB = new Model_Panels;
		$Panels = $DB->getAllData();
		$this -> view -> assign("Panels",$Panels);

	}
	
	public function listleagues($id)
	{
		

		$DB = new Model_SocietyStructures;
		$list = $DB->getAllData();
		$Union = new Model_UnionSocietyStructures;
		$Structs = $Union->getAllDataByUnion($id);
		$Structs_list =array();
		if(count($Structs)>0){
			foreach ($Structs as $Struct) {
				$Structs_list[$Struct["STID"]]=$Struct->toArray();
			}
		}
		$dataList = array();
		if(count($list)>0){
			$n =0;
			foreach ($list as $data) {
	
				$dataList[$n]["Structure"]=$data["Name"];
				$dataList[$n]["STID"]=$data["STID"];
				$dataList[$n]["Position"]=$data["Position"];
				$dataList[$n]["USID"]=($Structs_list[$data["STID"]]["USID"])?:"";
				$dataList[$n]["UID"]=($Structs_list[$data["STID"]]["UID"])?:"";
				$dataList[$n]["Name"]=($Structs_list[$data["STID"]]["Name"])?:"";
				$n++;
			}
		}
		
		return $dataList;
	}

	

	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);

	}

	public function passwordAction() {

		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$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 editAction() {
		$this -> AccessControll();
		$request = $this -> getRequest();

		$id = $request -> getParam("id");
		if ($this -> identity -> Active == 0 && $id != $this -> identity -> UserID) {
			$this -> _redirect("/");
		}

		$this -> view -> assign("UserID", $id);

		$dbprofile = new Model_Credentials;
		$db = new Model_Profile;
		$profile = $dbprofile -> fetchRow("UserID ='" . $id . "'");
		if ($request -> isPost()) {
			$Data = $request -> getParam("data");
			$birth = $request -> getParam("birth");
			$Data["DateOfBirth"] = date('Y-m-d', strtotime($birth["year"] . "-" . $birth["month"] . "-" . $birth["day"]));
			$Data["PassportExpireDate"] = date('Y-m-d', strtotime($birth["exyear"] . "-" . $birth["exmonth"] . "-" . $birth["exday"]));

			$this -> view -> assign("profile", $Data);

			$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"]);

			$insert = $db -> updateProfile($Data, $id);
			$dbCredentials = new Model_Credentials;
			$insertToDb = $dbCredentials -> updateData(array("Username" => $Data["Email"]), $id);
			if ($insert) {

				$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( 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("/IMGS/" . $fileName . '.jpg');
							}
						} else {
							unlink("/IMGS/" . $fileName . '.jpg');
						}

					}
				}
				$allowLogin = $request -> getParam("allowLogin");

				$allowLogin = $request -> getParam("allowLogin");

				if ($allowLogin && !$profile['CID']) {
					$password = $this -> getPassword();

					$dbCredentials = new Model_Credentials;
					$insertToDb = $dbCredentials -> insertData(array("Username" => $Data["Email"], "Password" => md5($password), "UserID" => $insert));
					if ($insertToDb) {

						$EmailContent = new PG_Controller_Plugin_EmailLayout;

						$EmailContent -> EmailTemplate($Data["Email"], $id, 1, 2, $password);

						$this -> _redirect('/members/profile/id/' . $id);
					}
				}

				$this -> _redirect('/members/profile/id/' . $id);
			}
		}

		//GET DETAILS
		$profile = $db -> getRow($id);

		$this -> view -> assign("profile", $profile);

		$InstityTypeDB = new Model_IntuitutionTypes;
		$this -> view -> assign("InstityType", $InstityTypeDB -> getAllForPlayers());

		$UnionsDB = new Model_Unions;
		$this -> view -> assign("Unions", json_encode($UnionsDB -> getAll() -> toArray()));

		$EthnicityDB = new Model_Ethnicity;
		$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());

		$StatusDB = new Model_RelationshipStatus;
		$this -> view -> assign("StatusList", $StatusDB -> getAll());

		$AccreditationsDB = new Model_Accreditation;
		$this -> view -> assign("AccreditationsList", $AccreditationsDB -> getAll());

		$TitleDB = new Model_Title;
		$this -> view -> assign("Title", $TitleDB -> getAll());

		$CountryDB = new Model_Country;
		$this -> view -> assign("Country", $CountryDB -> getAll());

		$RelationshipDB = new Model_Relationship;
		$this -> view -> assign("Relationship", $RelationshipDB -> getAll());

		$ProvinceDB = new Model_Province;
		$this -> view -> assign("Province", json_encode($ProvinceDB -> getAll() -> toArray()));
		//$this->view->assign("Province",$ProvinceDB->getAll());

		$JobTitleDB = new Model_UserType;
		$this -> view -> assign("TitleType", $JobTitleDB -> getAllNoPlayers(0) -> toArray());
		$this -> view -> assign("TitleTypeJson", json_encode($JobTitleDB -> getAll() -> toArray()));

		$this -> view -> assign("CodesList", json_encode(array( array("Text" => "--Select--", "Number" => "0"), array("Text" => "Rugby 15", "Number" => "15"), array("Text" => "Rugby 7", "Number" => "7"))));
	}

	public function uploadimageAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		echo $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');
					}

				}
			}

		}

	}

	public function profileoldAction() {
		$this -> AccessControll();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");

		if ($this -> identity -> Active == 0 && $id != $this -> identity -> UserID) {
			//$this->_redirect("/");
		}

		$this -> view -> assign("UserID", $id);
		$db = new Model_Profile;

		$profile = $db -> getRow($id);
		$this -> view -> assign("profile", $profile);
		if ($profile["JobType"] == 2) {

			//$this->_redirect('/players/profile/id/'.$id);
		}
		$UserDB = new Model_Credentials;
		$ModelDB = new Model_Models;

		$this -> view -> assign("Models", $ModelDB -> fetchAll() -> toArray());

		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$data = $request -> getParam("data");
			$model = $request -> getParam("model");

			$MID = 0;
			$roleArray = array();
			$i = 0;
			foreach ($model as $value) {

				$val = explode("|", $value["MID"]);

				$roleArray[$val[0]]["Actions"][$val[1]] = $val[1];
				$i++;
			}

			$data["Rule"] = json_encode($roleArray);
			//$data["Rule"]= $roleArray;
			$data["Author"] = $this -> identity -> UserID;
			$id = $AccessDB -> updateData($data, $id);

			if ($id > 0) {
				$this -> _redirect('/accesscontrol/edit/id/' . $id);
			}
		}

		$row = $UserDB -> fetchRow("UserID ='" . $id . "'");
		//print_r($row);
		//exit;
		$this -> view -> assign("role", json_decode($row["Role"], true));
		$career = new Model_PlayerCareer;

		$profileCarreer = $career -> getRow($id);

		$Squads = json_decode($profileCarreer["Squads"], true);
		$SquadsList = array();
		if (count($Squads) > 0) {
			foreach ($Squads as $Squad) {
				$SquadsBD = new Model_Squad;
				if (isset($Squad["SID"]) && $Squad["SID"] > 0) {
					$detals = $SquadsBD -> getMySquadsByTournByYear($Squad["SID"]);
					if ($detals) {
						$SquadsList[$Squad["SID"]] = $detals -> toArray();
					}
				}

			}
		}
		if ($this -> identity -> UserID == 1) {
			//print_r($SquadsList);
		}
		$this -> view -> assign("Squads", $SquadsList);

		////Assessment data
		$this -> condition();
		//$arr = $condition;
		//print_r($last);

	}

	public function condition() {
		//$this->_helper->viewRenderer->setNoRender();
		//$this->_helper->layout->disableLayout();
		//echo "<pre>";
		$vals = new Model_Condition;
		$Assessment = new Model_Assessments;
		$criteriaDB = new Model_Criteria;
		$assessments = new Model_PlayersHistory;
		$assessments = $assessments -> getHistory(1205);

		$all = json_decode($assessments['Condition'], true);
		$age = 'senior';
		$values = $vals -> getOne($age, 1);

		$ant = json_decode($values['Anthropometry'], true);
		$power = json_decode($values['Power'], true);
		$str = json_decode($values['Strength'], true);
		$me = json_decode($values['MuscleEndurance'], true);
		$speed = json_decode($values['Speed'], true);
		$af = json_decode($values['AnaerobicFitness'], true);
		$bt = json_decode($values['BleepTest'], true);

		$myID = $this -> identity -> UserID;

		$asesment = $Assessment -> getAssessment(291);
		$heading = array();
		$access = json_decode($asesment['Access'], true);

		$last = end($all);
		$html = '<table style="width:100%;" class="table table-striped"><thead><tr><th></th><th>Norm</th><th>Score</th><th>Rating</th></tr></thead><tbody>';

		foreach ($access as $crit) {
			if ($crit['aid'] == $myID) {
				$heading[] = $crit['cid'];
			}
		}

		//$res = array();
		$child = array();
		foreach ($heading as $head) {
			$criterias = $criteriaDB -> nameCriteria($head);
			//$res[] = array( "cid"=>$head,"name"=>$criterias['CriteriaName'] );
			$html .= '<tr><td><b>' . $criterias['CriteriaName'] . '</b></td>';
			$childs = "";
			$injury = "";

			$children = $criteriaDB -> bodyCriteria($head) -> toArray();
			foreach ($children as $body) {
				//$child[] = array( "bid"=>$body['ACID'],"cid"=>$head,"name"=>$body['CriteriaName'] );
				//$html .= '<tr><td style="padding-left:20px;">'.$body['CriteriaName'].'</td><td></td><td></td><td></td></tr>';
				foreach ($last['Content'] as $see => $seen) {
					$norm = "N/A";
					$rate = "";
					$sees = $body['CriteriaName'];
					$sees = str_replace(" ( cm )", "", $sees);
					$sees = str_replace(" ( mm )", "", $sees);
					$sees = str_replace(" ( kg )", "", $sees);
					$sees = str_replace("Skinfold ", "", $sees);
					$sees = str_replace(" of 7", "", $sees);

					$see = str_replace(" ( cm )", "", $see);
					$see = str_replace(" ( mm )", "", $see);
					$see = str_replace(" ( kg )", "", $see);
					$see = str_replace("Skinfold ", "", $see);
					$see = str_replace(" of 7", "", $see);

					if ($see == $sees) :
						if (!empty($ant)) :
							foreach ($ant as $wow => $dam) :
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen < $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen > $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						if (!empty($power)) :
							foreach ($power as $wow => $dam) :
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen > $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen < $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						if (!empty($str)) :
							foreach ($str as $wow => $dam) :
								$wow = str_replace(" ( kg )", "", $wow);
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen >= $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen < $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						if (!empty($me)) :
							foreach ($me as $wow => $dam) :
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen < $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen > $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						if (!empty($speed)) :
							foreach ($speed as $wow => $dam) :
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen < $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen > $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						if (!empty($af)) :
							foreach ($af as $wow => $dam) :
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen > $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen < $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						if (!empty($bt)) :
							foreach ($bt as $wow => $dam) :
								if ($wow == $see) :
									$norm = $dam['High'];
									if ($seen > $norm) {
										$rate = '<label class="label label-success">Excellent</label>';
									} elseif ($seen < $norm) {
										$rate = '<label class="label label-important">Unacceptable</label>';
									} else {
										$rate = '<label class="label label-warning">Acceptable</label>';
									}
									break;
								endif;
							endforeach;
						endif;

						$childs .= '<tr><td style="padding-left:20px;">' . $body['CriteriaName'] . '</td><td>' . $norm . '</td><td>' . $seen . '</td><td>' . $rate . '</td></tr>';
					elseif ($see == $criterias['CriteriaName']) :
						$injury = "Injured";
					endif;
				}
			}
			$html .= '<td></td><td>' . $injury . '</td><td></td></tr>';
			$html .= $childs;
		}

		$html .= '</tbody></table>';
		$this -> view -> assign('html', $html);
	}

	public function submitrolesAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		if ($request -> isPost()) {
			$Roles = $request -> getParam("model");
			$DATAr = $request -> getParam("data");

			$roleArray = array();

			foreach ($Roles as $value) {

				$val = explode("|", $value["MID"]);

				$roleArray[$val[0]]["Actions"][$val[1]] = $val[1];
				$i++;
			}
			$data["RoleSet"] = 1;

			$data["ScoutCoord"] = 0;
			$data["Scout"] = 0;
			//scout
			$data["NationCoord"] = 0;
			//nationalcoordinator
			$data["FPLogin"] = 0;
			//FPLogin
			$data["EFLogin"] = 0;
			//EFLogin
			$data["Administrator"] = 0;
			//EFLogin
			if ($DATAr["Administrator"] == 1) {
				$data["Administrator"] = 1;
			}
			if ($DATAr["FPLogin"] == 1) {
				$data["FPLogin"] = 1;
			}
			if ($DATAr["EFLogin"] == 1) {
				$data["EFLogin"] = 1;
			}

			if ($roleArray["scout"]["Actions"]["coordinator"] == "coordinator") {
				$data["ScoutCoord"] = 1;

			}
			if ($roleArray["scout"]["Actions"]["scout"] == "scout") {
				$data["Scout"] = 1;

			}
			if ($roleArray["scout"]["Actions"]["nationalcoordinator"] == "nationalcoordinator") {
				$data["NationCoord"] = 1;

			}
			echo "Yes" . $roleArray["scout"]["Actions"]["coordinator"];

			$data["Role"] = json_encode($roleArray);
			$UserDB = new Model_Credentials;
			$save = $UserDB -> updateData($data, $id);

			//$data["Rule"]= $roleArray;
			//$data["Author"]= $this->identity->UserID;

		}

	}

	public function deleteAction() {
		$this -> AccessControll();
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$db = new Model_Profile;

		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$user = $db -> fetchRow("UserID ='" . $id . "'");

		if ($user["JobType"] == 2) {
			$controller = "/members/players/";
		} else {
			$controller = "/members/";
		}

		if (!$id) {
			$this -> _redirect($controller);
		}

		$dbC = new Model_Credentials;
		$dbC -> delete("UserID ='" . $id . "'");
		$row = $db -> delete("UserID ='" . $id . "'");

		$this -> _redirect($controller);

	}

	public function delete2Action() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$db = new Model_Profile;

		$request = $this -> getRequest();
		$id = $request -> getParam("id");

		@$row = $db -> delete("UserID ='" . $id . "'");

	}
	
	private function notEmpty($value,$default){
		if(empty($value) || $value =="undefined"){
			return $default;
		}else{
			return $value;
		}
		
	}

	public function pdfAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		require_once ("dompdf/dompdf_config.inc.php");
		$request = $this -> getRequest();
$page = $this->notEmpty($request -> getParam("page"),0);
$type = $this->notEmpty($request -> getParam("type"),0);
$title = $this->notEmpty($request -> getParam("title"),0);
$role = $this->notEmpty($request -> getParam("role"),0);
$start = $this->notEmpty($request -> getParam("start"),0);
$length = $this->notEmpty($request -> getParam("length"),0);
$search = $this->notEmpty($request -> getParam("search"),"");
$column = $this->notEmpty($request -> getParam("column"),0);
$unionid = $this->notEmpty($request -> getParam("unionid"),0);
$current = $this->notEmpty($request -> getParam("current"),0);
$dir = $request -> getParam("dir");


		 $url = "http://" . $_SERVER["SERVER_NAME"] . "/pdf/print/page/" . $page .
		"/type/" . $type .
		"/title/" . $title.
		"/role/" . $role .
		 "/start/" . $start .
		  "/length/" . $length .
		   "/search/" . $search .
		    "/column/" . $column . 
		    "/unionid/" . $unionid . 
		    "/current/" . $current . 
		    "/dir/" . $dir;

		  $html = file_get_contents($url);
		

		$dompdf = new DOMPDF();
		$dompdf -> load_html($html);
		$dompdf -> set_paper('a4', $request -> getParam("orientation"));
		$dompdf -> render();
		$dompdf -> stream("Members.pdf");

	}

	private function updateEmailContent($Data) {
		return $content = '<html><head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">  <meta content="width=device-width, initial-scale=1.0" name="viewport">    
        <title></title>
        <body style="podding:0;margin:0;background:#8D8D8D; ">
        <div style="text-align:center; background:#8D8D8D; ">
        <table style="width:580px; margin:auto; background:#FFFFFF; text-align:left">
        <tr>
                <td><img src="http://saruefiling.com/img/EFiling_email.jpg"></td>
        </tr>
        <tr>
                <td style="padding:20px; color:#212121">
                <h3>Hello ' . $Data["FirstName"] . ' ' . $Data["LastName"] . '</h3>
        <p>This email is to notify you that you login details has been changed by ' . $this -> identity -> FirstName . '  ' . $this -> identity -> FirstName . '  at ' . date("Y-m-d H:i:s") . '</p>
        

       
        <p>
        We suggest you take a few minutes to familiarise yourself with the footprint.net <a href="http://www.footprint.net" style="color:#034f7f">sitemap</a>, including our <a href="http://www.footprint.net" style="color:#034f7f">Terms and Conditions</a>, so you can utilize the site\'s full potential.
        </p>
        <p>
        Please add support@footprint.net and info@footprint.net to your safe sender list, as this is the address Footprint will use to communicate with you. Please remember that your information is safe with us and will not be distributed to any third parties.
        </p>
        If you have any questions or comments please feel free to contact us at any time to hear a friendly voice! <br /><br />
        Kind regards,<br />
        Footprint Team
                </td>
        </tr>
        </table>
        </div>
        </body>
        </html>';
	}

	private function passwordEmailContent($Data, $password) {
		return $content = '<html><head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">  <meta content="width=device-width, initial-scale=1.0" name="viewport">    
        <title></title>
        <body style="podding:0;margin:0;background:#8D8D8D; ">
        <div style="text-align:center; background:#8D8D8D; ">
        <table style="width:580px; margin:auto; background:#FFFFFF; text-align:left">
        <tr>
                <td><img src="http://saruefiling.com/img/EFiling_email.jpg"></td>
        </tr>
        <tr>
                <td style="padding:20px; color:#212121">
                <h3>Hello ' . $Data["FirstName"] . ' ' . $Data["LastName"] . '</h3>
        <p>This email is to notify you that your account details has changed. Your account was updated by  ' . $this -> identity -> FirstName . '  ' . $this -> identity -> FirstName . '  at ' . date("Y-m-d H:i:s") . '</p>
        <h3>New Login Details</h3>
				<p>
         <strong>Username: </strong>' . $Data["Email"] . '	<br />
        <strong>Password: </strong>	' . $password . ' <br /><br />
        </p> 
       
        
        <p>
       Please add support@footprintapp.net and info@footprintapp.net to your safe sender list, as this is the address Footprint will use to communicate with you. Please remember that your information is safe with us and will not be distributed to any third parties.
       </p>
        If you have any questions or comments please feel free to contact us at any time to hear a friendly voice! <br /><br />
        Kind regards,<br />
        Footprint Team
                </td>
        </tr>
        </table>
        </div>
        </body>
        </html>';
	}

	private function newaccountEmailContent($Data, $password) {
		return $content = '<html><head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">  <meta content="width=device-width, initial-scale=1.0" name="viewport">    
        <title></title>
        <body style="podding:0;margin:0;background:#8D8D8D; ">
        <div style="text-align:center; background:#8D8D8D; ">
        <table style="width:580px; margin:auto; background:#FFFFFF; text-align:left">
        <tr>
                <td>FootprintApp</td>
        </tr>
        <tr>
                <td style="padding:20px; color:#212121">
                <h3>Hello ' . $Data["FirstName"] . ' ' . $Data["LastName"] . '</h3>
        <p>Welcome, and thank you for registering with Footprint, our exclusive, Union-facing website!  </p>
        You can now log into your  profile at <a href="http://www.footprintapp.net" style="color:#034f7f">http://www.footprintapp.net/login/</a> and complete your profile using the login details below:<br />
        <p>
         <strong>Username: </strong>' . $Data["Email"] . '	<br />
        <strong>Password: </strong>	' . $password . ' <br /><br />
        </p> 

        <p>
        Note that your Password is case sensitive. You should log in to <a href="http://http://www.footprintapp.net" style="color:#034f7f"http://www.footprintapp.net</a> and change the automatically assigned Password shown above to something you can remember.<br>
        </p>
        <p>
        We suggest you take a few minutes to familiarise yourself with the footprintapp.net <a href="http://www.footprintapp.net" style="color:#034f7f">sitemap</a>, including our <a href="http://www.footprint.net" style="color:#034f7f">Terms and Conditions</a>, so you can utilize the site\'s full potential.
        </p>
        <p>
        Please add support@footprint.net and info@footprint.net to your safe sender list, as this is the address Footprint will use to communicate with you. Please remember that your information is safe with us and will not be distributed to any third parties.
        </p>
        If you have any questions or comments please feel free to contact us at any time to hear a friendly voice! <br /><br />
        Kind regards,<br />
        Footprint Team
                </td>
        </tr>
        </table>
        </div>
        </body>
        </html>';
	}

	public function savecopeidAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$id = $request -> getParam("id");
			$data = $request -> getParam("Copy");
			$Name = $request -> getParam("Name");
			//$data = str_replace('data:image/png;base64,', '', $Image);
			/*$data = str_replace(' ', '+', $data);
			 $data = base64_decode($data);
			 $file = UPLOADS_PATH.'/'. uniqid().strrchr($Name, '.');;
			 $success = file_put_contents($file, $data);
			 $data = $Name;
			 $data = str_replace(' ', '+', $data);
			 list($type, $data) = explode(';', $data);
			 list(, $data)      = explode(',', $data);
			 $data = base64_decode($data);
			 $file = UPLOADS_PATH.'/'. uniqid().strrchr($Name, '.');;
			 file_put_contents($file, $data);

			 */

			$file = UPLOADS_PATH . '/' . uniqid() . strrchr($Name, '.');

			$data = str_replace('data:image/png;base64,', '', $data);
			$data = str_replace(' ', '+', $data);
			$data = base64_decode($data);

			$success = file_put_contents($file, $data);
			print $success ? $file : 'Unable to save the file.';
		}
	}

	public function activateAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$login = $request -> getParam("login");
		$reset = $request -> getParam("reset");
		$db = new Model_Profile;
		if ($request -> isPost()) {

			$UserDB = new Model_Credentials;
			if ($login == 1) {
				echo "Goo";
				$profile = $db -> getRow($id);
				$password = $this -> getPassword();

				$data = array("Username" => $profile["Email"], "Password" => md5($password), "UserID" => $id, "FPLogin" => 1);

				$update = $UserDB -> update($data, "UserID ='" . $id . "'");
				if (!$update) {
					$create = $UserDB -> insertData($data);
				}

				$EmailContent = new PG_Controller_Plugin_EmailLayout;

				$EmailContent -> EmailTemplate($profile["Email"], $id, 1, 1, $password);
			} else if ($reset == 1) {

				echo "Goo";
				$profile = $db -> getRow($id);
				$password = $this -> getPassword();

				$data = array("Username" => $profile["Email"], "Password" => md5($password), "UserID" => $id);

				$update = $UserDB -> update($data, "UserID ='" . $id . "'");
				if (!$update) {
					$create = $UserDB -> insertData($data);
				}
				$ProfileDB = new Model_Profile;
				$ProfileDB -> updateProfile(array("Status" => 0), $id);
				$EmailContent = new PG_Controller_Plugin_EmailLayout;
				$EmailContent -> EmailTemplate($Data["Email"], $insert, 1, 1, $password);
			} else {

				$profile = $db -> getRow($id);
				$saved = $db -> update(array("Active" => 1), "UserID ='" . $id . "'");
				$EmailContent = new PG_Controller_Plugin_EmailLayout;
				$EmailContent -> EmailTemplate($profile["Email"], $id, 1, 5, "");
			}

		}
	}

	public function resetaccountAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");

		$reset = $request -> getParam("reset");
		$db = new Model_Profile;
		if ($request -> isPost()) {

			$UserDB = new Model_Credentials;
			if ($reset == 1) {

				echo "Goo";
				$profile = $db -> fetchRow("UserID ='" . $id . "'");
				$password = $this -> getPassword();

				$dataNew = array("Password" => md5($password), "UserID" => $id);

				$update = $UserDB -> fetchRow("UserID ='" . $id . "'");
				if (isset($update)) {
					$update = $UserDB -> update($dataNew, "UserID ='" . $id . "'");

				}

				$db -> updateProfile(array("Status" => 0, "Active" => 0), $id);
				$EmailContent = new PG_Controller_Plugin_EmailLayout;

				$EmailContent -> EmailTemplate($profile["Email"], $id, 1, 1, $password);
			}

		}
	}

	public function deactivateAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");

		$db = new Model_Profile;
		if ($request -> isPost()) {
			$saved = $db -> update(array("Active" => 0), "UserID ='" . $id . "'");

		}
	}

	public function roleAction() {
		$AccessDB = new Model_AccessControl;
		$UserDB = new Model_Credentials;
		$ModelDB = new Model_Models;

		$request = $this -> getRequest();
		$id = $request -> getParam("id");

		if ($request -> isPost()) {

			$model = $request -> getParam("model");

			$MID = 0;
			$roleArray = array();
			$i = 0;
			foreach ($model as $value) {

				$val = explode("|", $value["MID"]);

				$roleArray[$val[0]]["Actions"][$val[1]] = $val[1];
				$i++;
			}

			$data["Role"] = json_encode($roleArray);
			$data["RoleSet"] = 1;

			//$data["Rule"]= $roleArray;

			$id = $UserDB -> updateData($data, $id);

			$this -> view -> assign("profile", $data);
			if ($id > 0) {
				//$this->_redirect('/members/profile/id/'.$id);
			}
		}
		$this -> view -> assign("UserID", $id);

		$User = $UserDB -> fetchRow("UserID ='" . $id . "'");
		$row = $AccessDB -> fetchRow("CID ='" . $User["RID"] . "'");
		$this -> view -> assign("profile", $row);

		$this -> view -> assign("Models", $ModelDB -> getAll(1) -> toArray());
		$this -> view -> assign("role", json_decode($User["Role"], true));

	}

	private function AccessControll() {
		$array = array("profile", "edit");
		$Action = $this -> getRequest() -> getActionName();
		if ($Action == "getmember") {
			$Action = "profile";
		}
		if (in_array($this -> getRequest() -> getActionName(), $array)) {
			$request = $this -> getRequest();
			$id = $request -> getParam("id");
			if ($this -> identity -> UserID != $id) {

				if (!isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"][$Action])) {
					$this -> _redirect("/");
				}
			}
		} else {
			if (!isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"][$Action])) {
				$this -> _redirect("/");
			}

		}
	}

	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 getmbrsAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("id");
		$search = $request -> getParam("search");
		$db = new Model_Profile;
		$members = $db -> getAllAjax($uid, $search);
		$list = array();
		$Response = array();
		if (count($members) > 0) {
			foreach ($members as $data) {
				if ($data["UserID"] > 0 && $data["FirstName"] != "") {
					$firatname = $data["Nickname"];
					if (empty($firatname)) {
						$firatname = $data["FirstName"];
					}
					$list[] = '<li style="height: 18px; clear: both;overflow: hidden" did="' . $data["UserID"] . '" class="SelectecUser" onclick="SelectecUser(this)" ><span class="pull-left name">' . $firatname . ', ' . $data["LastName"] . '</span> <span class="icon-ok pull-right" style="display: none"></span></li>';
				}
			}
			$Response = array("OK" => 1, "DATA" => $list);
		} else {

			$list[] = '<li style="height: 18px; clear: both;overflow: hidden"  ><span class="pull-left name">No Results</span> </li>';
			$Response = array("OK" => 0, "DATA" => $list);
		}
		echo json_encode($Response);
	}

	public function getmbrAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("id");
		$sid = $request -> getParam("sid");

		$pos = $request -> getParam("pos");

		$db = new Model_Profile;
		$dbSquads = new Model_Squad;
		$poDB = new Model_Positions;

		$squad = $dbSquads -> fetchRow("SID ='" . $sid . "'");

		$allpos = $poDB -> getPos($squad["RugbyCode"]);

		$member = $db -> getPlayersDetails($uid, $pos, $squad["RugbyCode"]);
		$pic = 'data:2;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9+zRmkzRmgBc0ZpM0ZoAXNGaTNGaAFzRSZozQAuaM0maM0ALmjNJmjNAC5opM0UANzRmkzRmgBc0ZpMijIoAXNQy3UUJwzc+g5qC9ujH+7Q/MRyfQVmZJJJoA1BqMRPIYfhU6XEUn3XBPpWJQDg5FAHQZozVO0u/N+R/vjofWreaAFzRmkyKMigBc0UmaKAGUUlGaAFozxSUdsUAY0jl5WY85NNpWXa7D0NJQAUUUUASQHbPGQf4hWxmsqzTfcDPQc1qUALRSZooAWikooAbmjNJRQA7NIeRikooAx2GGI9DRVq9QK4dRy3WqtABRRRQBasB+8Y+gq/mobeNUiUgYJGTUtAC5pc03NFADs0U3NFACZozTMmjJoAfmjNRlsdTj61E90i9DuPtQA66UNCfbms+nyzPKfm6egplABSqu5gPU0lFAGsOABS1Riu2UAPyPXvVgTow4cfjQBNRmmBs9DmjJ9aAH0UzJ9aKAEqCefy/lX738qlJwCT2rPZtzFj3oAGZmOSSaSiigAooooAKKKKACiiigBUdo2ypq9DMJF9D3FUKfE22QGgDQzRTc0UAMk/1bfSqNFFABRRRQAUUUUAFFFFABRRRQAUDqKKKAL+aKKKAP//Z';
		if (!empty($member["Avatar"])) {
			$pic = $member["Avatar"];
		}
		$firstname = $member["FirstName"];
		if (!empty($member["NickName"])) {
			$firstname = $member["FirstName"] . " (" . $member["NickName"] . ")";
		}

		$listPos = "";
		foreach ($allpos as $posision) {
			if ($posision["PID"] == $pos) {
				$listPos .= '<option value="' . $posision["PID"] . '" selected="true"  >' . $posision["Position"] . '</option>';
			} else {
				$listPos .= '<option value="' . $posision["PID"] . '">' . $posision["Position"] . '</option>';
			}

		}
		//

		echo '
				
				<style>
				.smalltable td{
					font-size:11px;
				}
				</style>
				
				<table class="table smalltable">
            	<tr>
            		<td width="30%" style="vertical-align:top"><img style="width:100px" src="' . $pic . '" /> </td>
            		<td width="70%">
            			<table class="table">
            				<tr>
            					<td colspan="2" style="color:#496D91; font-weight: bolder ">' . $member["LastName"] . ', ' . $firstname . '  </td>
            					
            				</tr>
            				<tr>
            					<td>Ethnicity</td>
            					<td>' . $member["Ethnicity"] . '</td>
            				</tr>
            				<tr>
            					<td >Height</td>
            					<td>' . $member["height"] . '</td>
            				</tr>
            				<tr>
            					<td >Weight</td>
            					<td>' . $member["weight"] . '</td>
            				</tr>
            				<tr>
            					<td>Position</td>
            					<td>
            					<select id="profile_player_id" did="' . $member["UserID"] . '" style="width:110px; margin:0px" onchange="changeplayerposition(this)">
            					' . $listPos . '
            					</select>
            					</td>
            				</tr>
            				
            			</table>
            		</td>
            	</tr>
            </table> ';

	}

	public function changepositionnumberAction() {
		//$this->_helper->viewRenderer->setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("id");
		$pos = $request -> getParam("pos");
		$sid = $request -> getParam("SID");
		$jersey = $request -> getParam("jersey");
		$db = new Model_Profile;
		$poDB = new Model_Positions;

		$SquadDB = new Model_Squad;
		$Squad = $SquadDB -> getSquad($sid);
		$listPlayers = json_decode($Squad["Players"], true);
		$PlayersSquadDetails = $listPlayers[$uid];

		$allpos = $poDB -> getPos($Squad["RugbyCode"]);

		$member = $db -> getProfileCareer($uid, $pos, $Squad["RugbyCode"]);

		$pic = 'data:2;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9+zRmkzRmgBc0ZpM0ZoAXNGaTNGaAFzRSZozQAuaM0maM0ALmjNJmjNAC5opM0UANzRmkzRmgBc0ZpMijIoAXNQy3UUJwzc+g5qC9ujH+7Q/MRyfQVmZJJJoA1BqMRPIYfhU6XEUn3XBPpWJQDg5FAHQZozVO0u/N+R/vjofWreaAFzRmkyKMigBc0UmaKAGUUlGaAFozxSUdsUAY0jl5WY85NNpWXa7D0NJQAUUUUASQHbPGQf4hWxmsqzTfcDPQc1qUALRSZooAWikooAbmjNJRQA7NIeRikooAx2GGI9DRVq9QK4dRy3WqtABRRRQBasB+8Y+gq/mobeNUiUgYJGTUtAC5pc03NFADs0U3NFACZozTMmjJoAfmjNRlsdTj61E90i9DuPtQA66UNCfbms+nyzPKfm6egplABSqu5gPU0lFAGsOABS1Riu2UAPyPXvVgTow4cfjQBNRmmBs9DmjJ9aAH0UzJ9aKAEqCefy/lX738qlJwCT2rPZtzFj3oAGZmOSSaSiigAooooAKKKKACiiigBUdo2ypq9DMJF9D3FUKfE22QGgDQzRTc0UAMk/1bfSqNFFABRRRQAUUUUAFFFFABRRRQAUDqKKKAL+aKKKAP//Z';
		if (!empty($member["Avatar"])) {
			$pic = $member["Avatar"];
		}
		$firstname = $member["FirstName"];

		$listPos .= '<option value="">None</option>';
		foreach ($allpos as $posision) {
			if ($posision["PID"] == $PlayersSquadDetails["Position"]) {
				$listPos .= '<option value="' . $posision["PID"] . '" selected="true"  >' . $posision["Position"] . ' (' . $posision["PID"] . ')</option>';
			} else {
				$listPos .= '<option value="' . $posision["PID"] . '">' . $posision["Position"] . ' (' . $posision["PID"] . ')</option>';
			}

		}

		$EthnicityDB = new Model_Ethnicity;
		$thnicity = $EthnicityDB -> getAll();

		$listEthin = '';
		foreach ($thnicity as $thnic) {
			if ($thnic["EthnicityName"] == $member["Ethnicity"]) {
				$listEthin .= '<option value="' . $thnic["EthnicityName"] . '" selected="true"  >' . $thnic["EthnicityName"] . '</option>';
			} else {
				$listEthin .= '<option value="' . $thnic["EthnicityName"] . '">' . $thnic["EthnicityName"] . '</option>';
			}

		}

		//
		$disabled = "";
		if ($jersey > 0 && $this -> identity -> UnionType > 2) {
			$disabled = "disabled='true'";
		}

		$this -> view -> assign("Member", $member);
		$this -> view -> assign("jersey", $jersey);
		$this -> view -> assign("pic", $pic);
		$this -> view -> assign("listEthin", $listEthin);
		$this -> view -> assign("listPos", $listPos);
		$this -> view -> assign("Squad", $Squad);
		$this -> view -> assign("Player", $PlayersSquadDetails);

	}

	public function changerankingAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("id");
		$pos = $request -> getParam("pos");
		$rank = $request -> getParam("rank");
		$SID = $request -> getParam("SID");

		$SquadDB = new Model_Squad;
		$Squad = $SquadDB -> getSquad($SID);

		$squadArray = json_decode($Squad["Players"], true);
		foreach ($squadArray as $ddd) {
			if ($ddd['ID'] == $uid) {
				$rank = $ddd['Rank'];
			}
		}

		$db = new Model_Profile;
		$poDB = new Model_Positions;
		$CommentsDB = new Model_SquadsComments;
		$COMMENTS = $CommentsDB -> fetchRow("UserID ='" . $uid . "' && SID ='" . $SID . "'");

		$allpos = $poDB -> getAll();

		$member = $db -> getProfileCareer($uid, $pos);
		$pic = 'data:2;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9+zRmkzRmgBc0ZpM0ZoAXNGaTNGaAFzRSZozQAuaM0maM0ALmjNJmjNAC5opM0UANzRmkzRmgBc0ZpMijIoAXNQy3UUJwzc+g5qC9ujH+7Q/MRyfQVmZJJJoA1BqMRPIYfhU6XEUn3XBPpWJQDg5FAHQZozVO0u/N+R/vjofWreaAFzRmkyKMigBc0UmaKAGUUlGaAFozxSUdsUAY0jl5WY85NNpWXa7D0NJQAUUUUASQHbPGQf4hWxmsqzTfcDPQc1qUALRSZooAWikooAbmjNJRQA7NIeRikooAx2GGI9DRVq9QK4dRy3WqtABRRRQBasB+8Y+gq/mobeNUiUgYJGTUtAC5pc03NFADs0U3NFACZozTMmjJoAfmjNRlsdTj61E90i9DuPtQA66UNCfbms+nyzPKfm6egplABSqu5gPU0lFAGsOABS1Riu2UAPyPXvVgTow4cfjQBNRmmBs9DmjJ9aAH0UzJ9aKAEqCefy/lX738qlJwCT2rPZtzFj3oAGZmOSSaSiigAooooAKKKKACiiigBUdo2ypq9DMJF9D3FUKfE22QGgDQzRTc0UAMk/1bfSqNFFABRRRQAUUUUAFFFFABRRRQAUDqKKKAL+aKKKAP//Z';
		if (!empty($member["Avatar"])) {
			$pic = $member["Avatar"];
		}
		$firstname = $member["FirstName"];

		$listPos = "";
		foreach ($allpos as $posision) {
			if ($posision["PID"] == $pos) {
				$listPos .= '<option value="' . $posision["PID"] . '" selected="true"  >' . $posision["Position"] . '</option>';
			} else {
				$listPos .= '<option value="' . $posision["PID"] . '">' . $posision["Position"] . '</option>';
			}

		}
		//

		echo '
				<style>
				.smalltable td{
					font-size:11px;
				}
				</style>
				
				<table class="table smalltable">
            	<tr>
            		<td width="30%" style="vertical-align:top"><img style="width:100px" src="' . $pic . '" /> </td>
            		<td width="70%">
            			<table class="table">
            				<tr>
            					<td colspan="2" style="color:#496D91; font-weight: bolder ">' . $member["FullName"] . '  </td>
            					
            				</tr>
            				<tr>
            					<td>Ethnicity</td>
            					<td>' . $member["Ethnicity"] . '</td>
            				</tr>
            				<tr>
            					<td >Height</td>
            					<td>' . $member["height"] . '</td>
            				</tr>
            				<tr>
            					<td >Weight</td>
            					<td>' . $member["weight"] . '</td>
            				</tr>
            				<tr>
            					<td>Position</td>
            					<td>
            					<select id="players_position" did="' . $uid . '" style="width:110px; margin:0px">
            					' . $listPos . '
            					</select>
            					</td>
            				</tr>
            				<tr>
            					<td>Ranking</td>
            					<td>
            					<input type="text" style="float: left;height: 29px;width: 108px;"  id="players_jerseynumber" value="' . $rank . '">
            					<input type="hidden" style="float: left;height: 29px;width: 108px;"  id="players_id" value="' . $uid . '">
            					</td>
            				</tr>';
		if ($this -> identity -> UnionType < 3) {
			$cheked = "";
			if ($member["flagged"] == 1) {
				$cheked = "checked";
			}
			echo '<tr>
            					<td>Flag Player</td>
            					<td>
            					<input type="checkbox" ' . $cheked . ' style="float: left;height: 29px;width: 108px;"  id="players_flag" value="1">
            					</td>
            				</tr>';
		}
		echo '</table>
            		</td>
            	</tr>
            	<tr>
            	<td colspan="2" style=" text-align:center;">
            	<textarea  id="players_comments" placeholder="Commets" style=" resize:none">' . $COMMENTS["Comment"] . '</textarea>
            					</td>
            	</tr>
            </table> ';

	}

	public function changeplayerpositionAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("uid");
		$sid = $request -> getParam("SID");
		$Position = $request -> getParam("pos");
		$flag = $request -> getParam("flag");
		$comments = $request -> getParam("comments");
		$rank = $request -> getParam("rank");
		$jersey = $request -> getParam("jersey");
		echo $captian = $request -> getParam("captian");
		$vice = $request -> getParam("vice");

		if ($request -> isPost()) {
			$SquadDB = new Model_Squad;
			$Squad = $SquadDB -> getSquad($sid);
			$jsonData = json_decode($Squad["Players"], true);

			$newPlayers = array();

			foreach ($jsonData as $PLAYER) {
				if ($PLAYER["ID"] != $uid) {
					$Captain = @$PLAYER["Captain"];
					$Vice = @$PLAYER["Vice"];
					if ($captian > 0) {
						$Captain = 0;
					}
					if ($vice > 0) {
						$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"];

					if ($jersey) {
						$Jersey = $jersey;
					}
					if ($rank > 0) {
						$Rank = $rank;
					}

					$newPlayers[$uid]["ID"] = $uid;
					$newPlayers[$uid]["Position"] = $Position;
					$newPlayers[$uid]["Rank"] = $Rank;
					$newPlayers[$uid]["Jersey"] = $Jersey;
					$newPlayers[$uid]["Captain"] = $captian;
					$newPlayers[$uid]["Vice"] = $vice;
				}
			}
			echo "<pre>";
			print_r($newPlayers);
			$array = array("Players" => json_encode($newPlayers));
			$SquadDB -> update($array, "SID ='" . $sid . "'");
			$db = new Model_Profile;
			if (!empty($comments)) {
				$CommentsDB = new Model_SquadsComments;
				$chekc = $CommentsDB -> fetchRow("UserID ='" . $uid . "' && SID ='" . $sid . "'");
				if ($chekc["UserID"] > 0) {
					$CommentsDB -> update(array("Comment" => $comments, "Author" => $this -> identity -> UserID, "DateUpdate" => date("Y-m-d H:i:s")), "UserID ='" . $uid . "' && SID ='" . $sid . "'");
				} else {
					$CommentsDB -> insert(array("Comment" => $comments, "SID" => $sid, "UserID" => $uid, "Author" => $this -> identity -> UserID, "DateUpdate" => date("Y-m-d H:i:s")));
				}

			}

			if ($this -> identity -> UnionType < 3) {
				if ($flag > 0) {
					$pdate = $db -> update(array("flagged" => 1), "UserID ='" . $uid . "'");
				} else {
					$pdate = $db -> update(array("flagged" => 0), "UserID ='" . $uid . "'");
				}

			}
		}

	}

	public function getplayersstatusAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("id");
		$pos = $request -> getParam("pos");
		$db = new Model_Profile;
		$FixtureDB = new Model_Fixture;
		$injuries = $FixtureDB -> InjuryType() -> toArray();

		$squads = new Model_PlayerInjury;
		$getIngetRy = $squads -> fetchRow("UserID ='" . $uid . "' AND ReturnToPlay >= '" . date("Y-m-d") . "'");

		$member = $db -> getProfile($uid, $pos);
		$pic = 'data:2;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9+zRmkzRmgBc0ZpM0ZoAXNGaTNGaAFzRSZozQAuaM0maM0ALmjNJmjNAC5opM0UANzRmkzRmgBc0ZpMijIoAXNQy3UUJwzc+g5qC9ujH+7Q/MRyfQVmZJJJoA1BqMRPIYfhU6XEUn3XBPpWJQDg5FAHQZozVO0u/N+R/vjofWreaAFzRmkyKMigBc0UmaKAGUUlGaAFozxSUdsUAY0jl5WY85NNpWXa7D0NJQAUUUUASQHbPGQf4hWxmsqzTfcDPQc1qUALRSZooAWikooAbmjNJRQA7NIeRikooAx2GGI9DRVq9QK4dRy3WqtABRRRQBasB+8Y+gq/mobeNUiUgYJGTUtAC5pc03NFADs0U3NFACZozTMmjJoAfmjNRlsdTj61E90i9DuPtQA66UNCfbms+nyzPKfm6egplABSqu5gPU0lFAGsOABS1Riu2UAPyPXvVgTow4cfjQBNRmmBs9DmjJ9aAH0UzJ9aKAEqCefy/lX738qlJwCT2rPZtzFj3oAGZmOSSaSiigAooooAKKKKACiiigBUdo2ypq9DMJF9D3FUKfE22QGgDQzRTc0UAMk/1bfSqNFFABRRRQAUUUUAFFFFABRRRQAUDqKKKAL+aKKKAP//Z';
		if (!empty($member["Avatar"])) {
			$pic = $member["Avatar"];
		}
		$firstname = $member["FirstName"];
		if (!empty($member["NickName"])) {
			$firstname = $member["NickName"];
		}

		$listPos = "<option value=''>Select Injury</option>";
		foreach ($injuries as $injury) {
			$listPos .= '<option value="' . $injury["ITID"] . '"';
			if ($getIngetRy["InjuryID"] == $injury["ITID"]) { $listPos .= ' selected ';
			}
			$listPos .= '  >' . $injury["Type"] . '</option>';
		}
		//
		echo '
				<input type="hidden" id ="InjusryIID"; value="' . $getIngetRy["IID"] . '"/>
				<table class="table"  style="width:100%">
            	<tr>
            		<td width="30%" style="vertical-align:top"><img style="width:100px" src="' . $pic . '" /> </td>
            		<td width="70%">
            			<table class="table"  style="width:100%">
            				<tr>
            					<td colspan="2" style="color:#496D91; font-weight: bolder ">' . $member["LastName"] . ', ' . $firstname . '</td>
            					
            				</tr>
            				<tr>
            					<td>Ethnicity</td>
            					<td>' . $member["Ethnicity"] . '</td>
            				</tr>
            				<tr>
            					<td >Height</td>
            					<td>' . $member["height"] . '</td>
            				</tr>
            				<tr>
            					<td >Weight</td>
            					<td>' . $member["weight"] . '</td>
            				</tr>
            			</table>
            		</td>
            	</tr>
            </table> 
            <table class="table" style="width:100%">
            <tr>
            <td colspan="2" style="color:#496D91; font-weight: bolder ">MEDICAL STATUS</td>
            </tr>
            <tr>
            					<td>Injury Type</td>
            					<td>
            					<select id="injuryType">
            					' . $listPos . '
            					</select>
            					</td>
            				</tr>
            				<tr>
            					<td>Injury Date</td>
            					<td><input type="text" name="InjuryDate" class="dateslector" id="InjuryDate" value="' . $getIngetRy["InjuryDate"] . '"  style="height:25px;"/></td>
            				</tr>
            				<tr>
            					<td>Return To Training</td>
            					<td><input type="text" name="ReturnToTraining" id="ReturnToTraining"  value="' . $getIngetRy["ReturnToTraining"] . '" class="dateslector" style="height:25px;" /></td>
            				</tr>
            				<tr>
            					<td>Return To Play</td>
            					<td><input type="text" name="ReturnToPlay" id="ReturnToPlay"  value="' . $getIngetRy["ReturnToPlay"] . '"  class="dateslector"  style="height:25px;"/></td>
            				</tr>
            				<tr>
            					<td>Comments</td>
            					<td><textarea  id="MedicalComments">' . $getIngetRy["Comments"] . '</textarea></td>
            				</tr>
            </table>
            		
            <script>
            $( ".dateslector" ).datepicker({
						  dateFormat: "yy-mm-dd"
						});
            </script>
            ';

	}

	public function changepositionAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$uid = $request -> getParam("id");
		$pos = $request -> getParam("pos");
		$db = new Model_Profile;
		$FixtureDB = new Model_Fixture;
		$injuries = $FixtureDB -> InjuryType() -> toArray();

		$member = $db -> getProfile($uid, $pos);
		$pic = 'data:2;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9+zRmkzRmgBc0ZpM0ZoAXNGaTNGaAFzRSZozQAuaM0maM0ALmjNJmjNAC5opM0UANzRmkzRmgBc0ZpMijIoAXNQy3UUJwzc+g5qC9ujH+7Q/MRyfQVmZJJJoA1BqMRPIYfhU6XEUn3XBPpWJQDg5FAHQZozVO0u/N+R/vjofWreaAFzRmkyKMigBc0UmaKAGUUlGaAFozxSUdsUAY0jl5WY85NNpWXa7D0NJQAUUUUASQHbPGQf4hWxmsqzTfcDPQc1qUALRSZooAWikooAbmjNJRQA7NIeRikooAx2GGI9DRVq9QK4dRy3WqtABRRRQBasB+8Y+gq/mobeNUiUgYJGTUtAC5pc03NFADs0U3NFACZozTMmjJoAfmjNRlsdTj61E90i9DuPtQA66UNCfbms+nyzPKfm6egplABSqu5gPU0lFAGsOABS1Riu2UAPyPXvVgTow4cfjQBNRmmBs9DmjJ9aAH0UzJ9aKAEqCefy/lX738qlJwCT2rPZtzFj3oAGZmOSSaSiigAooooAKKKKACiiigBUdo2ypq9DMJF9D3FUKfE22QGgDQzRTc0UAMk/1bfSqNFFABRRRQAUUUUAFFFFABRRRQAUDqKKKAL+aKKKAP//Z';
		if (!empty($member["Avatar"])) {
			$pic = $member["Avatar"];
		}
		$firstname = $member["FirstName"];
		if (!empty($member["NickName"])) {
			$firstname = $member["NickName"];
		}

		$listPos = "";
		foreach ($injuries as $injury) {

			$listPos .= '<option value="' . $injury["ITID"] . '" selected="true"  >' . $injury["Type"] . '</option>';

		}
		//
		echo '<table class="table"  style="width:100%">
            	<tr>
            		<td width="30%" style="vertical-align:top"><img style="width:100px" src="' . $pic . '" /> </td>
            		<td width="70%">
            			<table class="table"  style="width:100%">
            				<tr>
            					<td colspan="2" style="color:#496D91; font-weight: bolder ">' . $member["LastName"] . ', ' . $firstname . '</td>
            					
            				</tr>
            				<tr>
            					<td>Ethnicity</td>
            					<td>' . $member["Ethnicity"] . '</td>
            				</tr>
            				<tr>
            					<td >Height</td>
            					<td>' . $member["height"] . '</td>
            				</tr>
            				<tr>
            					<td >Weight</td>
            					<td>' . $member["weight"] . '</td>
            				</tr>
            				<tr>
            					<td >Position</td>
            					<td>' . $member["weight"] . '</td>
            				</tr>
            			</table>
            		</td>
            	</tr>
            </table> 
           
            		
            <script>
            $( ".dateslector" ).datepicker({
						  dateFormat: "yy-mm-dd"
						});
            </script>
            ';

	}

	public function validatesountryAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$uid = $request -> getParam("id");

		$db = new Model_Profile;
		$found = $db -> fetchAll("IDNumber ='" . $uid . "'");
		if (count($found) > 0) {
			echo 1;
		} else {
			echo 0;
		}

	}

	public function checkmemberAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$fname = $request -> getParam("fname");
		$lname = $request -> getParam("lname");
		$idNum = $request -> getParam("idNum");
		$email = $request -> getParam("EMail");
		$id = $request -> getParam("id");

		$match = "";
		$matchid = 0;
		$db = new Model_Profile;

		if ($id > 0) {
			if (!empty($idNum)) {
				$found = $db -> fetchAll("IDNumber ='" . $idNum . "' AND UserID !='" . $id . "'");
				$match = "Account With ID Number  <strong>" . $idNum . " </strong> ";
				$matchid = 1;
			} else if (!empty($email)) {
				$found = $db -> fetchAll("Email ='" . $email . "' AND UserID !='" . $id . "'");
				$match = "Account With Email  <strong>" . $email . " </strong>";
				$matchid = 1;
			} else if (!empty($fname) && !empty($lname)) {
				$found = $db -> fetchAll("FirstName ='" . $fname . "' AND LastName ='" . $lname . "' AND UserID !='" . $id . "'");
				$match = "Account With Fullname  <strong>" . $fname . " " . $lname . " </strong>";
			} else {
				$found = $db -> fetchAll("Fullname Like '" . $fname . " " . $lname . "' AND UserID !='" . $id . "'");
				$match = "Account With Lastname  <strong>" . $lname . " </strong> ";
			}
		} else {
			if (!empty($idNum)) {
				$found = $db -> fetchAll("IDNumber ='" . $idNum . "'");
				$match = "Account With ID Number  <strong>" . $idNum . " </strong> ";
				$matchid = 1;
			} else if (!empty($email)) {
				$found = $db -> fetchAll("Email ='" . $email . "' ");
				$match = "Account With Email  <strong>" . $email . " </strong>";
				$matchid = 1;
			} else if (!empty($fname) && !empty($lname)) {
				$found = $db -> fetchAll("FirstName ='" . $fname . "' AND LastName ='" . $lname . "'");
				$match = "Account With Fullname  <strong>" . $fname . " " . $lname . " </strong>";
			} else {
				$found = $db -> fetchAll("Fullname Like '" . $fname . " " . $lname . "'");
				$match = "Account With Lastname  <strong>" . $lname . " </strong> ";
			}
		}

		if (count($found) > 0) {
			echo '
				<h2 style="font-size:12px; margin:0px; border-bottom: 1px solid #ccc; background:#E0DEDE; padding : 0px 10px">Match Found!</h2>
				<p style="color:#f00;font-size:12px; margin:0px; border-bottom: 1px solid #ccc;  padding : 0px 10px">The Following match was found on our system for ' . $match . '</p>
				
				
				<div style="height:200px; overflow:auto; border: 1px solid #ccc; border-top: 0px solid #ccc"><table class="table" width="100">';
			$n = 1;
			foreach ($found as $player) {

				$profile = $db -> getRow($player["UserID"], 2);
				echo '<tr class="row-form clearfix" style="padding:0px">
													<td style="width:10px">' . $n . '</td>
													<td style="width:40px"><img src="' . $profile["Avatar"] . '" style="width:40px" /></td>
													<td ><a target="_blank" href="/players/profile/id/' . $player["UserID"] . '">' . $player["FirstName"] . ' ' . $player["LastName"] . '</a></td>
													<td>' . $profile["POS"] . '</td>
													<td>' . $profile["un_name"] . '</td>
                         </tr>';
				$n++;
			}

			echo '</table></div>';

			if ($matchid == 0) {
				echo '<div class="footer clearfix wizard_validate-buttons" id="wizard_validate-buttons-3" style="padding-top:10px">
                		<a id="wizard_validate-back-3" href="javascript:closeMadel();" class="btn button-back" style="margin-left:0px">Go Back</a>
                	<a id="wizard_validate-next-3" href="javascript:continuewithForm();" class="btn button-next">Continue ..</a>
                	</div>';
			} else {
				echo '<div class="footer clearfix wizard_validate-buttons" id="wizard_validate-buttons-3" style="padding-top:10px">
                		<a id="wizard_validate-back-3" href="javascript:closeMadel();" class="btn button-back" style="margin-left:0px">Go Back</a>
                	</div>';
			}
		} else {
			echo 0;
		}

	}

	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)));

		}

	}

	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 bonafideuploadsAction() {

	}

	public function uploadbonafidecsvAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		// Check if image file is a actual image or fake image
		if ($request -> isPost()) {
			$csvData = file_get_contents($_FILES["CSV"]["tmp_name"]);
			$lines = explode(PHP_EOL, $csvData);
			$array = array();
			foreach ($lines as $line) {
				$line = str_getcsv($line);
				if ($line[0] == "ID No") {

				} else {
					$array[] = $line;
				}

			}
			echo json_encode($array);

		}

	}

	public function savebonafideAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		// Check if image file is a actual image or fake image
		if ($request -> isPost()) {
			$data = $request -> getParam("data");
			if (count($data) > 0) {
				foreach ($data as $line) {
					if ($line["ID"] != "") {
						if (!isset($line["AT"])) {
							$line["AT"] = 0;
						}
						$DB = new Model_Profile;

						$DataArray = array("Bonified_no" => $line["BN"], "At_Risc" => $line["AT"], "Play_Year" => $line["DATE"]);
						$Profile = $DB -> update($DataArray, "IDNumber ='" . $line["ID"] . "'");
					}
				}
			}

		}

	}

	public function duplicateAction() {

	}

}
