<?php
ini_set("memory_limit", "800M");
date_default_timezone_set('Africa/Johannesburg');
class Union_SquadsController extends Zend_Controller_Action {
	public $squad;
	public $identity;
	public $fixture;
	public $Wallpaper;
	public $AdminUsers;
	public $LOCTournamnets;
	private $Tournament;
	private $UnionsTypes;
	private $Unions;
	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');
		} else {
			if ($this -> identity -> Active == 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());
		$pic = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAKMAowMBIgACEQEDEQH/xAAaAAEBAAMBAQAAAAAAAAAAAAAAAQIDBAUH/8QAKRABAAICAQEHBAMBAAAAAAAAAAECAxEEIRIiMUFCUXETMmGBBVKRI//EABQBAQAAAAAAAAAAAAAAAAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwD7iIAogCiAKIAogCiAKIAogCiAKIAogCCAKIAogCiAKJsBRNgKIAogCiAKIAogCAAAAAAA5eXyfpR2aTHbnx/ANufkY8Md6dz/AFhx35+Sd9mIrHk5JmZnczufcB0RzM0eqJ/Tbj58+ukfMOIB6uPl4sk9mN1ny23vDjpL0OLy4trHknVvKfcHYGwAAAAAEBNm0AXZtAF2bQBMmSMdLWt4RDyLWm9ptbxl3fyFtY619524AAAAAAAepxMv1cPWe9HSW7bj/jp6X+YdYLs2gC7NoAuxAAQBRAFEAcf8jHSk/Ljd/OtX6UVn7t7hwAAAAAAa8wd/Br2cU2/tLqYYoiuOIj2ZAogCiAKIAggCiAKIA5efHdpLjejyMf1cUxH3R4PPmsxMxPTQIAAAAVjdtT5jbgxWveJ13Y8ZB6MdIjSoAogCiAKIAgAAAAADh5sf9txHTTuc3MrukTHjAOMAAACHocSNYK/l5+t6iPHb06RqlY9oBkAAAAAACADEBkMQGQxY3yUpHetr4BsaORlrWmvGZ8mrJybT0pGvzLnmZmdyAAAADLHaK3i0xuIejWYtG4ncS8xnjy3p9s9PYHojRj5FLfdHZlt2DIYgMhiAyRABNgBPTrLRk5MeiIn8tefLNp7NelYaQZ2zXt6tMOvnOwAAAAAAAAAWLW95/wBQBnGbJHWLTPy34uRFul+kuU+AejCuTBl13bT8OrYKIAm2vPbs45956M48XPyp61j9g0AAAAAAAAAAAAAAAAO3DbtY4nzcTo4s9LQDoEAHNyfur8IA1AAAAAAAAAAAAAAAAN3G9X6AG8AH/9k=';
		$this -> view -> assign("Profile_Default", $pic);

		$SquadsTable = new Model_Squad;
		/*
		 * $id =$request->getParam("sid");
		 * $this->view->assign("sid",$id);
		 */
		$squad = $SquadsTable -> getSquad(1);
		$this -> view -> assign("profile", $squad);
		$this -> Unions = new Model_Unions;
		$this -> Tournament = new Model_Tournament;
		//$this->AdminUsers = array(1);
		$this -> AdminUsers = array(1, 989, 582, 4156, 1007, 1014);
		if (in_array($this -> identity -> UserID, $this -> AdminUsers)) {
			$this -> view -> assign("MySquads", "All Squads (Admin)");
		} else {
			$this -> view -> assign("MySquads", "My Squads");
		}
		$this -> view -> assign("Footprint", $this -> AdminUsers);

		$PlayersHistoryDB = new Model_PlayerCareer;
		$ListSquads = $PlayersHistoryDB -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
		$this -> view -> assign("CurrentSquads", json_decode($ListSquads["Squads"], true));

		if ($this -> identity -> UserID == 1177) {
			$LOC = new PG_Controller_Plugin_LOC;
			$check = $LOC -> getTournLoc($this -> identity -> UserID);
			$this -> view -> assign("LocAdmin", $check);
			$this -> LOCTournamnets = $check;
		}

	}

	public function uploadsubmitAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		$id = $request -> getParam("id");
		$this -> view -> assign("UserID", $id);
		if ($request -> isPost()) {
			$title = $request -> getParam("title");
			$Option = $request -> getParam("Option");
			$Type = $request -> getParam("Type");
			$SID = $request -> getParam("SID");
			if (!$SID) {
				$SID = 0;
			}
			$db = new Model_Profile;

			//UPLOAD COPY OF ID
			if ($_FILES["Myfile"]) {
				$imageFileType = pathinfo($_FILES["Myfile"]["name"], PATHINFO_EXTENSION);
				$fileName = md5(uniqid() . $_FILES["Myfile"]["name"]) . "." . $imageFileType;

				$target_file = UPLOADS_PATH . "/documents/" . $fileName;

				if (move_uploaded_file($_FILES["Myfile"]["tmp_name"], $target_file)) {
					$href = "http://" . $_SERVER["SERVER_NAME"] . "/uploads/documents/" . $fileName;

					$db = new Model_Documents;
					$insert = $db -> insertData(array("SID" => $SID, "Title" => $_FILES["Myfile"]["name"], "FileType" => $Type, "DateCreated" => date("Y-m-d H:s:i"), "File" => $fileName, "Type" => $imageFileType, "Category" => $Option, "Href" => $href, "UserID" => $id, "Author" => $this -> identity -> UserID));
					echo json_encode(array("Message" => 1));

				} else {
					echo json_encode(array("Message" => "No Upload"));
				}

			} else {
				echo json_encode(array("Message" => "Error"));
			}
		}

	}

	public function downloadAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$fl = $request -> getParam("fl");

		$imageFileType = pathinfo($fl, PATHINFO_EXTENSION);

		if (file_exists(UPLOADS_PATH . "/documents/" . $fl)) {
			$db = new Model_Documents;
			$FILEDetails = $db -> fetchRow("File ='" . $fl . "'");

			$explod = explode(".pdf", $FILEDetails["Title"]);
			$fileName = $this -> cleanString($explod[0]) . "." . $imageFileType;

			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header("Content-Type: application/force-download");
			header('Content-Disposition: attachment; filename=' . urlencode(basename($fileName)));
			// header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header('Content-Length: ' . filesize($fl));
			ob_clean();
			flush();
			readfile(UPLOADS_PATH . "/documents/" . $fl);
			exit ;
		}
	}

	function cleanString($string) {
		$string = str_replace('', '-', $string);
		// Replaces all spaces with hyphens.
		return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
		// Removes special chars.
	}

	public function doreportAction() {
		//
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$this -> view -> assign("sid", $sid);
		if ($request -> isPost()) {
			$this -> _helper -> viewRenderer -> setNoRender();
			$FormData["DateCreated"] = date("Y-m-d H:i:s");
			$FormData["UserID"] = $this -> identity -> UserID;
			$FormData["SID"] = $sid;
			$data = $request -> getParam("data");
			$FormData["Data"] = json_encode($data);
			//03/23/2016
			$date = explode("/", $data["Sessiondate"]);

			$FormData["SesionDate"] = date("Y-m-d H:i:s", strtotime($date[2] . "-" . $date[0] . "-" . $date[1]));
			$FormData["Location"] = $data["InsertLocation"];
			$db = new Model_GirReport;
			$insert = $db -> insertData($FormData);
		}
	}

	public function getdoreportAction() {
		//
		$this -> _helper -> layout -> disableLayout();
		$this -> _helper -> viewRenderer -> setNoRender();
		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$db = new Model_GirReport;
		$list = $db -> getAllBySID($sid);

		echo json_encode($list -> toArray());

	}

	public function indexAction() {

		$SquadTypeDb = new Model_SquadTypes;
		$Types = $SquadTypeDb -> fetchAll() -> toArray();
		$this -> view -> assign('SquadTypes', $Types);
		if ($this -> identity -> UserID == 1) {
			// $this->_helper->viewRenderer('squads/indextest', null, true);
		}

	}

	public function createAction() {

		$SquadTypeDb = new Model_SquadTypes;
		$Types = $SquadTypeDb -> fetchAll() -> toArray();
		$this -> view -> assign('SquadTypes', $Types);

		$UnionsDb = new Model_Unions;

		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$this -> _helper -> viewRenderer -> setNoRender();
			$this -> _helper -> layout -> disableLayout();
			$data = $request -> getParam("data");

			if ($data["SquadType"] == 2) {
				$data["TIDs"] = $data["TournamentID"];
				$data["TournamentID"] = 0;
			}

			if ($this -> identity -> UnionType == 11) {
				$data["Organization"] = $this -> identity -> UnionID;
			}
			if ($data["Organization"] == 0) {
				$data["Organization"] = $this -> identity -> UnionID;
			}

			$data["Year"] = date("Y", strtotime($data["FormDate"]));
			$data["DateCreated"] = date("Y-m-d H:i:s");
			$data["FormDate"] = date("Y-m-d", strtotime($data["FormDate"]));
			$data["Author"] = $this -> identity -> UserID;
			$data["TeamManager"] = $this -> identity -> UserID;
			$SquadsTable = new Model_Squad;
			$ID = $SquadsTable -> insertData($data);
			$Member[$this -> identity -> UserID]["ID"] = $this -> identity -> UserID;
			$Member[$this -> identity -> UserID]["Position"] = 42;
			$SquadsTable -> updateSquad(array("Coaches" => json_decode($Member)), $id);
			$PlayerCareer = new Model_PlayerCareer;
			$Jsondata = array("SID" => $ID, "Squad" => $data["SquadName"], "Pos" => "42", "DATE" => date("Y-m-d H:i:s"));

			$profile = $PlayerCareer -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
			$HistoryJson = json_decode($profile["Squads"], true);
			$HistoryJson[$ID] = $Jsondata;

			if ($profile["UserID"] > 0) {
				$PlayerCareer -> updateData(array("Squads" => json_encode($HistoryJson)), $this -> identity -> UserID);
			} else {
				$PlayerCareer -> insertData(array("Squads" => json_encode($HistoryJson), "UserID" => $this -> identity -> UserID));
			}

			//send email

		}

		$UnionsTypes = new Model_IntuitutionTypes;
		if ($this -> identity["UnionType"] == 12 || $this -> identity["UnionType"] < 3) {

			$Unions = $UnionsDb -> getAllSecondaryAndPrimary() -> toArray();

			$this -> view -> assign('Unions', $Unions);
			$this -> view -> assign("listTypesUnions", $UnionsTypes -> fetchAll("type_id >1 "));
		} else {
			$Unions = $UnionsDb -> getAllSecondaryAndPrimaryUnion($this -> identity["UnionID"]) -> toArray();
			$this -> view -> assign("listTypesUnions", $UnionsTypes -> fetchAll("type_id >2 AND type_id!=11"));
			$this -> view -> assign('Unions', $Unions);
		}

		if (count($this -> LOCTournamnets) > 0) {
			$Tournament = $this -> Tournament -> getAllWithSeriesByID($this -> LOCTournamnets);
			$this -> view -> assign("Tournament", $Tournament);

		} else {
			$Tournament = $this -> Tournament -> getAllWithSeries();
			$this -> view -> assign("Tournament", $Tournament);
		}

		$unions = $UnionsDb -> getAllDrop();
		$this -> view -> assign("listUnions", $unions);

		//$this->Tournament->update(array("AgeGroup"=>"[0]"),"AgeGroup =0");

	}

	public function createsAction() {

		$SquadTypeDb = new Model_SquadTypes;
		$Types = $SquadTypeDb -> fetchAll("GIR =1 ") -> toArray();
		$this -> view -> assign('SquadTypes', $Types);

		$UnionsDb = new Model_Unions;
		$Unions = $UnionsDb -> getAllSecondaryAndPrimary() -> toArray();

		$this -> view -> assign('Unions', $Unions);
		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$this -> _helper -> viewRenderer -> setNoRender();
			$this -> _helper -> layout -> disableLayout();
			$data = $request -> getParam("data");
			$data["Year"] = date("Y", strtotime($data["FormDate"]));
			$data["FormDate"] = date("Y-m-d", strtotime($data["FormDate"]));
			$data["Author"] = $this -> identity -> UserID;
			$SquadsTable = new Model_Squad;
			echo $ID = $SquadsTable -> insertData($data);
		}

		if ($this -> identity -> UserID == 1) {
			$View = new Zend_View();
			$View -> addScriptPath('/squads/creates');
		}

	}

	public function updateAction() {

		$SquadTypeDb = new Model_SquadTypes;
		$Types = $SquadTypeDb -> fetchAll() -> toArray();
		$this -> view -> assign('SquadTypes', $Types);

		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$SquadsTable = new Model_Squad;
		$test = $request -> getParam("test");
		$squad = $SquadsTable -> getSquad($id);
		$UnionsDb = new Model_Unions;
		if ($squad["SquadType"] == 1) {
			$Edit = 0;
			if (count($this -> LOCTournamnets) > 0) {
				foreach ($this->LOCTournamnets as $LocAdmin) {
					if ($LocAdmin["Position"] == 2 && $LocAdmin["TID"] == $squad["TournamentID"]) {
						$Edit = 1;
					}
				}
			}
			if ($Edit == 0) {
				$this -> _redirect('/union/squads/profile/id/' . $id);
			}
		}

		if ($request -> isPost()) {
			$this -> _helper -> viewRenderer -> setNoRender();
			$this -> _helper -> layout -> disableLayout();
			$data = $request -> getParam("data");

			if ($data["SquadType"] == 2) {
				$data["TIDs"] = $data["TournamentID"];
				$data["TournamentID"] = 0;
			}
			if ($this -> identity -> UnionType == 11) {
				$data["Organization"] = $this -> identity -> UnionID;
			}
			if ($data["Organization"] == 0) {
				$data["Organization"] = $this -> identity -> UnionID;
			}

			$data["DateModified"] = date("Y-m-d H:i:s");
			$data["Year"] = date("Y", strtotime($data["FormDate"]));
			$data["FormDate"] = date("Y-m-d", strtotime($data["FormDate"]));
			//$data["Author"] = $squad["Author"];

			$ID = $SquadsTable -> updateSquad($data, $id);

			//send email

		}

		$squad = $SquadsTable -> getSquad($id);
		$this -> view -> assign("squad", $squad);

		$UnionsTypes = new Model_IntuitutionTypes;
		if ($this -> identity["UnionType"] == 12 || $this -> identity["UnionType"] < 3) {

			$Unions = $UnionsDb -> getAllSecondaryAndPrimary() -> toArray();

			$this -> view -> assign('Unions', $Unions);
			$this -> view -> assign("listTypesUnions", $UnionsTypes -> fetchAll("type_id >1 "));
		} else {
			$Unions = $UnionsDb -> getAllSecondaryAndPrimaryUnion($this -> identity["UnionID"]) -> toArray();
			$this -> view -> assign("listTypesUnions", $UnionsTypes -> fetchAll("type_id >2 AND type_id!=11"));
			$this -> view -> assign('Unions', $Unions);
		}

		$unions = $UnionsDb -> getAllDrop();
		$this -> view -> assign("listUnions", $unions);
		if ($squad["SquadType"] == 1) {
			if (count($this -> LOCTournamnets) > 0) {
				$Tournament = $this -> Tournament -> getAllWithSeriesByID($this -> LOCTournamnets);
				$this -> view -> assign("Tournament", $Tournament);

			}
		}
		if ($squad["SquadType"] == 2) {

			$Tournament = $this -> Tournament -> getAllWithSeriesAll();
			$this -> view -> assign("Tournament", $Tournament);

		}
		if ($this -> identity -> UserID == 1177 || $this -> identity -> UserID == 1) {
			$this -> _helper -> viewRenderer('squads/updatetest', null, true);
		}

	}

	public function wallpaperAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		if ($request -> isPost()) {

			$IMGBASE64 = str_replace(" ", "+", $request -> getParam("Avatar"));
			$sid = $request -> getParam("sid");
			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_Wallpaper;
					$count = $imgDB -> fetchAll("SID ='" . $sid . "'");
					if (count($count) > 0) {
						$daone = $imgDB -> insertData(array("File" => $fileName . '.jpg', "SID" => $sid, "Wallpaper" => 0));
					} else {
						$daone = $imgDB -> insertData(array("File" => $fileName . '.jpg', "SID" => $sid, "Wallpaper" => 1));
					}

				}
			}
		}

	}

	public function getwallpaperAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$imgDB = new Model_Wallpaper;
		$count = $imgDB -> getAll($sid);
		echo json_encode($count -> toArray());

	}

	public function mainwallpaperAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$wallpaer = "/IMGS/wallpaper.jpg";
		$Model_WallpaperDB = new Model_Wallpaper;
		$wellpaperData = $Model_WallpaperDB -> fetchRow("SID ='" . $sid . "' AND Wallpaper =1 ");
		if (isset($wellpaperData["SID"]) && $wellpaperData["SID"] > 0) {
			$wallpaer = "/IMGS/" . $wellpaperData["File"];
		}

		echo $wallpaer;

	}

	public function deletewallpaperAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$id = $request -> getParam("id");
			$imgDB = new Model_Wallpaper;
			$Row = $imgDB -> fetchRow("IMGID ='" . $id . "'");
			if ($Row["IMGID"] > 0) {
				$imgDB -> delete("IMGID ='" . $id . "'");
				unlink(IMG_PATH . '/' . $Row["File"]);
			}
		}
	}

	public function setwallpaperAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$id = $request -> getParam("id");
			$sid = $request -> getParam("sid");
			$imgDB = new Model_Wallpaper;
			$Row = $imgDB -> update(array("Wallpaper" => 0), "SID ='" . $sid . "'");

			$imgDB -> update(array("Wallpaper" => 1), "IMGID ='" . $id . "'");

		}
	}

	public function medicalAction() {

		//$this->_helper->viewRenderer->setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("pid");

		$ProfileDB = new Model_Profile;

		$UserProfile = $ProfileDB -> getQuick($id);
		$Profile = $UserProfile -> toArray();
		$this -> view -> assign("Profile", $Profile);
		$this -> view -> assign("PID", $id);
		$squads = new Model_PlayerInjury;
		$getIngetRy = $squads -> fetchRow("UserID ='" . $id . "' AND ReturnToPlay >= '" . date("Y-m-d") . "'");

		$FixtureDB = new Model_Fixture;
		$injuries = $FixtureDB -> InjuryType() -> toArray();

		$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>';
		}

		$this -> view -> assign("InjuryType", $listPos);
		$this -> view -> assign("InjuryData", $getIngetRy);
	}

	public function profileAction() {
		$FixtureTbl = new Model_Fixture;
		$SquadsTbl = new Model_Squad;

		$request = $this -> getRequest();
		$id = $request -> getParam("id");

		$PlayersHistoryDB = new Model_PlayerCareer;
		$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
		$squads = json_decode($getCurrent["Squads"], true);

		if ($id < 1) {
			// chek if the user is in this squad
			$this -> _redirect('/union/squads');
		}

		//reset data
		$this -> resetdata($id);

		$squad = $SquadsTbl -> getSquad($id);

		$coaches = json_decode($squad["Coaches"], true);

		$TournmentTbl = new Model_Tournament;
		$Tournament = $TournmentTbl -> fetchRow("TID ='" . $squad["TournamentID"] . "'");

		$Officials = json_decode($Tournament["Officials"], true);
		$AllowMedical = array();
		if (count($Officials) > 0) {
			foreach ($Officials as $k => $v) {
				if ($v["UserID"] == $this -> identity -> UserID) {
					if ($k == 31 || $k == 17 || $k == 16) {
						$AllowMedical["JobType"] = $k;
						$AllowMedical["UserID"] = $v["UserID"];
						$AllowMedical["Medical"] = 1;
					}

				}
			}
		}
		
		$this -> view -> assign("Official", $AllowMedical);

		$view = 0;
		if ($squad["Author"] == $this -> identity -> UserID) {
			$view = 1;
		}
		if (count($coaches) > 0) {
			foreach ($coaches as $coache) {
				if ($coache["ID"] == $this -> identity -> UserID) {
					$view = 1;
				}
			}
		}
		if (in_array($this -> identity -> UserID, $this -> AdminUsers)) {
			$view = 1;
		}
		$MyRole = array();
		$MyRole["LOC"] = 0;
		$squadslist = array();
		$Tournaments = json_decode($this -> identity -> LOC, true);
		if (count($Tournaments) > 0) {
			foreach ($Tournaments as $Tournament) {

				$squadsli = $SquadsTbl -> getAllSquadsTournIDOnly($Tournament["TID"]);
				if (count($squadsli) > 0) {
					foreach ($squadsli as $Sqd) {

						if ($Sqd["SID"] == $id) {
							$view = 1;
							if ($Tournament["Position"] > 15 && $Tournament["Position"] < 19) {
								$MyRole["Parent"] = 5;
								$MyRole["LOC"] = 1;
							}
						}

					}
				}
			}
		}

		if ($view == 0) {
			// chek if the user is in this squad
			$this -> _redirect('/union/squads');
		}
		$this -> view -> assign("squad", $squad);
		$Started = 1;

		if ($squad["SquadType"] == 1) {
			$TournDB = new Model_Tournament;
			$Tour = $TournDB -> fetchRow("TID ='" . $squad["TournamentID"] . "'");

			if ($Tour["StartDate"] > date("Y-m-d")) {
				$Started = 0;

			}
			$this -> view -> assign("Tourn", $Tour);
		}

		$this -> view -> assign("StartDate", $Started);
		$getFixs = $FixtureTbl -> getFixtureUpcoming($id);

		$this -> view -> assign('UpcomingEvents', $getFixs);

		$DB = new Model_UserType;
		$user_types = $DB -> getForSquadsdrop();
		$this -> view -> assign("UsertTypes", $user_types);

		$DBPos = new Model_Positions();
		$Positions = $DBPos -> getPos($squad["RugbyCode"]);
		$this -> view -> assign("Positions", $Positions);

		$squadSelect = $SquadsTbl -> getMySquadGir($this -> identity -> UserID);
		$this -> view -> assign("MySquads", $squadSelect);
		//var_dump($players);
		if ($squad["SquadType"] > 12) {
			$this -> _helper -> viewRenderer('squads/profilegir', null, true);
		} else {

		}

		if ($this -> identity -> UserID == 1) {
			//$Members = json_decode($json,true);
			if (count($squads) > 0) {

				foreach ($squads as $sqd) {
					if ($sqd["SID"] == $id) {
						$UserRoleDB = new Model_UserType;
						$UserRole = $UserRoleDB -> fetchRow("TypeID ='" . $sqd["Pos"] . "'");
						$sqd["Parent"] = $UserRole["parent"];
						$MyRole = $sqd;
					}
				}
			}
			//  exit;
		}
		$this -> view -> assign("Role", $MyRole);
		//Get Members
		if ($squad["SquadType"] == 1) {
			//get fixtures
			$MatchReportTbl = new Model_MatchReport;
			$PrevFixture = $FixtureTbl -> getPrevFixture($id);

			$FixturesDetails = array();
			if (count($PrevFixture) > 0) {
				$fixtureD = $PrevFixture[count($PrevFixture) - 1] -> toArray();
				$FixturesDetails["PREV"] = $fixtureD;
				$HomeTeamScore = $MatchReportTbl -> getScore($fixtureD["FID"], $fixtureD["HomeTeam"]);

				$AwayTeamScore = $MatchReportTbl -> getScore($fixtureD["FID"], $fixtureD["AwayTeam"]);
				$FixturesDetails["SCORE"]["HScore"] = (!empty($HomeTeamScore["HFS"])) ? $HomeTeamScore["HFS"] : 0;
				$FixturesDetails["SCORE"]["AScore"] = (!empty($AwayTeamScore["HFS"])) ? $AwayTeamScore["HFS"] : 0; ;
				$edit =1;
				$AuditScoreDB = new Model_TeamScore;
				$ScoreData = $AuditScoreDB->getDespute($fixtureD["FID"]);
				if(isset($ScoreData["Match_Report"]) && $ScoreData["Match_Report"]==0){
					$Check_Audit = $AuditScoreDB->GetScore($fixtureD["FID"],$id);
					if($id== $Check_Audit["SID"] ){
						$edit =0;
						if ($Check_Audit) {
								$this -> view -> assign("SCORE", $Check_Audit);
						}
					}
				}else{
					$edit =2;
				}
				
				
				
				$Fixture_IDS = array("MyTeam"=>$fixtureD["HomeTeam"],"Opponent"=>$fixtureD["AwayTeam"]);
				if($fixtureD["AwayTeam"]== $squad["SID"]){
					$Fixture_IDS = array("MyTeam"=>$fixtureD["AwayTeam"],"Opponent"=>$fixtureD["HomeTeam"]);
				}
				
				
				$this -> view -> assign("AUDIT", $edit);
				$this -> view -> assign("TEAMS_IDS", $Fixture_IDS);
				
				
				
				$TEAMNUMBER = 1;
			if ($id == $fixtureD["AwayTeam"]) {
				$TEAMNUMBER = 2;
			}
			
			$this -> view -> assign("TEAMNUMBER", $TEAMNUMBER);
			}
			// Check if HomeTeam 1 And AwayTeam 2
			
			$NextFixture = $FixtureTbl -> getNextFixture($id);
			$NextFixturesDetails = array();
			if (count($NextFixture) > 0) {
				$FixturesDetails["NEXT"] = $NextFixture[0] -> toArray();
			}
			$this -> view -> assign("PREVIEW", $FixturesDetails);

		}

	}

	function resetdata($id) {
		$SquadsTbl = new Model_Squad;
		$squad = $SquadsTbl -> getSquad($id);
		$Players = json_decode($squad["Players"], true);
		if (count($Players) > 0) {
			$newPlayers = array();
			foreach ($Players as $Player) {
				if ($Player["ID"] > 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"] = @$Player["Captain"];
					$newPlayers[$Player["ID"]]["Vice"] = @$Player["Vice"];
				}
			}
			$SquadsTbl -> updateSquad(array("Players" => json_encode($newPlayers)), $id);

		}

	}
	private function ReverseData($data){
						$FT_Score = $data["OP_FT_Score"];
						$HT_Score = $data["OP_HT_Score"];
						$myTry = $data["OP_Try"];
						$myConversion = $data["OP_Conversion"];
						$myPenalty = $data["OP_Penalty"];
						$myDropgoal= $data["OP_Dropgoal"];
						$myPenaltyTry= $data["OP_PenaltyTry"];
						
						$data["OP_FT_Score"] = $data["FT_Score"];
						$data["OP_HT_Score"] = $data["HT_Score"];
						$data["OP_Try"] = $data["Try"];
						$data["OP_Conversion"] = $data["Conversion"];
						$data["OP_Penalty"] = $data["Penalty"];
						$data["OP_Dropgoal"] = $data["Dropgoal"];
						$data["OP_PenaltyTry"] = $data["PenaltyTry"];
						$data["FT_Score"] = $FT_Score;
						$data["HT_Score"] = $HT_Score;
						$data["Try"] = $myTry;
						$data["Conversion"] = $myConversion;
						$data["Penalty"] = $myPenalty;
						$data["Dropgoal"] = $myDropgoal;
						$data["PenaltyTry"] = $myPenaltyTry;
						return $data;
	}

	public function submittedinjuryAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$squads = new Model_PlayerInjury;
			$data = $request -> getParam("data");

			$data["ModifiedBy"] = $this -> identity -> UserID;
			$data["ModifiedDate"] = date("Y-m-d H:i:s");

			$data["InjuryDate"] = date("Y-m-d", strtotime($data["InjuryDate"]));
			$data["ReturnToPlay"] = date("Y-m-d", strtotime($data["ReturnToPlay"]));
			$data["ReturnToTraining"] = date("Y-m-d", strtotime($data["ReturnToTraining"]));

			if ($data["IID"] > 0 && is_numeric($data["IID"]) && isset($data["IID"])) {
				$Medical = $squads -> fetchRow("IID ='" . $data["IID"] . "'");
				$history = json_decode($Medical["History"], true);
				$history[] = $data;

				$data["History"] = json_encode($history);
				$update = $squads -> update($data, "IID ='" . $data["IID"] . "'");
				print_r($sdata);

			} else {

				$data["MedicID"] = $this -> identity -> UserID;
				$data["DateCreated"] = date("Y-m-d H:i:s");

				$data["History"] = json_encode($data);
				$Insert = $squads -> insertData($data);
			}

			//$id =$request->getParam("UserID");

		}
	}

	function deletedataplayers($sid, $id) {
		$SquadsTbl = new Model_Squad;
		$squad = $SquadsTbl -> getSquad($sid);
		$Players = json_decode($squad["Players"], true);
		if (count($Players) > 0) {
			$newPlayers = array();
			foreach ($Players as $Player) {
				if ($Player["ID"] > 0) {
					if ($Player["ID"] != $id) {
						$newPlayers[$Player["ID"]]["ID"] = $Player["ID"];
						$newPlayers[$Player["ID"]]["Position"] = @$Player["Position"];
						$newPlayers[$Player["ID"]]["Rank"] = @$Player["Rank"];
						$newPlayers[$Player["ID"]]["Jersey"] = @$Player["Jersey"];
					}
				}
			}
			$SquadsTbl -> updateSquad(array("Players" => json_encode($newPlayers)), $sid);
			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $sid);
		}

	}

	function deletedatamember($sid, $id) {
		$SquadsTbl = new Model_Squad;
		$squad = $SquadsTbl -> getSquad($sid);
		$Players = json_decode($squad["Coaches"], true);
		if (count($Players) > 0) {
			$newPlayers = array();
			foreach ($Players as $Player) {
				if ($Player["ID"] > 0) {
					if ($Player["ID"] != $id) {
						$newPlayers[$Player["ID"]]["ID"] = $Player["ID"];
						$newPlayers[$Player["ID"]]["Position"] = @$Player["Position"];
					}
				}
			}
			$SquadsTbl -> updateSquad(array("Coaches" => json_encode($newPlayers)), $sid);
			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $sid);
		}

	}

	public function copyplayersAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$data = $request -> getParams();
			$this -> removeplayers($data);
		}
	}

	public function moveplayersAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$data = $request -> getParams();
			if ($this -> addplayers($data)) {
				$this -> removeplayers($data);
			}
		}
	}

	public function addplayers($data) {
		$SquadsTbl = new Model_Squad;
		$SquadData = $SquadsTbl -> getSquadByID($data["nsid"]);
		$playesList = json_decode($SquadData["Players"], true);

		foreach ($data["players"] as $player) {
			if (!in_array($player, $playesList)) {
				$playesList[]["ID"] = $player;
			}
		}

		$SquadsTbl -> updateSquad(array("Players" => json_encode($playesList)), $data["nsid"]);
		return true;
	}

	public function removeplayers($data) {
		$SquadsTbl = new Model_Squad;
		$SquadData = $SquadsTbl -> getSquadByID($data["sid"]);
		$playesList = json_decode($SquadData["Players"], true);

		$SquadDataNew = $SquadsTbl -> getSquadByID($data["nsid"]);
		$playesListNew = json_decode($SquadDataNew["Players"], true);
		$n = 0;

		foreach ($data["players"] as $player) {

			$playesListNew[$player] = $playesList[$player];
			$n++;
		}

		print_r($playesListNew);
		$SquadsTbl -> updateSquad(array("Players" => json_encode($playesListNew)), $data["nsid"]);

		return true;
	}

	public function quickaddplayersAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		if ($request -> isPost()) {

			$SquadsTbl = new Model_Squad;

			$data = $request -> getParam("data");
			$id = $request -> getParam("id");

			if (count($data) > 0) {
				foreach ($data as $d) {
					$SquadData = $SquadsTbl -> getSquadByID($id);
					$playesList = json_decode($SquadData["Players"], true);

					if (!empty($d["LastName"]) && !empty($d["FirstName"]) && !empty($d["DateOfBirth"])) {

						$uid = $this -> checkDuplicates($d);

						$d["UnionID"] = $SquadData["Organization"];

						if ($uid == 0) {
							$profileDB = new Model_GirProfile;

							$d["FirstName"] = ucwords($d["FirstName"]);
							$d["LastName"] = ucwords($d["LastName"]);
							$d["DateCreated"] = date("Y-m-d");
							$d["YearCreated"] = date("Y");
							$d["author"] = $this -> identity -> UserID;
							$insert = $profileDB -> insertData($d);
						} else {
							$insert = $uid;
						}

						//	{:"5857","Position":"1","Jersey":"3","Rank":"0"}
						if ($insert > 0) {

							$Squads = new Model_Squad;
							$Squads -> addPlayerToSquad($id, $insert);

						}
					}
				}
			}
		}

	}

	public function getsquadsAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$type = $request -> getParam("type");
		$org = $request -> getParam("org");
		$year = $request -> getParam("year");
		$SquadTable = new Model_Squad;
		$PlayerCareer = new Model_PlayerCareer;
		$Career = $PlayerCareer -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
		$squads = json_decode($Career["Squads"], true);

		$SquadIDs = array();
		if (count($squads) > 0) {

			foreach ($squads as $sqd) {

				if (!in_array(@$sqd["SID"], $SquadIDs) && @$sqd["SID"] > 0) {

					$tourn = $SquadTable -> getMySquadByType(@$sqd["SID"], $type, $year);
					$count = 0;

					$count++;
					$SquadIDs[] = @$sqd["SID"];

					if (empty($tourn["SquadImage"])) {
						$SquadImage = "/IMGS/no-image.jpg";
					} else {
						$SquadImage = $tourn["SquadImage"];
					}
					$SquadName = $tourn["ShortName"];
					if (empty($tourn["ShortName"])) {
						$SquadName = $tourn["SquadName"];
					}

					$wallpaper = "/IMGS/wallpaper.jpg";
					$Model_WallpaperDB = new Model_Wallpaper;
					$wellpaperData = $Model_WallpaperDB -> fetchRow("SID ='" . $tourn["SID"] . "' AND Wallpaper =1 ");
					if (isset($wellpaperData["SID"]) && $wellpaperData["SID"] > 0) {
						$wallpaper = "/IMGS/" . $wellpaperData["File"];
					}
					if ($tourn["SID"] > 0) {
						echo '
					<div class="col-md-6 col-lg-4">
					<!-- Teams -->
					<div style="height:372PX " class="panel">
					<a href="/union/squads/profile/id/' . $tourn["SID"] . '" >
							<div class="team-linkable">
				   			<div class="panel-body profile" style="background: url(' . $wallpaper . ') top center no-repeat;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover; background-size: cover; background-size: 100% ; height:150px">
				            		<div class="profile-image squadBox" style=" margin-top: 100px">
				                		<img src="' . $SquadImage . '" alt="profile image" style="max-height:80px; max-width:80px;min-height:80px; min-width:80px">
				                	 </div>
				           			 <div class="profile-data">
				            			<a href=""> <h5 class="profile-data-name"><b>' . $SquadName . '</b><small> (' . $tourn["RugbyCode"] . 's)</small></h5></a>
				                		<a href="" class="">
											<span>
				                    			<span class="profile-data-data">' . $tourn["Type"] . ' <?=$MySquads["Type"]?> (' . count(json_decode($tourn["Players"], true)) . ')</span>
							            		
							        		</span>
										</a>
						     		</div>
				            	</div> 
				
				 			 	<div style="background-image:url("");filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src="", sizingMethod="scale");-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src="", sizingMethod="scale")";" class="team-photo-encase">
				   	
				  	 			</div>
				  			</div>
				  		<div class="panel-body list-group list-group-contacts" style="background:#E7E7E9;margin-top:160px;height: 60px">
				  			<div class=" list-group-contacts" style="background:#E7E7E9;padding: 10px;font-weight: bold;">                                
				    			<a href="#" class="list-group-item"  style="background: #E7E7E9">                   
				        			<img src="' . $tourn["Avatar"] . '" class="pull-left" alt="Squad picture">
                                                                    <span style="margin-top:20px; height: 88px;line-height: 18px">
				           				<span class="contact-titles">' . $tourn["LastName"] . ', ' . $tourn["FirstName"] . '</span>
				             				<p>Owner</p> </span>                                                                       
				         		</a>
                                                        </div>
						</div>
					</div>
					<!-- //Team -->
				</div>
					
					';

					}
				}
			}

		}

		if (count($SquadIDs) == 0) {
			echo ' <div class="col-md-6 col-lg-4">
					<!-- Teams -->
					<div style="height:400px ; border: 3px dashed #ccc; background:#F0F0F0" class="panel">
				
							<div class="team-linkable">
				   				<div class="panel-body profile" style=" height:335px ;background:#F0F0F0; text-align:center; line-height:335px">
				            		<a  class="btn  btn-default " onclick=" creatnewSquadBox()"
				            		style="margin:auto">Create <i class="fa fa-plus-circle"></i></a>
				          </div> 
				  	 	</div>
				  	
				  		
					</div>
					<!-- //Team -->
				</div>
					
					';
		}
	}

	function rendersquads($squads, $type, $year) {
		$SquadTable = new Model_Squad;
		$SquadIDs = array();
		$countSquads = 0;

		if (count($squads) > 0) {

			$SquadsList = array();
			foreach ($squads as $sqd) {
				if (!in_array(@$sqd["SID"], $SquadIDs) && @$sqd["SID"] > 0) {

					$tournData = $SquadTable -> getMySquadByType(@$sqd["SID"], $type, $year);

					if (isset($tournData["SID"])) {
						if ($this -> identity -> JobType == 2 && $tournData["SquadType"] < 3) {
							$SquadsList[$tournData["SID"]] = $tournData -> toArray();
						} else if ($this -> identity -> JobType != 2) {
							$SquadsList[$tournData["SID"]] = $tournData -> toArray();
						}
					}
				}
			}

			$this -> array_sort_by_column($SquadsList, "SquadName", SORT_ASC);
			foreach ($SquadsList as $tourn) {
				if (!in_array($tourn["SID"], $SquadIDs) && $tourn["SID"] > 0) {

					//$tourn = $SquadTable->getMySquadByType(@$sqd["SID"],$type,$year);
					$count = 0;

					$count++;
					$SquadIDs[] = $tourn["SID"];

					if (empty($tourn["SquadImage"])) {
						$SquadImage = "/IMGS/no-image.jpg";
					} else {
						$SquadImage = $tourn["SquadImage"];
					}
					$SquadName = $tourn["ShortName"];
					if (empty($tourn["ShortName"])) {
						$SquadName = $tourn["SquadName"];
					}

					$wallpaper = "/IMGS/wallpaper.jpg";
					$Model_WallpaperDB = new Model_Wallpaper;
					$wellpaperData = $Model_WallpaperDB -> fetchRow("SID ='" . $tourn["SID"] . "' AND Wallpaper =1 ");
					if (isset($wellpaperData["SID"]) && $wellpaperData["SID"] > 0) {
						$wallpaper = "/IMGS/" . $wellpaperData["File"];
					}
					if ($tourn["SID"] > 0) {
						$countSquads++;
						echo '
					<div class="col-md-6 col-lg-4">
					<!-- Teams -->
					<div style="height:372PX " class="panel">
					<a href="/union/squads/profile/id/' . $tourn["SID"] . '" >
							<div class="team-linkable">
				   			<div class="panel-body profile" style="background: url(' . $wallpaper . ') top center no-repeat;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover; background-size: cover; background-size: 100% ; height:150px">
				            		<div class="profile-image squadBox" style=" margin-top: 100px">
				                		<img src="' . $SquadImage . '" alt="profile image" style="max-height:80px; max-width:80px;min-height:80px; min-width:80px">
				                	 </div>
				           			 <div class="profile-data">
				            			<a  href="/union/squads/profile/id/' . $tourn["SID"] . '"> <h5 class="profile-data-name"><b>' . $SquadName . '</b><small> (' . $tourn["RugbyCode"] . 's)</small></h5></a>
				                		<a  href="/union/squads/profile/id/' . $tourn["SID"] . '" class="">
											<span>';
						if ($tourn["SquadType"] == 1) {
							echo ' <h5 class="profile-data-name" style="font-size:11px; line-height:10px"><span class="profile-data-data">' . $tourn["TournName"] . '  </span></h5>';
						}
						if ($tourn["SquadType"] == 2) {
							echo ' <h5 class="profile-data-name" style="font-size:11px; line-height:10px">' . $tourn["TournName2"] . '  </span><h5/>';
						}
						echo '
                                                             
				                    			<h5 class="profile-data-name" style="font-size:11px; line-height:10px">' . $tourn["Type"] . ' (' . count(json_decode($tourn["Players"], true)) . ')</h5> 
                                                                        ';
						if ($tourn["AgeGroup"] != 0) {
							echo '<h5 class="profile-data-name" style="font-size:11px; line-height:10px ">Under (' . $tourn["AgeGroup"] . ')</h5> ';
						} else {
							echo '<h5 class="profile-data-name" style="font-size:11px; line-height:10px">Senior</h5> ';
						}

						echo '</span></a>
						     		</div>
				            	</div> 
				
				 			 	<div style="background-image:url("");filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src="", sizingMethod="scale");-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader( src="", sizingMethod="scale")";" class="team-photo-encase">
				   	
				  	 			</div>
				  			</div>
				  		<div class="panel-body list-group list-group-contacts" style="background:#E7E7E9;margin-top:160px;height: 60px">
				  			<div class=" list-group-contacts" style="background:#E7E7E9;padding: 10px;font-weight: bold;">                                
				    			<a href="#" class="list-group-item"  style="background: #E7E7E9">                   
				        			<img src="' . $tourn["Avatar"] . '" class="pull-left" alt="Squad picture">
                                                                    <span style="margin-top:20px; height: 88px;line-height: 18px">
				           				<span class="contact-titles">' . $tourn["LastName"] . ', ' . $tourn["FirstName"] . '</span>
				             				<p>Owner</p> </span>                                                                       
				         		</a>
                                                        </div>
						</div>
					</div>
					<!-- //Team -->
				</div>
					
					';

					}
				}
			}

		}

		if ($countSquads == 0) {
			echo ' <div class="col-md-6 col-lg-4">
					<!-- Teams -->
					<div style="height:400px ; border: 3px dashed #ccc; background:#F0F0F0" class="panel">
				
							<div class="team-linkable">
				   				<div class="panel-body profile" style=" height:335px ;background:#F0F0F0; text-align:center; line-height:335px">
				            		<a  class="btn  btn-default " href="/union/squads/create/"
				            		style="margin:auto">Create <i class="fa fa-plus-circle"></i></a>
				          </div> 
				  	 	</div>
				  	
				  		
					</div>
					<!-- //Team -->
				</div>
					
					';
		}
	}

	public function getsquadadmintestAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$type = $request -> getParam("type");

		$org = $request -> getParam("org");
		$year = $request -> getParam("year");
		$SquadTable = new Model_Squad;
		if (in_array($this -> identity -> UserID, $this -> AdminUsers)) {
			if ($type == 0) {
				$type = 1;
			}
			$squads = $SquadTable -> getAllSquadsID($year, $type);

			$this -> rendersquads($squads, $type, $year);

		} else {
			$PlayerCareer = new Model_PlayerCareer;
			$Career = $PlayerCareer -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
			$squads = json_decode($Career["Squads"], true);

			//LOC

			$this -> rendersquads($squads, $type, $year);

		}
	}

	public function getsquadadminAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$type = $request -> getParam("type");

		$org = $request -> getParam("org");
		$year = $request -> getParam("year");
		$SquadTable = new Model_Squad;
		if (in_array($this -> identity -> UserID, $this -> AdminUsers)) {
			if ($type == 0) {
				$type = 1;
			}
			$squads = $SquadTable -> getAllSquadsID($year, $type);

			$this -> rendersquads($squads, $type, $year);

		} else {

			$PlayerCareer = new Model_PlayerCareer;
			$Career = $PlayerCareer -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
			$squads = json_decode($Career["Squads"], true);

			$squadslist = array();
			$Tournaments = json_decode($this -> identity -> LOC, true);
			if (count($Tournaments) > 0) {
				foreach ($Tournaments as $Tournament) {
					$squadsli = $SquadTable -> getAllSquadsTournID($year, $Tournament["TID"], $type);
					if (count($squadsli) > 0) {
						foreach ($squadsli as $Sqd) {
							$squadslist[$Sqd["SID"]]["SID"] = $Sqd["SID"];
							$squadslist[$Sqd["SID"]]["Squad"] = $Sqd["SID"];

						}
					}
				}
			}

			//LOC
			if (count($squads) > 0 && count($squadslist) > 0) {
				$squads = array_merge($squads, $squadslist);
			}
			if (count($squads) < 1 && count($squadslist) > 0) {
				$squads = $squadslist;
			}

			$this -> rendersquads($squads, $type, $year);

		}
	}

	function age($birthday) {
		if (!empty($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;
		} else {
			return "";
		}
	}

	private function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
		$sort_col = array();
		if (count($arr) > 0) {
			foreach ($arr as $key => $row) {
				@$sort_col[$key] = @$row[$col];
			}
		}
		array_multisort($sort_col, $dir, $arr);
	}

	public function savesquadsAction() {

		$Tournament = new Model_Tournament;
		$squadDB = new Model_Squad;
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$data = $request -> getParams();
			$form = $request -> getParam("form");
			$formData = explode("&", $form);
			$formArray = array();
			foreach ($formData as $key) {
				$val = explode("=", $key);
				if (!empty($val[0])) {
					$val[1] = $formArray[$val[0]] = $val[1];
				}

			}

			$formArray["Author"] = $this -> identity -> UserID;

			$formArray["DateCreated"] = date("Y-m-d H:s:i");

			$formArray["TeamManager"] = $this -> identity -> UserID;

			$OtherDATa = $data["img"];
			$IMGBASE64 = str_replace(" ", "+", $OtherDATa["img"]);
			if (!empty($IMGBASE64)) {
				$fileName = uniqid();

				$data = $IMGBASE64;
				$pos = strpos($data, ';');
				$type = explode("/", explode(':', substr($data, 0, $pos))[1])[1];
				$t = $type;
				list($type, $data) = explode(';', $data);
				list(, $data) = explode(',', $data);
				$data = base64_decode($data);

				if (file_put_contents(IMG_PATH . '/' . $fileName . '.' . $t, $data)) {

					$dst_x = 0;
					$dst_y = 0;
					$src_x = $OtherDATa["x"];
					$src_y = $OtherDATa["y"];
					$dst_w = $OtherDATa["h"];
					$dst_h = $OtherDATa["w"];

					$src_w = $src_x + $dst_w;
					$src_h = $src_y + $dst_h;

					$dst_image = imagecreatetruecolor($dst_w, $dst_h);
					if ($t == "jpeg" || $t == "jpg") {
						$src_image = imagecreatefromjpeg(IMG_PATH . '/' . $fileName . '.' . $t);
						imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
						imagejpeg($dst_image, IMG_PATH . '/Crop' . $fileName . '.' . $t);
					}

					$content = file_get_contents(IMG_PATH . '/Crop' . $fileName . '.' . $t, true);
					$base64 = base64_encode($content);
					$imageData = "data:$t;base64," . $base64;

					$imgDB = new Model_Images;
					$daone = $imgDB -> Update(array("Wallpaper" => $imageData), "UserID ='" . $this -> identity -> UserID . "'");
					if ($daone) {
						unlink(IMG_PATH . '/Crop' . $fileName . '.' . $t);
						unlink(IMG_PATH . '/' . $fileName . '.' . $t);
						$formArray["SquadImage"] = $imageData;
					}

				}
			}
			$formArray['Gender'] = $formArray['Sex'];
			unset($formArray['Sex']);

			$ID = $squadDB -> insert($formArray);
			//INSERT THE SQUAD HERE

			$details = array("Position" => 42, "ID" => $this -> identity -> UserID);
			$mySquads = $squadDB -> update(array("Coaches" => json_encode($mySquads)), "SID ='" . $ID . "'");

			$PlayersHistoryDB = new Model_PlayerCareer;
			$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");

			if ($getCurrent) {

				$squads = json_decode($getCurrent["Squads"], true);
				$i = 0;
				foreach ($squads as $squad) {
					if (@$squad["SID"] == $ID) {
						unset($squads[$i]);
					}
					$i++;
				}

				$squads[count($squads)] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $ID, "Squad" => $formArray['SquadName'], "Pos" => 42);

				$data = array("UserID" => $this -> identity -> UserID, "Squads" => json_encode($squads));

				$added = $PlayersHistoryDB -> updateData($data, $this -> identity -> UserID);

			} else {
				$squads[] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $ID, "Squad" => $formArray['SquadName'], "Pos" => 42);

				$data = array("UserID" => $this -> identity -> UserID, "Squads" => json_encode($squads));

				$PlayersHistoryDB -> insertData($data);
			}

			if ($ID > 0)//FROM SQUAD ID WE PUT SQUAD TO THE TOURNAMNET
			{

				if ($formArray['TournamentID']) {
					$TournamentDATA = $Tournament -> getTourny($tournamentID);
					$SquadsArray = json_decode($TournamentDATA["Squads"], true);
					if (!in_array($ID, $SquadsArray)) {
						$SquadsArray[] = $ID;
					}

					$saved = $Tournament -> updateData(array("Squads" => json_encode($SquadsArray)), $formArray['TournamentID']);
					if ($saved) {
						echo 1;
					}
				}
			} else {
				echo "There was an error please try again...";
			}
		}
	}

	public function checkplayersAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$data = $request -> getParams();

			echo $this -> checkDuplicates($data);

		}
	}

	private function checkDuplicates($data) {
		$profileDB = new Model_GirProfile;
		$checked = 0;
		if (strlen($data["LastName"]) == 13) {

			$check = $profileDB -> fetchRow("IDNumber ='" . $data["LastName"] . "'");
			$checked = $check["UserID"];
		} else {

			$check = $profileDB -> fetchRow("LastName ='" . ucwords($data["LastName"]) . "'");

			if ($check["Sex"] == $data["Sex"] && $check["Ethnicity"] == $data["Ethnicity"] && ucwords($check["FirstName"]) == ucwords($data["FirstName"]) && date("Y-m-d", strtotime($check["DateOfBirth"])) == date("Y-m-d", strtotime($data["DateOfBirth"]))) {
				$checked = $check["UserID"];
			}
		}

		return $checked;
	}

	public function deletememberAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$pid = $request -> getParam("pid");
			$type = $request -> getParam("type");
			$sid = $request -> getParam("sid");

			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);

			if ($type == 1) {
				$this -> deletedatamember($sid, $pid);
			} else {
				$this -> deletedataplayers($sid, $pid); ;
			}

			$playersDB = new Model_Profile;
			$historyDB = new Model_SquadsHistory;
			$history = $historyDB -> fetchRow("SID ='" . $sid . "'");

			if (!$history) {

				$historyDB -> insert(array("SID" => $sid));
				$history = array();
			} else {
				$history = json_decode($history["History"], true);
			}
			$UserID = $pid;
			$player = $playersDB -> getPlayerProfile($UserID);
			$action = $this -> identity -> FirstName . " " . $this -> identity -> LastName . " <span class='label label-red'>Removed</span> " . $player["FirstName"] . " " . $player["LastName"] . " from the  squad";

			$history[count($history)] = array("DATETIME" => date("Y-m-d H:i:s"), "USERID" => $UserID, "MESSAGE" => $action, "POSITION" => $pos, "AUTHOR" => $this -> identity -> UserID, "AUTHORFULLNAME" => $this -> identity -> FirstName . " " . $this -> identity -> LastName);

			$updateHistory = $historyDB -> update(array("History" => json_encode($history)), "SID ='" . $sid . "'");

			$PlayersHistoryDB = new Model_PlayerCareer;
			$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $UserID . "'");

			$squadsList = json_decode($getCurrent["Squads"], true);
			unset($squadsList[$sid]);

			print_r($squadsList);
			$newData = array("Squads" => json_encode($squadsList));
			$added = $PlayersHistoryDB -> updateData($newData, $UserID);

		}
	}

	public function changeposAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$pid = $request -> getParam("pid");
			$type = $request -> getParam("type");
			$sid = $request -> getParam("sid");
			$pos = $request -> getParam("pos");

			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);

			if ($type == 1) {
				$newList = array();
				$listPlayers = json_decode($squad["Coaches"], true);
				$i = 0;
				foreach ($listPlayers as $Coaches) {
					if ($Coaches["ID"] == $pid) {
						$newList[$i]["Position"] = $pos;
						$newList[$i]["ID"] = $Coaches["ID"];

					} else {
						$newList[$i]["Position"] = $Coaches["Position"];
						$newList[$i]["ID"] = $Coaches["ID"];
					}
					$i++;
				}
				$DATASAVE = array("Coaches" => json_encode($newList));
			} else {
				$newList = array();
				$listPlayers = json_decode($squad["Players"], true);
				$i = 0;
				foreach ($listPlayers as $Coaches) {
					if ($Coaches["ID"] == $pid) {
						$newList[$i]["Position"] = $Coaches["Position"];
						$newList[$i]["Jersey"] = $Coaches["Jersey"];
						$newList[$i]["Rank"] = $Coaches["Rank"];
						$newList[$i]["ID"] = $Coaches["ID"];

					} else {
						$newList[$i]["Position"] = $pos;
						$newList[$i]["Jersey"] = $Coaches["Jersey"];
						$newList[$i]["Rank"] = $Coaches["Rank"];
						$newList[$i]["ID"] = $Coaches["ID"];
					}
					$i++;
				}
				$DATASAVE = array("Players" => json_encode($newList));
			}

			$SquadsTbl -> updateSquad($DATASAVE, $sid);
			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $sid);

		}
	}

	public function addmemberAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$pid = $request -> getParam("pid");
			$type = $request -> getParam("type");
			$sid = $request -> getParam("sid");
			$role = $request -> getParam("role");

			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);
			$position = 0;
			if ($role > 0) {
				$position = $role;
			}

			if ($pid > 0) {

				if ($type == 1) {

					$listPlayers = json_decode($squad["Coaches"], true);

					$listPlayers[] = array("Position" => $position, "ID" => $pid);

					$DATASAVE = array("Coaches" => json_encode($listPlayers));

					$PlayersHistoryDB = new Model_PlayerCareer;
					$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $pid . "'");
					if ($getCurrent["UserID"] > 0) {
						$squads = json_decode($getCurrent["Squads"], true);

						$squads[count($squads)] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $sid, "Squad" => $squadDetails['SquadName'], "Pos" => $position);

						$data = array("UserID" => $pid, "Squads" => json_encode($squads));

						$added = $PlayersHistoryDB -> updateData($data, $pid);
					} else {
						$squads[0] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $sid, "Squad" => $squadDetails['SquadName'], "Pos" => $position);

						$data = array("UserID" => $pid, "Squads" => json_encode($squads));
						$PlayersHistoryDB -> insertData($data);
					}

				} else {

					$listPlayers = json_decode($squad["Players"], true);
					$listPlayers[] = array("Position" => $position, "ID" => $pid, "Jersey" => 0, "Rank" => 0);

					$DATASAVE = array("Players" => json_encode($listPlayers));

				}

				$SquadsTbl -> updateSquad($DATASAVE, $sid);

			}

		}
	}

	public function searchddAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$searchkey = $request -> getParam("searchkey");
			$type = $request -> getParam("type");

			$sid = $request -> getParam("sid");

			$squadDB = new Model_Squad;

			$ProfileDB = new Model_Profile;
			$unionID = $this -> identity -> UnionID;

			if ($this -> identity -> UnionType < 3) {
				$unionID = 0;
			}

			$ListofMembers = $ProfileDB -> SearchAll($unionID, $searchkey, $type);
			$listPlayersData = array();

			foreach ($ListofMembers as $list) {
				$add = $this -> getunionID($list, $list);
				$listPlayersData[$list["UserID"]]["Add"] = $add;
				$listPlayersData[$list["UserID"]]["Details"] = $list -> toArray();
			}
			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);

			if ($type == 1) {
				$listPlayers = json_decode($squad["Coaches"], true);

			} else {
				$listPlayers = json_decode($squad["Players"], true);
			}

			$newList = array();
			if (count($listPlayers) > 0) {
				foreach ($listPlayers as $player) {
					$newList[] = $player["ID"];
				}
			}

			echo json_encode(array("List" => $listPlayersData, "Current" => $newList));
		}
	}

	public function searchAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		if ($request -> isPost()) {
			$searchkey = $request -> getParam("searchkey");
			$type = $request -> getParam("type");

			$sid = $request -> getParam("sid");

			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);

			$ProfileDB = new Model_Profile;
			$unionID = 0;

			$ListofMembers = $ProfileDB -> SearchAllMain($unionID, $searchkey, $type);
			$listPlayersData = array();

			foreach ($ListofMembers as $list) {
				$add = 1;
				if ($squad["Organization"] == $list["UnionID"] || $squad["Organization"] == $list["parentid"]) {
					$add = 0;
				}
				$listPlayersData[$list["UserID"]] = $list -> toArray();
				$listPlayersData[$list["UserID"]]["Add"] = $add;
			}

			if ($type == 1) {
				$listPlayers = json_decode($squad["Coaches"], true);

			} else {
				$listPlayers = json_decode($squad["Players"], true);
			}

			$newList = array();
			if (count($listPlayers) > 0) {
				foreach ($listPlayers as $player) {
					$newList[] = $player["ID"];
				}
			}

			$PositionTbl = new Model_Positions;
			$allPositio = $PositionTbl -> fetchAll();
			echo json_encode(array("List" => $listPlayersData, "Current" => $newList, "Position" => $allPositio -> toArray()));
		}
	}

	public function createsquadAction() {

	}

	public function indextempAction() {

		//css for the datepicker

		$SquadsTable = new Model_Squad;
		$FixtureTable = new Model_Fixture;
		$SquadTypeDb = new Model_SquadTypes;
		$AgeGroupDb = new Model_AgeGroups;
		$PlayersHistoryDB = new Model_PlayerCareer;
		$UnionsTypes = new Model_IntuitutionTypes;
		$Unions = new Model_Unions;
		$ProfileDB = new Model_Profile;

		$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $this -> identity -> UserID . "'");
		$squads = json_decode($getCurrent["Squads"], true);

		$UpcomingTourn = array();
		if (count($squads) > 0) {
			foreach ($squads as $squad) {
				$SquadTourn = $FixtureTable -> getFixtureUpcoming(@$squad["SID"]);
				foreach ($SquadTourn->toArray() as $tourn) {
					$UpcomingTourn[] = $tourn;
				}
			}
		}

		$UserProfile = $ProfileDB -> getRow($this -> identity -> UserID);
		$this -> view -> assign("Profile", $UserProfile);

		$Types = $SquadTypeDb -> fetchAll() -> toArray();

		$this -> view -> assign('SquadTypes', $Types);

		$this -> view -> assign('UpcomingEvents', $UpcomingTourn);

		$SquadTable = new Model_Squad;

		$squads = $SquadTable -> getMyAllSquadsDrop();
		$this -> view -> assign('SchoolsList', $squads);

	}

	public function mailAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$config = array('auth' => 'login', 'username' => 'support@footprintapp.net', 'password' => 'EVO2018!');

		$transport = new Zend_Mail_Transport_Smtp('mail.footprintapp.net', $config);

		$mail = new Zend_Mail();
		$mail -> setBodyText('This is the text of the mail.');
		$mail -> setFrom('support@footprintapp.net', 'Some Sender');
		$mail -> addTo('andre.ferraz@evolveav.co.za', 'Some Recipient');
		$mail -> setSubject('TestSubject');
		$mail -> send($transport);

	}

	private function getunionID($Union, $Player) {

		$return = 0;
		if ($Union["un_type"] > 2) {

			// Check User type
			// player belongs to a user
			if ($Player["UnionType"] == 3) {
				if ($Union["parentid"] != $Player["parentid"]) {
					$return = 1;
				}
			} else if ($Player["UnionType"] > 3) {
				if ($Union["un_id"] != $Player["UnionID"]) {
					$return = 1;
				}
			}

		}

		return $return;
	}

	public function requesttranferAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$data = $request -> getParams();
		if ($request -> isPost()) {
			$Player = new Model_Profile;
			$SquadDB = new Model_Squad;
			$Squad = $SquadDB -> getSquadUnion($data["SID"]);
			$User = $Player -> getPerson($data["UID"]);
			$TRDB = new Model_TransferRequest;
			$requestData = array("UserID" => $data["UID"], "UserID" => $data["UID"], "UnionFrom" => $User["UnionID"], "UnionTo" => $Squad["un_id"], "Status" => 0, "DateRequested" => date("Y-m-d H:i:s"), "DateCompleted" => date("Y-m-d H:i:s"), "AuthorID" => $this -> identity -> UserID);
			$TRDB -> insertData($requestData);
			$Profile = $Player -> updateProfile(array("UnionID" => $Squad["un_id"], "UnionType" => $Squad["un_type"]), $data["UID"]);
			$this -> addmembertosquad($data["UID"], $data["SID"]);
			//Send Email to whom and whats the email
			$config = array('auth' => 'login', 'username' => 'support@footprintapp.net', 'password' => 'EVO2018!!');

			$transport = new Zend_Mail_Transport_Smtp('mail.footprintapp.net', $config);

			$mail = new Zend_Mail();
			$mail -> setBodyHtml('<p>Dear ' . $this -> identity -> FirstName . ' ' . $this -> identity -> LastName . ',</p>

<p>This email serves to confirm your request to transfer ' . $User["FullName"] . ' from ' . $User["un_name"] . ' to ' . $Squad["un_name"] . '.  </p>

<p>By submitting this request you confirmed that the required form(s) (Schedule II) have been signed by the CEO of ' . $User["un_name"] . ' and is currently on file at ' . $Squad["un_name"] . '.</p>

<p>Please note this request has been logged on the SA Rugby Footprint system under your ID.  Should this transfer request been done in error, please contact SA Rugby at footprint@sarugby.co.za immediately to make any corrections.</p>
<br />
<p>Regards,</p>
<p>SA Rugby Footprint Team</p>');
			$mail -> setFrom('support@footprintapp.net', 'Footprint');
			$mail -> addTo($this -> identity -> Email, $this -> identity -> FirstName . ' ' . $this -> identity -> LastName);
			$mail -> setSubject('Transfer Notification');
			$mail -> send($transport);
		}

	}

	public function addmembertosquad($id, $SID) {

		$Player = new Model_Profile;

		//$type =$request->getParam("type");
		$pos = 0;
		$historyDB = new Model_SquadsHistory;
		$SquadsTbl = new Model_Squad;
		$PlayersHistoryDB = new Model_PlayerCareer;
		$squad = $SquadsTbl -> getSquad($SID);
		$SquadsTbl -> addPlayerToSquad($SID, $id, $pos);

		$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $id . "'");

		if (isset($getCurrent["UserID"])) {
			$squads = json_decode($getCurrent["Squads"], true);
			$squads[$SID] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $SID, "Squad" => $squad['SquadName'], "Pos" => $pos);
			$data = array("UserID" => $id, "Squads" => json_encode($squads));
			$added = $PlayersHistoryDB -> updateData($data, $id);
		} else {
			$squads[$SID] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $SID, "Squad" => $squad['SquadName'], "Pos" => $pos);
			$data = array("UserID" => $id, "Squads" => json_encode($squads));
			$PlayersHistoryDB -> insertData($data);
		}

		$historyDB = new Model_SquadsHistory;
		$history = $historyDB -> fetchRow("SID ='" . $SID . "'");
		if (!$history) {
			$historyDB -> insert(array("SID" => $SID));
			$history = array();
		} else {
			$history = json_decode($history["History"], true);
		}

		$player = $Player -> getPlayerProfile($id);
		$action = $this -> identity -> FirstName . " " . $this -> identity -> LastName . " <span class='label label-success'>Added</span>  " . $player["FirstName"] . " " . $player["LastName"] . " to the  squad";
		$history[count($history)] = array("DATETIME" => date("Y-m-d H:i:s"), "USERID" => $id, "MESSAGE" => $action, "POSITION" => $pos, "AUTHOR" => $this -> identity -> UserID, "AUTHORFULLNAME" => $this -> identity -> FirstName . " " . $this -> identity -> LastName);
		$updateHistory = $historyDB -> update(array("History" => json_encode($history)), "SID ='" . $SID . "'");

		$SquadsTbl = new Model_Squad;
		$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $SID);

	}

	public function checkmemberAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$data = $request -> getParams();
		$Player = new Model_Profile;
		$SquadDB = new Model_Squad;
		$Squad = $SquadDB -> getSquadUnion($data["SID"]);

		$requestor = $Player -> getMemberNoImage($this -> identity -> UserID);
		if ($data["op"] == 1) {
			$details = $Player -> getPersonByIDNumber($data["id"]);
			if ($details["UserID"] > 0) {
				$playerDetails = $details -> toArray();

				$add = $this -> getunionID($Squad, $playerDetails);

				echo json_encode(array("Details" => $playerDetails, "UserID" => $details["UserID"], "Add" => $add, "User" => $requestor -> toArray()));
			} else {
				echo json_encode(array("UserID" => 0, "Add" => 0));
			}

		} else {
			$details = $Player -> getPersonByPasspoert($data["id"]);
			if ($details["UserID"] > 0) {
				$playerDetails = $details -> toArray();
				$add = $this -> getunionID($Squad, $playerDetails);
				echo json_encode(array("Details" => $playerDetails, "UserID" => $details["UserID"], "Add" => $add, "User" => $requestor -> toArray()));
			} else {
				echo json_encode(array("UserID" => 0, "Add" => 0));
			}
		}

	}

	public function newplayerAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$dataR = $request -> getParams();
		$Player = new Model_Profile;
		$sid = $request -> getParam("sid");

		$SquadsTbl = new Model_Squad;
		$squad = $SquadsTbl -> getSquad($sid);
		if ($request -> isPost()) {
			$POSITION = 0;

			$data = $dataR["data"];
			$UserID = 0;
			$newData = array();
			$newData["author"] = $this -> identity -> UserID;

			if ($squad["un_type"] > 0) {
				$newData["UnionType"] = $squad["un_type"];
			} else {
				$newData["UnionType"] = $this -> identity -> UnionType;
			}

			if ($squad["Organization"] > 0) {
				$newData["UnionID"] = $squad["Organization"];
			} else {
				$newData["UnionID"] = $this -> identity -> UnionID;
			}

			$newData["DateCreated"] = date("Y-m-d H:i:s");
			if ($data["UserID"] > 0) {//update

				if ($data["parentcheck"] == 1) {
					$newData["parent_Login"] = 1;
					$newData["parent_FirstName"] = $data["parent_FirstName"];
					$newData["parent_LastName"] = $data["parent_LastName"];
					$newData["parent_Cell"] = (!empty($data["parent_Cell"])) ? $data["parent_Cell"] : "";
					$newData["parent_Email"] = $data["parent_Email"];

				}

				if (isset($data["Player_Prim_Pos"])) {
					$newData["Player_Prim_Pos"] = @$data["Player_Prim_Pos"];
					$POSITION = $newData["Player_Prim_Pos"];
				}
				$newData["SecondarySchool"] = @$data["sSchool"];
				$newData["PrimarySchool"] = (isset($data["pSchool"])) ? $data["pSchool"] : "";
				$newData["TertiaryInstitution"] = (isset($data["TertiaryInstitution"])) ? $data["TertiaryInstitution"] : "";
				$newData["Club"] = (isset($data["Club"])) ? $data["Club"] : "";
				$newData["DateOfBirth"] = $data["DateOfBirth"];
				$newData["Email"] = (isset($data["Email"])) ? $data["Email"] : "";
				$Player -> updateProfile($newData, $data["UserID"]);

				$UserID = $data["UserID"];
			} else {
				$newData["JobType"] = 2;

				if ($squad["SquadType"] > 4 && $squad["SquadType"] < 12) {
					$newData["ConfirmedDetails"] = 1;
					$newData["Scouted"] = 1;
					$newData["ScoutID"] = $this -> identity -> UserID;

				}
				$newData["IDType"] = $data["IDType"];
				$newData["IDNumber"] = $data["IDNumber"];
				$newData["PassportNumber"] = $data["PassportNumber"];
				$newData["FirstName"] = $data["FirstName"];
				$newData["LastName"] = $data["LastName"];
				if (isset($data["Player_Prim_Pos"])) {
					$newData["Player_Prim_Pos"] = @$data["Player_Prim_Pos"];
					$POSITION = $newData["Player_Prim_Pos"];
				}
				$newData["Sex"] = $data["Sex"];

				if (!empty($data["pSchool"])) {
					$newData["PrimarySchool"] = $data["pSchool"];
				}
				if (!empty($data["pSchool"])) {
					$newData["SecondarySchool"] = $data["sSchool"];
				}
				$newData["PrimarySchool"] = (isset($data["pSchool"])) ? $data["pSchool"] : "";
				$newData["TertiaryInstitution"] = (isset($data["TertiaryInstitution"])) ? $data["TertiaryInstitution"] : "";
				$newData["Club"] = (isset($data["Club"])) ? $data["Club"] : "";
				$newData["Email"] = (isset($data["Email"])) ? $data["Email"] : "";

				$newData["Ethnicity"] = $data["Ethnicity"];
				if ($data["parentcheck"] == 1) {
					$newData["parent_Login"] = 1;
					$newData["parent_FirstName"] = $data["parent_FirstName"];
					$newData["parent_LastName"] = $data["parent_LastName"];
					$newData["parent_Cell"] = $data["parent_Cell"];
					$newData["parent_Email"] = $data["parent_Email"];
					$newData["Email"] = $data["parent_Email"];

				}

				$newData["DateOfBirth"] = $data["DateOfBirth"];

				$CredentialsDB = new Model_Credentials;
				$UserID = $Player -> insertData($newData);
				$EmailContent = new PG_Controller_Plugin_EmailLayout;
				if ($data["parentcheck"] == 1) {
					//Create Login with parent details and send email to parent

					$password = $this -> getPassword();

					$dataCre = array("Username" => $newData["parent_Email"], "Password" => md5($password), "UserID" => $UserID, "FPLogin" => 1);

					$CheckCre = $CredentialsDB -> fetchRow("Username ='" . $newData["parent_Email"] . "'");
					if ($CheckCre["UserID"] > 0) {
						//$create = $CredentialsDB->updateData(array("UserID"=>$UserID),"Username ='".$newData["parent_Email"]."'");
						$EmailContent = new PG_Controller_Plugin_EmailLayout;
						$EmailContent -> EmailTemplate2(15, $this -> identity -> UserID, $UserID, $sid, "Was previously sent to you ");
					} else {
						$create = $CredentialsDB -> insertData($dataCre);
						$EmailContent -> EmailTemplate2(15, $this -> identity -> UserID, $UserID, $sid, $password);

					}

					$EmailContent -> EmailTemplateManger(17, $this -> identity -> UserID, $UserID, $sid);

				} else if ($data["userlogincheck"]) {
					$password = $this -> getPassword();
					$dataCre = array("Username" => $newData["Email"], "Password" => md5($password), "UserID" => $UserID, "FPLogin" => 1);

					$CheckCre = $CredentialsDB -> fetchRow("Username ='" . $newData["Email"] . "'");
					if ($CheckCre["UserID"] > 0) {
						//$create = $CredentialsDB->updateData(array("UserID"=>$UserID),"Username ='".$newData["parent_Email"]."'");
						$EmailContent = new PG_Controller_Plugin_EmailLayout;
						$EmailContent -> EmailTemplate($newData["Email"], $UserID, 1, 1, "Was previously sent to you ");
					} else {
						$create = $CredentialsDB -> insertData($dataCre);
						@$EmailContent = new PG_Controller_Plugin_EmailLayout;
						@$EmailContent -> EmailTemplate($newData["Email"], $UserID, 1, 1, $password);

					}
				} else {

					if ($squad["AgeGroup"] > 0) {
						if ($squad["AgeGroup"] < 19) {
							$EmailContent -> EmailTemplateManger(16, $this -> identity -> UserID, $UserID, $sid);
						}
					}
				}

			}
			if ($UserID > 0) {

				//Add To Squad
				$Squads = new Model_Squad;
				$Squads -> addPlayerToSquad($sid, $UserID, $POSITION);

				$PlayersHistoryDB = new Model_PlayerCareer;
				$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $UserID . "'");
				if (isset($getCurrent["UserID"])) {
					$squads = json_decode($getCurrent["Squads"], true);

					$squads[$sid] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $sid, "Squad" => $squad['SquadName'], "Pos" => 0);

					$data = array("UserID" => $UserID, "Squads" => json_encode($squads));

					$added = $PlayersHistoryDB -> updateData($data, $UserID);
				} else {
					$squads[$sid] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $sid, "Squad" => $squad['SquadName'], "Pos" => 0);

					$data = array("UserID" => $UserID, "Squads" => json_encode($squads));
					$PlayersHistoryDB -> insertData($data);
				}

				$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 . " 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)), $UserID);
					$errro = "None";

				} else {

					$History[] = array("DATE" => date("Y-m-d H:i:s"), "MESSAGE" => $this -> identity -> FirstName . " " . $this -> identity -> FirstName . " Create this profile and added to ");
					;
					$Details[] = array("DATE" => date("Y-m-d H:i:s"), "CONTENT" => $Data);
					$historyPlayerDb -> insertData(array("UserID" => $UserID, "History" => json_encode($History), "Details" => json_encode($Details)));

				}

				$historyDB = new Model_SquadsHistory;
				$history = $historyDB -> fetchRow("SID ='" . $sid . "'");

				if (!$history) {

					$historyDB -> insert(array("SID" => $sid));
					$history = array();
				} else {
					$history = json_decode($history["History"], true);
				}

				$player = $Player -> getPlayerProfile($UserID);
				$action = $this -> identity -> FirstName . " " . $this -> identity -> LastName . " <span class='label label-success'>Added</span>  " . $player["FirstName"] . " " . $player["LastName"] . " to the  squad";
				$history[count($history)] = array("DATETIME" => date("Y-m-d H:i:s"), "USERID" => $UserID, "MESSAGE" => $action, "POSITION" => $pos, "AUTHOR" => $this -> identity -> UserID, "AUTHORFULLNAME" => $this -> identity -> FirstName . " " . $this -> identity -> LastName);
				$updateHistory = $historyDB -> update(array("History" => json_encode($history)), "SID ='" . $sid . "'");

			}

			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $sid);
			echo $UserID;
			//add to squads
		}

	}

	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 newmemberAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$dataR = $request -> getParams();
		$Player = new Model_Profile;
		$sid = $request -> getParam("sid");
		$SquadsTbl = new Model_Squad;
		$squad = $SquadsTbl -> getSquad($sid);
		if ($request -> isPost()) {
			$data = $dataR["data"];
			$JobTitle = $data["JobTitle"];
			if ($JobTitle > 0) {
				$User_typeDB = new Model_UserType;
				$jobTypeRow = $User_typeDB -> getRow($JobTitle);
				$jobType = $jobTypeRow["parent"];
			}
			$UserID = 0;
			$newData = array();

			$Message = "";
			if ($data["UserID"] > 0) {//update

				if (!empty($data["DateOfBirth"])) {
					$newData["DateOfBirth"] = $data["DateOfBirth"];
				}
				if (!empty($data["boksmart"])) {
					$newData["boksmart"] = $data["boksmart"];
				}
				$newData["Mobile"] = $data["Mobile"];
				$newData["Email"] = $data["Email"];
				$Player -> updateProfile($newData, $data["UserID"]);
				$UserID = $data["UserID"];
				$newData["Status"] = 1;
				$newData["Active"] = 1;
				if ($squad["SquadType"] < 3) {
					if (!filter_var($newData["Email"], FILTER_VALIDATE_EMAIL) === true) {
						$EmailContent = new PG_Controller_Plugin_EmailLayout;
						$EmailContent -> EmailTemplateAddedToSquad($newData["Email"], 18, $UserID, $sid, "", $data["JobTitle"]);
						$Message = "Added player to squad (" . $squad["SquadName"] . ") ";
					}
				}
			} else {

				if ($squad["un_type"] > 0) {
					$newData["UnionType"] = $squad["un_type"];
				} else {
					$newData["UnionType"] = $this -> identity -> UnionType;
				}
				$newData["DateCreated"] = date("Y-m-d H:i:s");
				if ($squad["Organization"] > 0) {
					$newData["UnionID"] = $squad["Organization"];
				} else {
					$newData["UnionID"] = $this -> identity -> UnionID;
				}

				$newData["IDType"] = $data["IDType"];
				$newData["IDNumber"] = $data["IDNumber"];
				$newData["PassportNumber"] = $data["PassportNumber"];
				$newData["FirstName"] = $data["FirstName"];
				$newData["LastName"] = $data["LastName"];
				$newData["Sex"] = $data["Sex"];
				$newData["JobTitle"] = $JobTitle;
				$newData["JobType"] = $jobType;
				$newData["Ethnicity"] = $data["Ethnicity"];
				$newData["boksmart"] = $data["boksmart"];
				$newData["Mobile"] = $data["Mobile"];
				$newData["Email"] = $data["Email"];
				$newData["DateOfBirth"] = $data["DateOfBirth"];
				$newData["Status"] = 1;
				$newData["Active"] = 1;
				$UserID = $Player -> insertData($newData);
				$Message = "Created this player and added  to squad (" . $squad["SquadName"] . ") ";
				if ($UserID > 0) {

					if ($squad["SquadType"] < 3) {
						$CredentialsDB = new Model_Credentials;

						$password = $this -> getPassword();
						$dataCre = array("Username" => $newData["Email"], "Password" => md5($password), "UserID" => $UserID, "FPLogin" => 1);
						try {
							$CheckCre = $CredentialsDB -> insert($dataCre);
						} catch (Exception $ex) {
							$CheckCre = $CredentialsDB -> update($dataCre, "Username='" . $data["Email"] . "'");
						}
						//

						if (!filter_var($newData["Email"], FILTER_VALIDATE_EMAIL) === true) {
							$EmailContent = new PG_Controller_Plugin_EmailLayout;
							$EmailContent -> EmailTemplateAddedToSquad($newData["Email"], 19, $UserID, $sid, $password, $data["JobTitle"]);
						}
					}
				}
			}

			$historyPlayerDb = new Model_PlayersHistory;
			$historyPlayer = $historyPlayerDb -> getHistory($UserID);

			$History = json_decode($historyPlayer["History"], true);
			$History[] = array("DATE" => date("Y-m-d H:i:s"), "MESSAGE" => $this -> identity -> FirstName . " " . $this -> identity -> FirstName . " " . $Message);

			if (isset($historyPlayer["UserID"])) {

				$Details = json_decode($historyPlayer["Details"], true);
				$Details[] = array("DATE" => date("Y-m-d H:i:s"), "CONTENT" => $newData);
				$historyPlayerDb -> updateData(array("History" => json_encode($History), "Details" => json_encode($Details)), $UserID);

			} else {

				$Details[] = array("DATE" => date("Y-m-d H:i:s"), "CONTENT" => $newData);
				$historyPlayerDb -> insertData(array("UserID" => $id, "History" => json_encode($History), "Details" => json_encode($Details)));

			}
			if ($UserID > 0) {

				$playerData["ID"] = $UserID;
				$playerData["Position"] = $JobTitle;

				$listPlayers = json_decode($squad["Coaches"], true);
				$playersForSquad = array();
				if (count($listPlayers) > 0) {

					foreach ($listPlayers as $P) {
						if ($P["ID"] > 0 && $P["ID"] != $UserID) {
							$playersForSquad[] = $P;
						}
					}
				}

				$playersForSquad[] = $playerData;
				$SquadsTbl -> updateSquad(array("Coaches" => json_encode($playersForSquad)), $sid);

				if ($data["JobTitle"] == 42) {
					$SquadsTbl -> updateSquad(array("TeamManager" => $UserID), $sid);
				}

				$PlayersHistoryDB = new Model_PlayerCareer;
				$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $UserID . "'");

				if (isset($getCurrent["UserID"])) {
					$squads = json_decode($getCurrent["Squads"], true);

					$squads[$sid] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $sid, "Squad" => $squad['SquadName'], "Pos" => $JobTitle);

					$data = array("UserID" => $UserID, "Squads" => json_encode($squads));

					$added = $PlayersHistoryDB -> updateData($data, $UserID);
				} else {
					$squads[$sid] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $sid, "Squad" => $squad['SquadName'], "Pos" => $JobTitle);

					$data = array("UserID" => $UserID, "Squads" => json_encode($squads));
					$PlayersHistoryDB -> insertData($data);
				}

				$historyDB = new Model_SquadsHistory;
				$history = $historyDB -> fetchRow("SID ='" . $sid . "'");

				if (!$history) {

					$historyDB -> insert(array("SID" => $sid));
					$history = array();
				} else {
					$history = json_decode($history["History"], true);
				}

				$player = $Player -> getPlayerProfile($UserID);
				//$action = $this->identity->FirstName." ".$this->identity->LastName." <span class='label label-red'>Removed</span> ".$player["FirstName"]." ".$player["LastName"]." from the  squad";

				$action = $this -> identity -> FirstName . " " . $this -> identity -> LastName . " <span class='label label-success'>Added</span>  " . $player["FirstName"] . " " . $player["LastName"] . " to the  squad";

				$history[count($history)] = array("DATETIME" => date("Y-m-d H:i:s"), "USERID" => $UserID, "MESSAGE" => $action, "POSITION" => $pos, "AUTHOR" => $this -> identity -> UserID, "AUTHORFULLNAME" => $this -> identity -> FirstName . " " . $this -> identity -> LastName);

				$updateHistory = $historyDB -> update(array("History" => json_encode($history)), "SID ='" . $sid . "'");
			}
			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $sid);
			echo $UserID;
			//add to squads
		}

	}

	public function uploadimagesquadAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		$sid = $request -> getParam("sid");
		if ($request -> isPost()) {
			$IMGBASE64 = str_replace(" ", "+", $request -> getParam("Avatar"));
			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> updateSquad(array("SquadImage" => $IMGBASE64), $sid);

			$historyDB = new Model_SquadsHistory;
			$history = $historyDB -> fetchRow("SID ='" . $sid . "'");

			if (!$history) {

				$historyDB -> insert(array("SID" => $sid));
				$history = array();
			} else {
				$history = json_decode($history["History"], true);
			}

			$action = $this -> identity -> FirstName . " " . $this -> identity -> LastName . " <span class='label label-red'>Removed</span> Change Squad Logo";

			$history[count($history)] = array("DATETIME" => date("Y-m-d H:i:s"), "USERID" => 0, "MESSAGE" => $action, "POSITION" => 0, "AUTHOR" => $this -> identity -> UserID, "AUTHORFULLNAME" => $this -> identity -> FirstName . " " . $this -> identity -> LastName);

			$updateHistory = $historyDB -> update(array("History" => json_encode($history)), "SID ='" . $sid . "'");
		}
	}

	public function uploadimageAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$sid = $request -> getParam("sid");
		if ($request -> isPost()) {
			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);

			$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)));

					}

					$SquadPlayerProfileDB = new Model_Squadplayerprofile;

					$update2 = $SquadPlayerProfileDB -> updateData(array("File" => $IMGBASE64, "UserID" => $id, "SID" => $sid, "thumb" => $this -> thumbnail_data_uri(IMG_PATH . '/' . $fileName . '.jpg', 100, 100)), $id, $sid);
					if (!$update2) {
						$done = $SquadPlayerProfileDB -> insertData(array("File" => $IMGBASE64, "UserID" => $id, "SID" => $sid, "thumb" => $this -> thumbnail_data_uri(IMG_PATH . '/' . $fileName . '.jpg', 100, 100)));

					}

					unlink(IMG_PATH . '/' . $fileName . '.jpg');

				}
			}

			//HISTORY
			$historyPlayerDb = new Model_PlayersHistory;
			$historyPlayer = $historyPlayerDb -> getHistory($id);
			$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 in squad (" . $squad["SquadName"] . ")");
			if (isset($historyPlayer["UserID"])) {
				$historyPlayerDb -> updateData(array("History" => json_encode($History)), $id);

			} else {
				$historyPlayerDb -> insertData(array("UserID" => $id, "History" => json_encode($History)));

			}

		}

	}

	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 rankingAction() {
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$ID = $request -> getParam("pid");
		$SID = $request -> getParam("sid");
		$pos = $request -> getParam("pos");
		$profileDB = new Model_Profile;
		$rankingDB = new Model_Ranking;
		$squadsDB = new Model_Squad;
		$Squad = $squadsDB -> fetchRow("SID ='" . $SID . "'");
		$players = json_decode($Squad["Players"], true);

		$PRanking = "N/A";
		$CRanking = "N/A";

		$Rankings = $rankingDB -> fetchAll("SID ='" . $SID . "' AND UserID ='" . $ID . "'");
		if (count($Rankings -> toArray()) > 0) {
			$count = count($Rankings -> toArray());
			$PRanking = $Rankings[$count - 1]["PRanking"];
			$CRanking = $Rankings[$count - 1]["CRanking"]; ;
		} else {
			foreach ($players as $player) {
				if ($player["ID"] == $ID) {
					if ($player["Rank"] > 0) {
						$CRanking = $player["Rank"];
					}

				}
			}
		}

		if ($request -> isPost()) {

			$rank = $request -> getParam("rank");
			$comm = $request -> getParam("comm");
			$data = array("UserID" => $ID, "SID" => $SID, "PRanking" => $CRanking, "CRanking" => $rank, "Author" => $this -> identity -> UserID, "AuthorNAme" => $this -> identity -> LastName . " " . $this -> identity -> FirstName, "DateCreated" => date("Y-m-d H:i:s"), "Comments" => $comm);
			$rankingDB -> insertData($data);
			$NewPlayera = array();
			foreach ($players as $player) {
				if ($player["ID"] == $ID) {
					$NewPlayera[$ID]["ID"] = $player["ID"];
					$NewPlayera[$ID]["Position"] = $player["Position"];
					$NewPlayera[$ID]["Jersey"] = $player["Jersey"];
					$NewPlayera[$ID]["Rank"] = $rank;
				} else {
					$NewPlayera[$player["ID"]]["ID"] = $player["ID"];
					$NewPlayera[$player["ID"]]["Position"] = $player["Position"];
					$NewPlayera[$player["ID"]]["Jersey"] = $player["Jersey"];
					$NewPlayera[$player["ID"]]["Rank"] = $player["Rank"];
				}
			}
			$squadsDB -> updateSquad(array("Players" => json_encode($NewPlayera)), $SID);

		}

		$Profile = $profileDB -> getProfileForRanking($ID, $pos);
		$this -> view -> assign("Profile", $Profile -> toArray());
		$this -> view -> assign("pid", $ID);
		$this -> view -> assign("sid", $SID);
		$this -> view -> assign("pos", $pos);
		$this -> view -> assign("Ranking", array("Previous" => $PRanking, "Current" => $CRanking));
		$SquadsTbl = new Model_Squad;
		$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $SID);

	}

	public function calenderAction() {
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$startingdate = $request -> getParam("startingdate");
		if (!$startingdate) {
			$startingdate = date("Y-m-d");
		}

		$squadsDB = new Model_Squad;
		$Squad = $squadsDB -> fetchRow("SID ='" . $sid . "'");
		$FixturesDB = new Model_Fixture;
		$Fixtures = $FixturesDB -> getFixtureForCal($sid);
		$FixturesList = array();
		if (count($Fixtures) > 0) {
			$addded = array();
			foreach ($Fixtures->toArray() as $Fixture) {

				$FixturesList[strtotime($Fixture["FixtureDate"])][$Fixture["FID"]] = $Fixture;

			}

		}

		$this -> view -> assign("Fixtures", $FixturesList);
		$this -> view -> assign("StrDate", $startingdate);
		$this -> view -> assign("SID", $sid);
		$this -> view -> assign("SQUAD", $Squad);
		if ($this -> identity -> UserID == 1) {
			/* $this->_helper->viewRenderer('squads/calendertest', null, true);
			 echo "<pre>";
			 print_r($FixturesList);
			 */
		}
		//

	}

	public function calendertestAction() {
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$startingdate = $request -> getParam("startingdate");
		if (!$startingdate) {
			$startingdate = date("Y-m-d");
		}

		$squadsDB = new Model_Squad;
		$Squad = $squadsDB -> fetchRow("SID ='" . $sid . "'");
		$FixturesDB = new Model_Fixture;
		$Fixtures = $FixturesDB -> getFixtureForCal($sid);
		$FixturesList = array();
		if (count($Fixtures) > 0) {
			foreach ($Fixtures->toArray() as $Fixture) {
				$FixturesList[strtotime($Fixture["FixtureDate"])][] = $Fixture;
			}
		}

		$this -> view -> assign("Fixtures", $FixturesList);
		$this -> view -> assign("StrDate", $startingdate);
		$this -> view -> assign("SID", $sid);
		$this -> view -> assign("SQUAD", $Squad);

	}

	public function squadsheetAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		require_once ("dompdf/dompdf_config.inc.php");
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$url = "http://footprintapp.net/pdf/squadsheet/id/" . $id;

		$html = file_get_contents($url);
		$html = $this -> AfrReplace($html);

		$dompdf = new DOMPDF();
		$dompdf -> load_html($html);

		$SquadDB = new Model_Squad;
		$Squad = $SquadDB -> getSquad($id);
		$name = $Squad['ShortName'];
		if ($Squad["SquadType"] == 1) {
			$TourDB = new Model_Tournament;
			$Tourn = $TourDB -> getTourny($Squad["TournamentID"]);
			$name = $Tourn["TournName"] . "-" . $name;
		}
		if ($Squad["SquadType"] == 2) {
			$TourDB = new Model_Tournament;
			$Tourn = $TourDB -> getTourny($Squad["TIDs"]);
			$name = $Tourn["TournName"] . "-" . $name;
		}

		$dompdf -> set_paper('a3', 'portrait');
		$dompdf -> render();
		$dompdf -> stream($name . "-" . date("Y-m-dH:i:s") . ".pdf");
	}

	public function checknewemailAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$email = $request -> getParam("email");
			$id = $request -> getParam("id");

			$Profile_Model = new Model_Profile;
			$Profile = $Profile_Model -> checkemail($email, $id);
			echo count($Profile);
		}

	}

	public function AfrReplace($string) {
		$string = str_replace("ë", "e", $string);
		$string = str_replace("Ë", "E", $string);
		$string = str_replace("è", "e", $string);
		$string = str_replace("È", "E", $string);
		$string = str_replace("é", "e", $string);
		$string = str_replace("ê", "e", $string);
		$string = str_replace("ï", "i", $string);
		$string = str_replace("ò", "o", $string);
		$string = str_replace("ü", "u", $string);
		return $string;
	}

	public function competitionsquadstatsAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$SID = $request -> getParam("SID");
		$FilterBypos = $request -> getParam("pos");

		$squadsDB = new Model_Squad;
		$DATA = $squadsDB -> fetchRow("SID ='" . $SID . "'");

		$ProfileDB = new Model_Profile;

		$PlayersArray = json_decode($DATA["Players"], true);
		$ConfirmedPlayers = json_decode($DATA["ConfirmedPlayers"], true);

		$PLAYERSLIST = array();
		$COUNT = 0;
		$TotalCOUNT = 0;
		$DEMOGRAPHICS["African"] = 0;
		$DEMOGRAPHICS["Coloured"] = 0;
		$DEMOGRAPHICS["Indian"] = 0;
		$DEMOGRAPHICS["White"] = 0;
		$DEMOGRAPHICS["Undefined"] = 0;

		if (count($PlayersArray) > 0) {
			if (isset($PlayersArray["Jersey"])) {
				$this -> array_sort_by_column($PlayersArray, 'Jersey');
			}

			foreach ($PlayersArray as $d) {

				$Profile = $ProfileDB -> getProfileWithCareer($d["ID"], $d["Position"], $DATA["RugbyCode"]);

				if ($Profile["UserID"] > 0) {

					$PlayerInjury = new Model_PlayerInjury;
					$getIngetRy = $PlayerInjury -> fetchRow("UserID ='" . $d["ID"] . "' AND ReturnToPlay > '" . date("Y-m-d") . "'");
					$injury = 0;
					if ($getIngetRy) {

						if ($getIngetRy["ReturnToTraining"] <= date("Y-m-d")) {
							$injury = 1;
						} else {
							$injury = 2;
						}
					}

					if ($FilterBypos > 0) {
						if ($d["Position"] == $FilterBypos) {

							$Profile = $Profile -> toArray();
							$Profile["PositionNo"] = $d["Position"];
							$Profile["SID"] = $SID;
							$Profile["Jersey"] = $d["Jersey"];
							$Profile["Rank"] = $d["Rank"];
							$Profile["ReturnToTraining"] = $injury;
							$Profile["DATA"] = $Profile2;
							$PLAYERSLIST[] = $Profile;

							if (!empty($Profile["Ethnicity"])) {
								$DEMOGRAPHICS[$Profile["Ethnicity"]]++;
							}
							//ENTHNICITY

							$TotalCOUNT++;
						}
					} else {
						$Profile = $Profile -> toArray();
						$un_name = $Profile["un_name"];
						if ($DATA['AgeGroup'] < 14 && $DATA['AgeGroup'] > 0) {
							$un_name = $Profile["PrimarySchool"];
						} else if ($DATA['AgeGroup'] > 13 && $DATA['AgeGroup'] < 18) {
							$un_name = $Profile["SecondarySchool"];
						}

						$PROFILEDOC = 0;
						// 1  4
						$IDDOC = 0;
						// 1 1
						$INDEMNITY = 0;
						// 5  16
						$PROFILEDOCFile = "";
						$IDDOCFile = "";
						$INDEMNITYFile = "";
						//Question when uploading a file do we link it to the squad
						$db = new Model_Documents;
						$documents = $db -> getForPlayer($Profile["UserID"]);
						if (count($documents) > 0) {
							foreach ($documents as $document) {
								if ($document["Category"] == 1 && $document["FileType"] == 4) {
									$PROFILEDOC = 1;
									$PROFILEDOCFile = $document["File"];

								}
								if ($document["Category"] == 1 && $document["FileType"] == 1) {
									$IDDOC = 1;
									$IDDOCFile = $document["File"];

								}

								if ($document["Category"] == 5 && $document["FileType"] == 16) {
									$INDEMNITY = 1;
									$INDEMNITYFile = $document["File"];
								}

							}
						}

						$Confirmed = 0;
						if (isset($ConfirmedPlayers[$Profile["UserID"]])) {
							$Confirmed = $Profile["UserID"];
						}
						$Profile["CONFIRMED"] = $Confirmed;
						$Profile["Update"] = ($Profile["DateModified"] != "0000-00-00 00:00:00") ? 1 : 0;
						$Profile["PROFILEDOC"] = $PROFILEDOC;
						$Profile["IDDOC"] = $IDDOC;
						$Profile["INDEMNITY"] = $INDEMNITY;

						$Profile["PROFILEDOCLink"] = $PROFILEDOCFile;
						$Profile["IDDOCLink"] = $IDDOCFile;
						$Profile["INDEMNITYLink"] = $INDEMNITYFile;

						$Profile["un_name"] = $un_name;
						$Profile["PositionNo"] = $d["Position"];
						$Profile["SID"] = $SID;
						$Profile["Jersey"] = $d["Jersey"];
						$Profile["Rank"] = $d["Rank"];
						$Profile["ReturnToTraining"] = $injury;
						$Profile["Captain"] = (!empty($d["Captain"])) ? $d["Captain"] : 0; ;
						$Profile["Vice"] = (!empty($d["Vice"])) ? $d["Vice"] : 0; ;

						$Profile["DATA"] = $Profile2;
						$PLAYERSLIST[] = $Profile;

						//ENTHNICITY
						if (!empty($Profile["Ethnicity"])) {
							$DEMOGRAPHICS[$Profile["Ethnicity"]]++;
						}

						$TotalCOUNT++;
					}
					$COUNT++;
				}

			}

		}
		$avarage = $DEMOGRAPHICS["African"] + $DEMOGRAPHICS["Coloured"];

		$all = 0;
		foreach ($DEMOGRAPHICS as $thni) {
			$all = $all + $thni;
		}

		$percentage = floor(($avarage) / $all * 100);

		if ($request -> isPost()) {
			echo json_encode(array("Players" => $PLAYERSLIST, "Count" => $COUNT, "Transform" => $DEMOGRAPHICS, "Percent" => $percentage));
		} else {
			echo "<pre>";
			print_r($PLAYERSLIST);

		}

		//echo "<pre>";
		//					print_r($PLAYERSLIST);
	}
	public function getmemberstestAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$reQuest = $this -> getRequest();
		
			$sid = $reQuest -> getParam("sid");
			$type = $reQuest -> getParam("type");
			$sort = $reQuest -> getParam("sort");

			$SquadsTbl = new Model_Squad;
			if($type==1){
				$squad = $SquadsTbl -> SquadCoaches($sid);
			}else{
				$squad = $SquadsTbl -> SquadPlayers($sid);
			}
			
			echo "<pre>";
			if(count($squad)>0){
				print_r($squad->toArray());
			}
			

	}

	public function getmembersAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$reQuest = $this -> getRequest();
		//if ($reQuest -> isPost()) {
			$sid = $reQuest -> getParam("sid");
			$type = $reQuest -> getParam("type");
			$sort = $reQuest -> getParam("sort");

			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($sid);
			

			if ($type == 1) {
				$profileDB = new Model_Profile;
				$listPlayers = json_decode($squad["Coaches"], true);

			} else {
				if ($squad["SquadType"] > 12) {
					$profileDB = new Model_GirProfile;
				} else {
					$profileDB = new Model_Profile;
				}

				$listPlayers = json_decode($squad["Players"], true);
			}
			$Image = "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";
			$NewplaersArray = array();
			$list = array();
			$ArrayCheck = array();
			$i = 0;

			if (count($listPlayers) > 0) {
				$ConfirmedPlayers = json_decode($squad["ConfirmedPlayers"], true);
				foreach ($listPlayers as $player) {

					if ($type == 1) {
						//* Get Members */
						$getProfile = $profileDB -> GetPesonnalByPositions($player["ID"], $player["Position"]);
						if (empty($getProfile["Avatar"]) || $getProfile["Avatar"] == "null") {
							$getProfile["Avatar"] = $Image;
						}
						$Profile2 = array();
						if ($getProfile["UserID"] > 0) {

							if (!empty($getProfile["NickName"])) {
								$getProfile["FirstName"] = $getProfile["NickName"];
							}

							$NewplaersArray[$player['ID']]["UserID"] = $getProfile["UserID"];
							$NewplaersArray[$player['ID']]["Avatar"] = $getProfile["Avatar"];
							$NewplaersArray[$player['ID']]["FirstName"] = $getProfile["FirstName"];
							$NewplaersArray[$player['ID']]["LastName"] = $getProfile["LastName"];
							$NewplaersArray[$player['ID']]["FullName"] = $getProfile["FullName"];
							$NewplaersArray[$player['ID']]["Postion"] = $getProfile["POS"];
							$NewplaersArray[$player['ID']]["PostionNo"] = $player["Position"];
							$NewplaersArray[$player['ID']]["boksmart"] = $getProfile["boksmart"];
							$NewplaersArray[$player['ID']]["PID"] = $getProfile["PID"];

							$list[$player['ID']] = $player;
						}
						$i++;
					} else {
						//* Get Players */
						$getProfile = $profileDB -> getProfileCareer_For_Squads($player['ID'], $player['Position'], $squad["RugbyCode"]);
						if ($getProfile["UserID"] > 0 && !in_array($getProfile["UserID"], $ArrayCheck)) {

							$PlayerInjury = new Model_PlayerInjury;
							$getIngetRy = $PlayerInjury -> fetchRow("UserID ='" . $player["ID"] . "' AND ReturnToPlay >= '" . date("Y-m-d") . "'");
							$injury = 0;
							if ($getIngetRy) {
								if ($getIngetRy["ReturnToTraining"] <= date("Y-m-d")) {
									$injury = 1;
								} else {
									$injury = 2;

								}

							}

							$PROFILEDOC = 0;
							// 1  4
							$IDDOC = 0;
							// 1 1
							$INDEMNITY = 0;
							// 5  16
							//Question when uploading a file do we link it to the squad
							$db = new Model_Documents;
							$documents = $db -> getForPlayer($getProfile["UserID"]);
							if (count($documents) > 0) {
								foreach ($documents as $document) {
									if ($document["Category"] == 1 && $document["FileType"] == 4) {
										$PROFILEDOC = 1;
									}
									if ($document["Category"] == 1 && $document["FileType"] == 1) {
										$IDDOC = 1;
									}

									if ($document["Category"] == 5 && $document["FileType"] == 16) {
										$INDEMNITY = 1;
									}

								}
							}
							$SquadPlayerPhoto = new Model_Squadplayerprofile;
							$PlayerPhoto = $SquadPlayerPhoto -> fetchRow("UserID ='" . $player['ID'] . "' AND SID ='" . $sid . "'");
							if ($PlayerPhoto["File"] == null || !isset($PlayerPhoto)) {
								if (empty($getProfile["Avatar"]) || $getProfile["Avatar"] == "null") {
									$PlayerPhoto["Thumb"] = $Image;
								} else {
									$PlayerPhoto["Thumb"] = $getProfile["Avatar"];
								}

							}
							if (!empty($getProfile["NickName"])) {
								$getProfile["FirstName"] = $getProfile["NickName"];
							}
							$ArrayCheck[] = $getProfile["UserID"];
							$NewplaersArray[$player['ID']]["Rank"] = ($player["Rank"] != null || $player["Rank"] != 0) ? $player["Rank"] : 0;
							$NewplaersArray[$player['ID']]["RankNo"] = ($player["Rank"] != null || $player["Rank"] != 0) ? $player["Rank"] : 10000000;

							$Ethnicity = "";
							switch ($getProfile["Ethnicity"]) {
								case "African" :
									$Ethnicity = "A";
									break;
								case "Coloured" :
									$Ethnicity = "C";
									break;
								case "Indian" :
									$Ethnicity = "I";
									break;
								case "White" :
									$Ethnicity = "W";
									break;
							}
							$SEX = "";
							switch ($getProfile["Sex"]) {
								case "Male" :
									$SEX = "M";
									break;
								case "Female" :
									$SEX = "F";
									break;
							}

							$Profile = $getProfile;

							$Profile["Json"] = json_decode($Profile["Json"], true);

							$Profile2["Started"] = 0;
							$Profile2["Benched"] = 0;
							$Profile2["tries"] = 0;
							$Profile2["Conversions"] = 0;
							$Profile2["Penalties"] = 0;
							$Profile2["DropGoals"] = 0;
							$Profile2["GameTime"] = 0;
							$Profile2["YellowCard"] = 0;
							$Profile2["RedCard"] = 0;

							if (count(@$Profile["Json"][$sid]) > 0) {
								//$Profile["Json"]=$Profile["Json"][$SID];

								foreach ($Profile["Json"][$sid] as $fixtureJso) {

									$Profile2["GameTime"] = @$Profile2["GameTime"] + $fixtureJso["GameTime"];
									$Profile2["YellowCard"] = @$Profile2["YellowCard"] + $fixtureJso["YellowCard"];
									$Profile2["RedCard"] = @$Profile2["RedCard"] + $fixtureJso["RedCard"];

									if ($fixtureJso["Position"] < 16) {
										$Profile2["Started"]++;
									}
									if ($fixtureJso["Position"] > 15) {
										$Profile2["Benched"]++;
									}
									if (isset($fixtureJso["DATA"])) {
										$Profile2["tries"] = $Profile2["tries"] + $fixtureJso["DATA"]["tries"];
										$Profile2["Conversions"] = $Profile2["Conversions"] + $fixtureJso["DATA"]["Conversions"];
										$Profile2["Penalties"] = $Profile2["Penalties"] + $fixtureJso["DATA"]["Penalties"];
										$Profile2["DropGoals"] = $Profile2["DropGoals"] + $fixtureJso["DATA"]["DropGoals"];
									}

								}

							}

							// Check for University PLayers Bonafide Nomber
							$AllowedToPlay = 0;
							if ($squad["un_type"] == 8) {
								if ($getProfile["Play_Year"] != date("Y")) {
									$AllowedToPlay = 1;
								} else {
									// date if file

									if ($getProfile["At_Risc"] == 1) {
										$AllowedToPlay = 2;
									} else {
										if ($getProfile["Bonified_no"] == "") {
											$AllowedToPlay = 1;
										}

									}
								}

							}

							$age = date("Y") - date("Y", strtotime($getProfile["DateOfBirth"]));
							$NewplaersArray[$player['ID']]["UserID"] = $getProfile["UserID"];
							$NewplaersArray[$player['ID']]["Avatar"] = $PlayerPhoto["Thumb"];
							$NewplaersArray[$player['ID']]["FirstName"] = $getProfile["FirstName"];
							$NewplaersArray[$player['ID']]["LastName"] = $getProfile["LastName"];
							$NewplaersArray[$player['ID']]["FullName"] = $getProfile["FullName"];
							$NewplaersArray[$player['ID']]["DateOfBirth"] = $getProfile["DateOfBirth"];
							$NewplaersArray[$player['ID']]["Age"] = $this -> age($getProfile["DateOfBirth"]);
							$NewplaersArray[$player['ID']]["AgeThisYear"] = $age;
							$NewplaersArray[$player['ID']]["height"] = $getProfile["height"];
							$NewplaersArray[$player['ID']]["weight"] = $getProfile["weight"];
							$NewplaersArray[$player['ID']]["Sex"] = $SEX;
							$NewplaersArray[$player['ID']]["Ethnicity"] = $Ethnicity;
							$NewplaersArray[$player['ID']]["PID"] = $getProfile["PID"];
							$NewplaersArray[$player['ID']]["JerseyNumber"] = (!empty($player["Jersey"])) ? $player["Jersey"] : 0;
							$NewplaersArray[$player['ID']]["PostionNo"] = @$player['Position'];
							$NewplaersArray[$player['ID']]["ReturnToTraining"] = $injury;
							$NewplaersArray[$player['ID']]["POS"] = (!empty($getProfile["Position"])) ? $getProfile["Position"] : "POS: not assigned";
							$NewplaersArray[$player['ID']]["Org"] = (!empty($getProfile["un_name"])) ? $getProfile["un_name"] : "not assigned"; ;
							$NewplaersArray[$player['ID']]["Update"] = ($getProfile["DateModified"] != "0000-00-00 00:00:00") ? 1 : 0;
							$NewplaersArray[$player['ID']]["PROFILEDOC"] = $PROFILEDOC;
							$NewplaersArray[$player['ID']]["IDDOC"] = $IDDOC;
							$NewplaersArray[$player['ID']]["INDEMNITY"] = $INDEMNITY;
							$NewplaersArray[$player['ID']]["Captain"] = (!empty($player["Captain"])) ? $player["Captain"] : 0; ;
							$NewplaersArray[$player['ID']]["Vice"] = (!empty($player["Vice"])) ? $player["Vice"] : 0;
							$NewplaersArray[$player['ID']]["DATA"] = $Profile2;
							$NewplaersArray[$player['ID']]["AllowedToPlay"] = $AllowedToPlay;
							$Confirmed = 0;
							if (isset($ConfirmedPlayers[$player["ID"]])) {
								$Confirmed = $player['ID'];
							}
							$NewplaersArray[$player['ID']]["CONFIRMED"] = $Confirmed;

							$un_name = $getProfile["un_name"];
							if ($squad['AgeGroup'] < 14 && $squad['AgeGroup'] > 0) {
								if ($squad["Country"] == 239 && $squad['AgeGroup'] == 13) {
									$un_name = $getProfile["SecondarySchool"];
								} else {
									$un_name = $getProfile["PrimarySchool"];
								}
							} else if ($squad['AgeGroup'] > 13 && $squad['AgeGroup'] < 19) {
								$un_name = $getProfile["SecondarySchool"];
							}
							$NewplaersArray[$player['ID']]["School"] = $un_name;

							$list[$player['ID']] = $player;

						}

						$i++;
						//$NewplaersArray[$i]["weight"] = $getProfile["weight"];
						//$NewplaersArray[$i]["height"] = $getProfile["height"];
						//$NewplaersArray[$i]["PID"] = $getProfile["PID"];
					}

				}

			}

			if ($sort > 0) {
				switch ($sort) {
					case 1 :
						$this -> array_sort_by_column($NewplaersArray, 'FirstName');
						break;
					case 2 :
						$this -> array_sort_by_column($NewplaersArray, 'LastName');
						break;

					case 3 :
						$this -> array_sort_by_column($NewplaersArray, 'PostionNo');
						break;
					default :
						$this -> array_sort_by_column($NewplaersArray, 'LastName');
						break;
				}
			} else {
				if ($squad["SquadType"] < 2) {
					//$this->array_sort_by_column($NewplaersArray, 'PostionNo');
					$this -> array_sort_by_column($NewplaersArray, 'JerseyNumber');

				} else if ($squad["SquadType"] > 4 && $squad["SquadType"] < 12) {
					$this -> array_sort_by_column($NewplaersArray, 'RankNo');
				} else if ($squad["SquadType"] == 12) {
					$this -> array_sort_by_column($NewplaersArray, 'RankNo');
				} else {
					$this -> array_sort_by_column($NewplaersArray, 'LastName');
				}
			}
			 json_encode(array("Players" => $NewplaersArray, "AllowJersey" => $squad["AllowJerseyChange"]));
			echo "<pre>";
			print_r($NewplaersArray);
			
			//echo "<pre>";
			//print_r($squad);
		//}
	}

	public function xlsAction() {

		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();

		$sid = $request -> getParam("id");

		$SquadsTbl = new Model_Squad;
		$squad = $SquadsTbl -> getSquad($sid);

		if (PHP_SAPI == 'cli')
			die('This example should only be run from a Web Browser');

		/** Include PHPExcel */
		require_once 'Classes/PHPExcel.php';

		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();

		// Set document properties
		$objPHPExcel -> getProperties() -> setCreator("Messias Andre") -> setLastModifiedBy("Messias Andre") -> setTitle("Office 2007 XLSX Test Document") -> setSubject("Office 2007 XLSX Test Document") -> setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") -> setKeywords("office 2007 openxml php") -> setCategory("Test result file");

		$jerseyText = "Rank";
		if ($squad["SquadType"] < 3) {

			$jerseyText = "Jersey";
		}

		$row = 1;
		$objPHPExcel -> setActiveSheetIndex(0);
		$objWorkSheetp = $objPHPExcel -> createSheet(0);
		$objWorkSheetp -> setTitle("Players");
		$objWorkSheetp -> setCellValueByColumnAndRow(0, $row, "Name");
		$objWorkSheetp -> setCellValueByColumnAndRow(1, $row, "Surname");
		$objWorkSheetp -> setCellValueByColumnAndRow(2, $row, "Known As");
		$objWorkSheetp -> setCellValueByColumnAndRow(3, $row, "Position");
		$objWorkSheetp -> setCellValueByColumnAndRow(4, $row, "Captain");
		$objWorkSheetp -> setCellValueByColumnAndRow(5, $row, $jerseyText . " #");
		$objWorkSheetp -> setCellValueByColumnAndRow(6, $row, "ID Number");
		$objWorkSheetp -> setCellValueByColumnAndRow(7, $row, "Passport");
		$objWorkSheetp -> setCellValueByColumnAndRow(8, $row, "Passport Expiry");
		$objWorkSheetp -> setCellValueByColumnAndRow(9, $row, "Date of Birth");
		$objWorkSheetp -> setCellValueByColumnAndRow(10, $row, "Age");
		$objWorkSheetp -> setCellValueByColumnAndRow(11, $row, "Ethnicity");
		$objWorkSheetp -> setCellValueByColumnAndRow(12, $row, "Gender");
		$objWorkSheetp -> setCellValueByColumnAndRow(13, $row, "Birth Place");
		$objWorkSheetp -> setCellValueByColumnAndRow(14, $row, "Birth Country");
		$objWorkSheetp -> setCellValueByColumnAndRow(15, $row, "Relationship");
		$objWorkSheetp -> setCellValueByColumnAndRow(16, $row, "Height");
		$objWorkSheetp -> setCellValueByColumnAndRow(17, $row, "Weight");
		$objWorkSheetp -> setCellValueByColumnAndRow(18, $row, "Mobile No");
		$objWorkSheetp -> setCellValueByColumnAndRow(19, $row, "Telephone No");
		$objWorkSheetp -> setCellValueByColumnAndRow(20, $row, "Email");
		$objWorkSheetp -> setCellValueByColumnAndRow(21, $row, "Parent Name");
		$objWorkSheetp -> setCellValueByColumnAndRow(22, $row, "Parent Surname");
		$objWorkSheetp -> setCellValueByColumnAndRow(23, $row, "Parent Email");
		$objWorkSheetp -> setCellValueByColumnAndRow(24, $row, "Parent Mobile");
		$objWorkSheetp -> setCellValueByColumnAndRow(25, $row, "Parent Relationship");
		$objWorkSheetp -> setCellValueByColumnAndRow(26, $row, "Street");
		$objWorkSheetp -> setCellValueByColumnAndRow(27, $row, "Suburb");
		$objWorkSheetp -> setCellValueByColumnAndRow(28, $row, "City");
		$objWorkSheetp -> setCellValueByColumnAndRow(29, $row, "Province");
		$objWorkSheetp -> setCellValueByColumnAndRow(30, $row, "Postal Code");
		$objWorkSheetp -> setCellValueByColumnAndRow(31, $row, "Country");
		$objWorkSheetp -> setCellValueByColumnAndRow(32, $row, "Union");
		$objWorkSheetp -> setCellValueByColumnAndRow(33, $row, "Primiry School");
		$objWorkSheetp -> setCellValueByColumnAndRow(34, $row, "Secondary School");
		$objWorkSheetp -> setCellValueByColumnAndRow(35, $row, "Dietary");

		$objPHPExcel -> getActiveSheet() -> getStyle($row) -> getFont() -> setBold(true) -> setSize(16);
		$row++;
		$listPlayers = json_decode($squad["Players"], true);
		if (count($listPlayers) > 0) {
			foreach ($listPlayers as $player) {
				$profileDB = new Model_Profile;
				$getProfile = $profileDB -> GetPlayersByPositions($player['ID'], $player['Position']);
				$un_name = $getProfile["un_name"];
				if ($getProfile["un_type"] > 3 && $getProfile["un_type"] != 11) {
					$unionDB = new Model_Unions;
					$union = $unionDB -> fetchRow("un_id ='" . $getProfile["parentid"] . "'");
					$un_name = $union["un_name"];
				}

				if ($getProfile["DiettryType"] == 1) {
					$Dietary = "Halaal";
				} elseif ($getProfile["DiettryType"] == 2) {
					$Dietary = "Vegetarian";
				} elseif ($getProfile["DiettryType"] == 3) {
					$Dietary = $getProfile["DiettryOther"];
				} else {
					$Dietary = "None";
				}
				$expire = $getProfile["PassportExpireDate"];
				if (empty($getProfile["PassportNumber"])) {
					$expire = "";
				}

				$jersey = (!empty($player["Rank"])) ? $player["Rank"] : 0;
				if ($squad["SquadType"] < 3) {
					$jersey = (!empty($player["Jersey"])) ? $player["Jersey"] : 0;
				}

				$Captain = "";
				if ($player['Captain'] == 1) {
					$Captain = "Yes";
				}

				$objWorkSheetp -> setCellValueByColumnAndRow(0, $row, $getProfile["FirstName"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(1, $row, $getProfile["LastName"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(2, $row, $getProfile["NickName"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(3, $row, $getProfile["POS"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(4, $row, $Captain);
				$objWorkSheetp -> setCellValueByColumnAndRow(5, $row, $jersey);
				$objWorkSheetp -> setCellValueByColumnAndRow(6, $row, "No: " . $getProfile["IDNumber"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(7, $row, $getProfile["PassportNumber"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(8, $row, $expire);
				$objWorkSheetp -> setCellValueByColumnAndRow(9, $row, $getProfile["DateOfBirth"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(10, $row, $this -> age($getProfile["DateOfBirth"]));
				$objWorkSheetp -> setCellValueByColumnAndRow(11, $row, $getProfile["Ethnicity"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(12, $row, $getProfile["Sex"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(13, $row, $getProfile["BirthPlace"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(14, $row, $getProfile["BirthCountry"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(15, $row, $getProfile["rel_status"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(16, $row, $getProfile["height"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(17, $row, $getProfile["weight"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(18, $row, $getProfile["Mobile"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(19, $row, $getProfile["alt_mobile"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(20, $row, $getProfile["Email"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(21, $row, $getProfile["parent_FirstName"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(22, $row, $getProfile["parent_LastName"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(23, $row, $getProfile["parent_Email"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(24, $row, $getProfile["parent_Cell"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(25, $row, $getProfile["relation"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(26, $row, $getProfile["address"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(27, $row, $getProfile["suburb"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(28, $row, $getProfile["city"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(29, $row, $getProfile["Province"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(30, $row, $getProfile["postal"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(31, $row, $getProfile["country"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(32, $row, $un_name);
				$objWorkSheetp -> setCellValueByColumnAndRow(33, $row, $getProfile["PrimarySchool"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(34, $row, $getProfile["SecondarySchool"]);
				$objWorkSheetp -> setCellValueByColumnAndRow(35, $row, $Dietary);
				$row++;
			}

		}

		$row = 1;
		$objWorkSheet = $objPHPExcel -> createSheet(1);
		$objWorkSheet -> setTitle("Coaches");

		$objWorkSheet -> setCellValueByColumnAndRow(0, $row, "Role");
		$objWorkSheet -> setCellValueByColumnAndRow(1, $row, "Surname");
		$objWorkSheet -> setCellValueByColumnAndRow(2, $row, "Name");
		$objWorkSheet -> setCellValueByColumnAndRow(3, $row, "BokSmart");
		$objWorkSheet -> setCellValueByColumnAndRow(4, $row, "Date of Birth");
		$objWorkSheet -> setCellValueByColumnAndRow(5, $row, "Email");
		$objWorkSheet -> setCellValueByColumnAndRow(6, $row, "Ethnicity");
		$objWorkSheet -> setCellValueByColumnAndRow(7, $row, "Organisation");
		$objWorkSheet -> setCellValueByColumnAndRow(8, $row, "Dietary");

		$row++;
		$listCoaches = json_decode($squad["Coaches"], true);
		if (count($listCoaches) > 0) {
			foreach ($listCoaches as $Coach) {
				$profileDB = new Model_Profile;
				$getProfile = $profileDB -> GetPesonnalByPositions($Coach['ID'], $Coach['Position']);
				if ($getProfile["DiettryType"] == 1) {
					$Dietary = "Halaal";
				} elseif ($getProfile["DiettryType"] == 2) {
					$Dietary = "Vegetarian";
				} elseif ($getProfile["DiettryType"] == 3) {
					$Dietary = $getProfile["DiettryOther"];
				} else {
					$Dietary = "None";
				}
				$un_name = $getProfile["un_name"];
				if ($getProfile["un_type"] > 3 && $getProfile["un_type"] != 11) {
					$unionDB = new Model_Unions;
					@$union = $unionDB -> fetchRow("un_id ='" . $getProfile["parentid"] . "'");
					$un_name = $union["un_name"];
				}
				$objWorkSheet -> setCellValueByColumnAndRow(0, $row, $getProfile["POS"]);
				$objWorkSheet -> setCellValueByColumnAndRow(1, $row, $getProfile["LastName"]);
				$objWorkSheet -> setCellValueByColumnAndRow(2, $row, $getProfile["FirstName"]);
				$objWorkSheet -> setCellValueByColumnAndRow(3, $row, $getProfile["boksmart"]);
				$objWorkSheet -> setCellValueByColumnAndRow(4, $row, $getProfile["DateOfBirth"]);
				$objWorkSheet -> setCellValueByColumnAndRow(5, $row, $getProfile["Email"]);
				$objWorkSheet -> setCellValueByColumnAndRow(6, $row, $getProfile["Ethnicity"]);
				$objWorkSheet -> setCellValueByColumnAndRow(7, $row, $un_name);
				$objWorkSheet -> setCellValueByColumnAndRow(8, $row, $Dietary);

				$row++;
			}
		}

		$name = $squad['ShortName'];
		if ($squad["SquadType"] == 1) {
			$TourDB = new Model_Tournament;
			$Tourn = $TourDB -> getTourny($squad["TournamentID"]);
			$name = $Tourn["TournName"] . "-" . $name;
		}
		if ($squad["SquadType"] == 2) {
			$TourDB = new Model_Tournament;
			$Tourn = $TourDB -> getTourny($squad["TIDs"]);
			$name = $Tourn["TournName"] . "-" . $name;
		}
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="' . $name . '- Squad list-' . date("Y-m-dH:i:s") . '.xls"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		// Date in the past
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		// always modified
		header('Cache-Control: cache, must-revalidate');
		// HTTP/1.1
		header('Pragma: public');
		// HTTP/1.0

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter -> save('php://output');

	}

	public function addtosquadAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$Player = new Model_Profile;
		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$id = $request -> getParam("id");
			$type = $request -> getParam("type");
			$pos = $request -> getParam("pos");
			$SID = $request -> getParam("SID");

			$historyDB = new Model_SquadsHistory;
			$SquadsTbl = new Model_Squad;
			$squad = $SquadsTbl -> getSquad($SID);
			echo "setp 1";
			$SquadsTbl -> addPlayerToSquad($SID, $id, $pos);

			$PlayersHistoryDB = new Model_PlayerCareer;
			$getCurrent = $PlayersHistoryDB -> fetchRow("UserID ='" . $id . "'");
			if (isset($getCurrent["UserID"])) {
				$squads = json_decode($getCurrent["Squads"], true);
				$squads[$SID] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $SID, "Squad" => $squad['SquadName'], "Pos" => $pos);
				$data = array("UserID" => $id, "Squads" => json_encode($squads));
				$added = $PlayersHistoryDB -> updateData($data, $id);
			} else {
				$squads[$SID] = array("DATE" => date("Y-m-d H:i:s"), "SID" => $SID, "Squad" => $squad['SquadName'], "Pos" => $pos);
				$data = array("UserID" => $id, "Squads" => json_encode($squads));
				$PlayersHistoryDB -> insertData($data);
			}

			$historyDB = new Model_SquadsHistory;
			$history = $historyDB -> fetchRow("SID ='" . $SID . "'");

			if (!$history) {

				$historyDB -> insert(array("SID" => $SID));
				$history = array();
			} else {
				$history = json_decode($history["History"], true);
			}

			$player = $Player -> getPlayerProfile($id);
			$action = $this -> identity -> FirstName . " " . $this -> identity -> LastName . " <span class='label label-success'>Added</span>  " . $player["FirstName"] . " " . $player["LastName"] . " to the  squad";
			$history[count($history)] = array("DATETIME" => date("Y-m-d H:i:s"), "USERID" => $id, "MESSAGE" => $action, "POSITION" => $pos, "AUTHOR" => $this -> identity -> UserID, "AUTHORFULLNAME" => $this -> identity -> FirstName . " " . $this -> identity -> LastName);
			$updateHistory = $historyDB -> update(array("History" => json_encode($history)), "SID ='" . $SID . "'");

			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $SID);

		}
	}

	public function addtosquad($SID, $id) {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();
		if ($request -> isPost()) {

			$db = new Model_Squad;
			$squad = $db -> getSquad($SID);

			$sdata = array();

			$squadArray = (array) json_decode($squad["Managers"]);
			$n = 0;
			$listArray = array();
			foreach ($squadArray as $ddd) {
				if ($ddd -> ID != $id) {
					$listArray[] = array("ID" => $ddd -> ID, "Position" => $ddd -> Position);
				}
				$n++;
			}

			array_push($listArray, array("ID" => $id, "Position" => 42));

			$array = array("Managers" => json_encode($listArray), "CountManagers" => count($listArray), "TotalCount" => count($listArray) + $squad["CountPlayers"] + $squad["CountCoaches"] + $squad["CountMedical"]);

			$saved = $db -> updateSquad($array, $SID);
			if ($saved) {

				echo "done";
			} else {
				echo "error";
			}
			$SquadsTbl = new Model_Squad;
			$SquadsTbl -> updateSquad(array("DateModified" => date("Y-m-d H:i:s")), $SID);
		}
	}

	public function downloadscoresheetAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		require_once ("dompdf/dompdf_config.inc.php");

		$request = $this -> getRequest();
		$sid = $request -> getParam("sid");
		$fid = $request -> getParam("id");

		$FixtureDB = new Model_Fixture;

		$fixture = $FixtureDB -> getFixture($fid);

		$url = shapeSpace_check_https() . "/pdf/matchscoresheet/id/" . $fid . "/sid/" . $sid;

		$html = file_get_contents($url);
		$html = $this -> AfrReplace($html);

		$dompdf = new DOMPDF();
		$dompdf -> load_html($html);
		$dompdf -> set_paper('a3', 'portrait');
		$dompdf -> render();

		$dompdf -> stream($fixture["SquadName1"] . " vs " . $fixture["SquadName2"] . " ScoreSheet.pdf");
	}

	public function saveteamscoreAction() {

		$request = $this -> getRequest();
		if ($request -> isPost()) {
			$data = $request -> getParam("data");
			$fid = $request -> getParam("fid");
			$sid = $request -> getParam("sid");
			$HomeSore = $request -> getParam("home");
			$AwaySore = $request -> getParam("away");
			$team = $request -> getParam("team");
			
			$abid = $request -> getParam("abid");
			$ffid = $request -> getParam("ffid");
			if($ffid >0 && $abid < 3){
				$ForfeitedID = $ffid;
			}else{
				$ForfeitedID = 0;
			}
			

			$data["FID"] = $fid;
			$data["SID"] = $sid;
			$data["FT_Score"] = $HomeSore;
			$data["OP_FT_Score"] = $AwaySore;
			$data["Status"] = 1;

			$data["Author"] = $this -> identity -> UserID;
			$data["DateSubmitted"] = date("Y-m-d H:i:s");
			

			
			$Status = 1;
			$audit_Data["Status"] = $Status;
			$data["Abandend"] = 0;
			if ($abid== 3) {
				$data["Abandend"] = 1;
				
				$data["FT_Score"] = 0;
			$data["OP_FT_Score"] = 0;
			}
			if ($ForfeitedID >0 ) {
				 $data["Forfeited_Team_id"] = $ForfeitedID;
				$data["FT_Score"] = 0;
				$data["OP_FT_Score"] = 0;
			}
			
			$DB = new Model_TeamScore;
			$Saved = $DB -> updateData($data);
			if($Saved){
				$dispute = $DB->getDespute($fid);
				if(isset($dispute["Disputed"]) && $dispute["Disputed"]==0){
					//save score to match report
				}
				
			}
			//print_r($data);

		}

		exit ;
	}

	public function testAction() {

		//$this->CheckForDispute(3327,3119);
		exit ;
	}

}
