<?php
ini_set('display_errors', 1);
ini_set('error_reporting', 1);

class MembersController extends Zend_Controller_Action {
	private $identity;
	private $AccessDB;
	private $AccessRights;

	public function init() {
		try{
		$Auth = new PG_Controller_Plugin_Authontication;
		 $User = $Auth->Auth();
		$this -> identity = $User;
		
		$this -> AccessRights = json_decode($this -> identity -> Role, true);
		$this -> view -> assign("AccessRoles", $this -> AccessRights);
		$this -> view -> assign("UserDetails", $this -> identity);
		$this -> view -> assign("getControllerName", $this -> getRequest() -> getControllerName());
		$this -> view -> assign("getActionName", $this -> getRequest() -> getActionName());
		$this -> AccessDB = new Model_DbTable_AccessControl;
		
		}catch(exception $expression){
			 echo "<pre>";
			print_r($expression);
		}
		
	}
	public function addAction() {
		try{
		$this -> getInstitutionType();
		$EthnicityDB = new Model_DbTable_Ethnicity;
		$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());

		

		$CountryDB = new Model_DbTable_Country;
		$this -> view -> assign("Country", $CountryDB -> getAll());

		$RelationshipDB = new Model_DbTable_Relationship;
		$this -> view -> assign("Relationship", $RelationshipDB -> getAll());

		$ProvinceDB = new Model_DbTable_Province;
		$this -> view -> assign("Province", json_encode($ProvinceDB -> getAll() -> toArray()));
		$this->view->assign("Province",$ProvinceDB->getAll());

		$JobTitleDB = new Model_DbTable_UserType;
		$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());

		$SportCodeDB = new Model_DbTable_SportsCode;
		$this -> view -> assign("SportCode", $SportCodeDB -> getAll());
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}
		

	}

public function newmemberAction() {
	try{
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$data["data"] = $request -> getParam("data");
		$birth["birth"] = $request -> getParam("birth");
		$data["data"]["PassportExpireDate"] = $birth["birth"]["xyear"] . "-" . $birth["birth"]["xmonth"] . "-" . $birth["birth"]["xday"];

		$data["data"]["DateOfBirth"] = date("d-m-Y", strtotime($birth["birth"]["day"] . "-" . $birth["birth"]["month"] . "-" . $birth["birth"]["year"]));

		if (!empty($data["data"]["DateOfBirth"])) {
			$data["DateOfBirth"] = date("d-m-Y", strtotime($data["data"]["DateOfBirth"]));
			$dateOfbirth = explode("-", $data["data"]["DateOfBirth"]);
			if (strlen($dateOfbirth[2]) == 2) {
				$year = "20" . $dateOfbirth[2];
				if ($year > date("Y")) {
					$year = "19" . $dateOfbirth[2];
				}
				$data["data"]["DateOfBirth"] = date("d-m-Y", strtotime($dateOfbirth[0] . "-" . $dateOfbirth[1] . "-" . $year));
			}
		}
		

		$data["data"]["boksmartExpiryDate"] = $birth["birth"]["byear"] . "-" . $birth["birth"]["bmonth"] . "-" . $birth["birth"]["bday"];
		if (empty($data["data"]["NickName"])) {
			$data["data"]["NickName"] = $data["data"]["LastName"];
		}
		if ($data["data"]["ClubID"] =="") {
			$data["data"]["ClubID"] = 0;
		}
		if ($data["data"]["SocietyID"] =="") {
			$data["data"]["SocietyID"] = 0;
		}
		if ($data["data"]["JobType"] ==2) {
			$data["data"]["JobTitle"] = 0;
		}
		
		$data["data"]["author"] = $this->identity->UserID;
		$data["data"]["DateCreated"] = date("Y-m-d H:i:s");
		$UserProfileDB = new Model_DbTable_Profile;
		$UserProfile = $UserProfileDB -> insert($data["data"]);
		$response = array("OK" => 1);
		if ($UserProfile > 0) {
			$response = array("OK" => 0, "ID" => $UserProfile);
		}

		echo json_encode($response);
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}
	}

public function profileAction() {
	try{
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$gir = $request -> getParam("gir");

		if ($gir == 1) {
			$UserProfileDB = new Model_DbTable_GirProfile;
			$UserProfile = $UserProfileDB -> getFullProfile($id);

		} else {
			$UserProfileDB = new Model_DbTable_Profile;
			$UserProfile = $UserProfileDB -> getFullProfileDetails($id);
		}
		if ($UserProfile["JobType"] == 2) {
			$posDB = new Model_DbTable_Positions;
			$pos = $posDB -> getPosByPOS($UserProfile["p_code"], $UserProfile["Player_Prim_Pos"]);
			if (isset($pos["Position"])) {
				$this -> view -> assign("POS", $pos["Position"]);
			} else {
				$this -> view -> assign("POS", "N/A");
			}
		}

		$this -> view -> assign("profile", $UserProfile);
		$Age = $UserProfile["Age"];
		$ShowTabs = array("Parent" => 0);
		if ($Age > 18) {
			$ShowTabs["Parent"] = 1;
		}
		$this -> view -> assign("ShowTabs", $ShowTabs);


		$ModelDB = new Model_DbTable_Models;
		$this -> view -> assign("Models", $ModelDB -> fetchAll() -> toArray());
	

		//Roles
		$ROLES = json_decode($UserProfile["Role"], true);

		if (count($ROLES) > 0) {
			$this -> view -> assign("role", $ROLES);
		}

			
		
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}
		
	}
public function dropdownsAction(){
			$CountryDB = new Model_DbTable_Country;
			$EthnicityDB = new Model_DbTable_Ethnicity;
			$RelationshipDB = new Model_DbTable_Relationship;
			$StatusDB = new Model_DbTable_RelationshipStatus;
			$ProvinceDB = new Model_DbTable_Province;
			$JobTitleDB = new Model_DbTable_UserType;
			$PositionDB = new Model_DbTable_Positions;
			$RelationshipDB = new Model_DbTable_Relationship;
			$SquadsDB = new Model_DbTable_Squad;
			$CityDB = new Model_DbTable_Cities;
			
	$Drodown = array("Country"=>$CountryDB -> getAll(),);
		
			
			$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());
			
			$this -> view -> assign("Relationship", $RelationshipDB -> getAll());
			
			$this -> view -> assign("StatusList", $StatusDB -> getAll());
		

		
			
			$this -> view -> assign("Province", $ProvinceDB -> getAll());
			
			$this -> view -> assign("City", $CityDB -> getAllData());

		
		
			$this -> getInstitutionType();
			
			$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());
			$SportCodeDB = new Model_DbTable_SportsCode;
			$this -> view -> assign("SportCode", $SportCodeDB -> getAll());

			
			$this -> view -> assign("Positions", $PositionDB -> getPos(15));

			$this -> view -> assign("SevensPositions", $PositionDB -> getPos(7));
			$this->getInstitutionType();
		
		
			
			$RelStatus = $RelationshipDB -> getAll();
			$this -> view -> assign("RelStatus", $RelStatus);
			
			//Get Careeer
			
			$UserSquad = $SquadsDB->GetMySquads_Of_User($id);
			$this -> view -> assign("Participations", $UserSquad);
	exit;
}
	public function indexAction() {
	try {
		
		$this -> AccessControll();
		$request = $this -> getRequest();
		//list Unions
		$UnionsDB = new Model_DbTable_Unions;
		$UnionsList = $UnionsDB -> listUnionsByUserLogin();
		$this -> view -> assign("Unions", $UnionsList);

		$unionID = 0;
		$uid = $request -> getParam("union");
		if ($uid) {
			$unionID = $uid;
		}
		$this -> view -> assign("unionID", $uid);
		if ($this -> identity -> Active == 0) {
			$this -> _redirect("/");
		}

		$this -> view -> assign("UnionType", $this -> identity -> UnionType);
		//List Types
		$IntuitutionTypesDB = new Model_DbTable_IntuitutionTypes;
		$this -> view -> assign("UnionTypes", $IntuitutionTypesDB -> list_For_Table_Dropdown());
		//List User Types
		$JobTitleDB = new Model_DbTable_UserType;
		$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}
	}

	public function getmembersAction() {
try {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		$request = $this -> getRequest();

		$unionFilter = $request -> getParam("unionid");
		$type = $request -> getParam("type");
		$title = $request -> getParam("title");
		$role = $request -> getParam("role");
		if ($this -> identity -> UnionType > 2 && ($unionFilter == 0 || $unionFilter == "")) {
			$unionFilter = $this -> identity -> UnionID;
		}

		$order = $_GET["order"][0]["dir"];
		$column = $_GET["order"][0]["column"];
		switch ($column) {
			case 0 :
				$column = 'FirstName';
				break;
			case 1 :
				$column = 'FirstName';
				break;
			case 2 :
				$column = 'un_name';

				break;
			case 3 :
				$column = 'Email';

				break;
			case 4 :
				$column = 'TypeName';

				break;
			case 5 :
				$column = 'Mobile';
				break;
			default :
				$column = 'FirstName';
				break;
		}
		$searchSQL = null;
		$search = @$request -> getParam("search");
		if (@strlen($search) > 0) {
			$searchSQL = $search;
		}
		if ($this -> identity -> JobTitle == 55) {
			$title = 8;
		}
		if ($title == 2) {
			$role = 0;
		}

		
			$dbUsers = new Model_DbTable_Profile;
			$list = $dbUsers -> listUsers($order, $column, $searchSQL, $unionFilter, $type, $title, $role);
			$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($list -> toArray()));
			$paginator -> setCurrentPageNumber(($_GET["start"] / $_GET["length"]) + 1);
			$paginator -> setItemCountPerPage($_GET["length"]);
			$this -> datatable($paginator, $_GET, count($list -> toArray()));

		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}

		exit ;

	}

	private function datatable($dataArray, $requestData, $total) {

		$data = array();
		$i = 1 + $requestData['start'];
		foreach ($dataArray as $row) {

			$c = ",";
			if ($i == 0) {
				$c = "";
			}
			$green = '';
			if ($data["CID"] > 0) {
				$row = 'green';
			}

			$action = '';
			$link = '';
			if (isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"]["edit"])) {
				//$action ='<a  target="_blank" class="btn tipb" href="/'.$this->getRequest()->getControllerName().'/edit/id/'.$row["UserID"].'/"  data-placement="top" title="Edit" ><span class=isw-edit></span></a>';
			}

			$action .= '<a   class="btn tipb"  id="' . $row["UserID"] . '" onclick="Quickview(this)"  data-placement="top" title="View" ><span class=isw-zoom></span></a>';

			if (isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"]["profile"])) {
				$link = ' target="_blank" href="/' . $this -> getRequest() -> getControllerName() . '/profile/id/' . $row["UserID"] . '"';
				$action .= '<a  target="_blank" href="/' . $this -> getRequest() -> getControllerName() . '/profile/id/' . $row["UserID"] . '/" class="btn tipb" title="Profile" ><span class=isw-picture></span></a>';
			}
			if (isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"]["delete"])) {
				$action .= '<a  class="btn-danger tipb"  id="' . $row["UserID"] . '" onclick="delete_acc(this)"  data-placement="top" title="Delete"><span class=isw-delete></span></a>';
			}
			$link_Company = "";
			if (isset($this -> AccessRights["organisations"]["Actions"]["profile"])) {
				$link_Company = " href='/organisations/view/id/" . $row['un_id'] . "'";
			}
			//preparing an array

			$nestedData = array();
			$nestedData[] = $i;
			$nestedData[] = '<a ' . $link . ' > ' . $row["FullName"] . '</a>';
			$nestedData[] = "<a target='_blank' " . $link_Company . " >" . $row['un_name'] . "</a>";
			$nestedData[] = $row['Email'];
			$nestedData[] = $row["TypeName"];
			$nestedData[] = $row['Mobile'];
			$nestedData[] = $row['LastLogin'];
			$nestedData[] = '<span class=buttons>' . $action . '</span>';

			$data[] = $nestedData;
			$i++;

		}

		$json_data = array("search" => $requestData["search"]["value"], "column" => $requestData["order"][0]["column"], "dir" => intval($requestData["order"][0]["dir"]), "start" => intval($requestData['start']), "page" => intval($requestData["start"] / $requestData["length"]), "length" => intval($requestData['length']), "draw" => intval($requestData['draw'] + 1), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
		"recordsTotal" => intval($total), // total number of records
		"recordsFiltered" => intval($total), // total number of records after searching, if there is no searching then totalFiltered = totalData
		"data" => $data // total data array
		);

		echo json_encode($json_data);
		// send data as json format

	}

	public function getmemberAction() {
		try {
			$this -> _helper -> layout -> disableLayout();

			$request = $this -> getRequest();

			$id = $request -> getParam("id");
			$dbUsers = new Model_DbTable_Profile;
			$member = $dbUsers -> getRow($id);
			$member["UserID"] = $id;
			$UnionID = $member["UnionID"];
			if ($member["UnionType"] > 3) {
				$UnionID = $member["parentid"];
			}
			$avator = $member["Avator"];
			if (!$member["Avator"]) {
				$member["Avator"] = "/img/user_default.jpg";
			}
			$this -> view -> assign("member", $member);
			$this -> view -> assign("access_Role", $this -> AccessRights);
			$this -> view -> assign("listleague", $this -> listleagues($UnionID));

			$DB = new Model_DbTable_Panels;
			$Panels = $DB -> getAllData();
			$this -> view -> assign("Panels", $Panels);
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}

	}
	public function deleteAction() {
		$this -> AccessControll();
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		try{
			
		
		$db = new Model_DbTable_Profile;

		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$user = $db -> DeleteRow( $id );
		if($user){
			echo json_encode(array("OK"=>1));
		}else{
			echo json_encode(array("OK"=>0));
		}
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}

	}
	
	public function updateleagueAction() {
		//$this->AccessControll();
try{
		$this->_helper->viewRenderer->setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		if($request->isPost()){
			$option = $request -> getParam("opt");
			$id = $request -> getParam("id");
			$data["UserID"] = $id;
			if($option==1){
				$data["LeagueID"] = $request -> getParam("lid");
			}
			if($option==2){
				$data["PanelID"] = $request -> getParam("pid");
			}
			$dbUsers = new Model_DbTable_Profile;
			$dbUsers->updateProfile($data,$id);
		}
		} catch(Exception $expression) {
		ErrorLog($expression);
			
		}
}
	
	public function loadprofileAction() {
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$page = $request -> getParam("page");
		$UserProfileDB = new Model_DbTable_Profile;
		$UserProfile = $UserProfileDB -> getFullProfileNoImage($id);
		$this -> view -> assign("profile", $UserProfile);

		$CountryDB = new Model_DbTable_Country;
		$this -> view -> assign("Country", $CountryDB -> getAll());

		if ($page == "personaldetails") {
			$EthnicityDB = new Model_DbTable_Ethnicity;
			$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());
			$RelationshipDB = new Model_DbTable_Relationship;
			$this -> view -> assign("Relationship", $RelationshipDB -> getAll());
			$StatusDB = new Model_DbTable_RelationshipStatus;
			$this -> view -> assign("StatusList", $StatusDB -> getAll());
		}

		if ($page == "contactsdetails") {
			$ProvinceDB = new Model_DbTable_Province;
			$this -> view -> assign("Province", $ProvinceDB -> getAll());
			$CityDB = new Model_DbTable_Cities;
			$this -> view -> assign("City", $CityDB -> getAllData());

		}
		if ($page == "organisationdetails") {
			$this -> getInstitutionType();
			$JobTitleDB = new Model_DbTable_UserType;
			$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());
			$SportCodeDB = new Model_DbTable_SportsCode;
			$this -> view -> assign("SportCode", $SportCodeDB -> getAll());

			$PositionDB = new Model_DbTable_Positions;
			$this -> view -> assign("Positions", $PositionDB -> getPos(15));

			$this -> view -> assign("SevensPositions", $PositionDB -> getPos(7));

		}
		if ($page == "guardian") {
			$RelationshipDB = new Model_DbTable_Relationship;
			$RelStatus = $RelationshipDB -> getAll();
			$this -> view -> assign("RelStatus", $RelStatus);
		}

		/*
		 $AccreditationsDB = new Model_Accreditation;
		 $this->view->assign("AccreditationsList",$AccreditationsDB->getAll());

		 */

		$this -> _helper -> viewRenderer('members/profile/' . $page, null, true);
	}
	public function editprofileAction() {
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		$page = $request -> getParam("page");
		$UserProfileDB = new Model_DbTable_Profile;
		$UserProfile = $UserProfileDB -> fetchRow("UserID ='".$id."'");
		$this -> view -> assign("profile", $UserProfile);
		$CountryDB = new Model_DbTable_Country;
		$this -> view -> assign("Country", $CountryDB -> getAll());


		if ($page == "personaldetails") {
			$EthnicityDB = new Model_DbTable_Ethnicity;
			$this -> view -> assign("Ethnicity", $EthnicityDB -> getAll());
			$RelationshipDB = new Model_DbTable_Relationship;
			$this -> view -> assign("Relationship", $RelationshipDB -> getAll());
			$StatusDB = new Model_DbTable_RelationshipStatus;
			$this -> view -> assign("StatusList", $StatusDB -> getAll());
		}

		if ($page == "contactsdetails") {
			$ProvinceDB = new Model_DbTable_Province;
			$this -> view -> assign("Province", $ProvinceDB -> getAll());
			$CityDB = new Model_DbTable_Cities;
			$this -> view -> assign("City", $CityDB -> getAllData());

		}
		if ($page == "organisationdetails") {
			$this -> getInstitutionType();
			$JobTitleDB = new Model_DbTable_UserType;
			$this -> view -> assign("TitleType", $JobTitleDB -> getAllN());
			$SportCodeDB = new Model_DbTable_SportsCode;
			$this -> view -> assign("SportCode", $SportCodeDB -> getAll());

			$PositionDB = new Model_DbTable_Positions;
			$this -> view -> assign("Positions", $PositionDB -> getPos(15));

			$this -> view -> assign("SevensPositions", $PositionDB -> getPos(7));

		}
		if ($page == "guardian") {
			$RelationshipDB = new Model_DbTable_Relationship;
			$RelStatus = $RelationshipDB -> getAll();
			$this -> view -> assign("RelStatus", $RelStatus);
		}

		
		$this -> _helper -> viewRenderer('members/editprofile/' . $page, null, true);
	}
	
	public function squadsAction() {
		
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		//Get Careeer
			$ProfileDB = new Model_DbTable_Profile;
			$UserSquad = $ProfileDB->GetMySquads($id);
			$UserSquadPersonal = $ProfileDB->GetMySquadsPersonnel($id);
			if(count($UserSquad)>0 && count($UserSquadPersonal)>0){
				$UserSquad = array_merge($UserSquad,$UserSquadPersonal);
			}else if(count($UserSquad)==0 && count($UserSquadPersonal)>0){
				$UserSquad =$UserSquadPersonal;
			}
			
		
			$this -> view -> assign("Participations", $UserSquad);
		
	}
	public function fixturesplaidAction() {
		
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$id = $request -> getParam("id");
		//Get Careeer
			$FixtureDB = new Model_DbTable_Profile;
			$FixtureList = $FixtureDB->TimePaid($id);
			$ArrayList =array();
			if(count($FixtureList)>0){
				foreach ($FixtureList as $Fixture) {
					//$Fixture = $Fixture->toArray();
					$ArrayList[$Fixture["TID"]][]=$Fixture;
				}
			}
			
			$this -> view -> assign("FixtureTime", $ArrayList);
	}
	
	public function pdfAction() {
		try{
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();

		require_once ("dompdf/dompdf_config.inc.php");
		$request = $this -> getRequest();
$page = $this->notEmpty($request -> getParam("page"),0);
$type = $this->notEmpty($request -> getParam("type"),0);
$title = $this->notEmpty($request -> getParam("title"),0);
$role = $this->notEmpty($request -> getParam("role"),0);
$start = $this->notEmpty($request -> getParam("start"),0);
$length = $this->notEmpty($request -> getParam("length"),0);
$search = $this->notEmpty($request -> getParam("search"),"");
$column = $this->notEmpty($request -> getParam("column"),0);
$unionid = $this->notEmpty($request -> getParam("unionid"),0);
$current = $this->notEmpty($request -> getParam("current"),0);
$dir = $request -> getParam("dir");


		 $url = "http://" . $_SERVER["SERVER_NAME"] . "/pdf/print/page/" . $page .
		"/type/" . $type .
		"/title/" . $title.
		"/role/" . $role .
		 "/start/" . $start .
		  "/length/" . $length .
		   "/search/" . $search .
		    "/column/" . $column . 
		    "/unionid/" . $unionid . 
		    "/current/" . $current . 
		    "/dir/" . $dir;

		  $html = file_get_contents($url);
		

		$dompdf = new DOMPDF();
		$dompdf -> load_html($html);
		$dompdf -> set_paper('a4', $request -> getParam("orientation"));
		$dompdf -> render();
		$dompdf -> stream("Members.pdf");
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}

	}


public function saveaccountAction() {
		$this -> _helper -> viewRenderer -> setNoRender();
		$this -> _helper -> layout -> disableLayout();
		$request = $this -> getRequest();
		$data = $request -> getParam("data");
		$id = $request -> getParam("id");

		$UserProfileDB = new Model_DbTable_Profile;

		$data["Email"] = preg_replace('/\s+/', '', $data["Email"]);
		if (!empty($data["DateOfBirth"])) {
			$data["DateOfBirth"] = date("d-m-Y", strtotime($data["DateOfBirth"]));
			$dateOfbirth = explode("-", $data["DateOfBirth"]);
			if (strlen($dateOfbirth[2]) == 2) {
				$year = "20" . $dateOfbirth[2];
				if ($year > date("Y")) {
					$year = "19" . $dateOfbirth[2];
				}
				$data["DateOfBirth"] = date("d-m-Y", strtotime($dateOfbirth[0] . "-" . $dateOfbirth[1] . "-" . $year));
			}
		}
		if ($data["ClubID"] =="") {
			$data["ClubID"] = 0;
		}
		if ($data["SocietyID"] =="") {
			$data["SocietyID"] = 0;
		}
		if ($data["JobType"] ==2) {
			$data["JobTitle"] = 0;
		}
		foreach ($data as $key=>$value) {
			if($value==""){
				unset($data[$key]);
			}
		}

		$UserProfile = $UserProfileDB -> updateProfile($data, $id);

		$response = array("OK" => 1);
		if ($UserProfile > 0) {
			$response = array("OK" => 0, "ID" => $UserProfile);
		}

		if (isset($data["Email"])) {

			
			$profile = $UserProfileDB -> getUsername($id);
			if (isset($profile["CID"])) {

				if ($profile["Email"] != $profile["Username"]) {
					//save email
					$pcDB = new Model_DbTable_Credentials;
					$save = $pcDB -> updateData(array("Username" => $data["Email"]), $id);
				}

			}
		}

		echo json_encode($response);
	}
	
	public function listleagues($id)
	{
		try{

		$DB = new Model_DbTable_SocietyStructures;
		$list = $DB->getAllData();
		$Union = new Model_DbTable_UnionSocietyStructures;
		$Structs = $Union->getAllDataByUnion($id);
		$Structs_list =array();
		if(count($Structs)>0){
			foreach ($Structs as $Struct) {
				$Structs_list[$Struct["STID"]]=$Struct->toArray();
			}
		}
		$dataList = array();
		if(count($list)>0){
			$n =0;
			foreach ($list as $data) {
	
				$dataList[$n]["Structure"]=$data["Name"];
				$dataList[$n]["STID"]=$data["STID"];
				$dataList[$n]["Position"]=$data["Position"];
				$dataList[$n]["USID"]=($Structs_list[$data["STID"]]["USID"])?:"";
				$dataList[$n]["UID"]=($Structs_list[$data["STID"]]["UID"])?:"";
				$dataList[$n]["Name"]=($Structs_list[$data["STID"]]["Name"])?:"";
				$n++;
			}
		}
		
		return $dataList;
		} catch(Exception $expression) {
			ErrorLog($expression);
			
		}
	}
	

	private function AccessControll() {
		$array = array("profile", "edit");
		$Action = $this -> getRequest() -> getActionName();
		if ($Action == "getmember") {
			$Action = "profile";
		}
		if (in_array($this -> getRequest() -> getActionName(), $array)) {
			$request = $this -> getRequest();
			$id = $request -> getParam("id");
			if ($this -> identity -> UserID != $id) {

				if (!isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"][$Action])) {
					$this -> _redirect("/");
				}
			}
		} else {
			if (!isset($this -> AccessRights[$this -> getRequest() -> getControllerName()]["Actions"][$Action])) {
				$this -> _redirect("/");
			}

		}

	}
	
	private function notEmpty($value,$default){
		if(empty($value) || $value =="undefined"){
			return $default;
		}else{
			return $value;
		}
		
	}
	
	private function getInstitutionType() {

		$Instdb = new Model_DbTable_IntuitutionTypes;
		$UnionsDB = new Model_DbTable_Unions;
		//$union = $UnionsDB->GetUnion($this->identity->UnionID);

		$this -> view -> assign("Institution", $Instdb -> listInstByUserLogin($this -> identity));
		$this -> view -> assign("Unions", $UnionsDB -> listUnionsByUserLogin($this -> identity));

	}
	
	public function testAction() {
		$request = $this->getRequest();
		
		if($request->isPost()){
			$id = $request->getParam("fid");
		$reportDB = new Model_MatchReport;
		$report = $reportDB->updateTimePlayed($id);
			echo $id;
			exit;
		}else{
			$FXDB = new Model_DbTable_Fixture;
			$Fixt = $FXDB->getAllFixtureIDs();
			$this->view->assign("fixture",$Fixt);
		}
		
		
	}
	public function tAction() {
		$request = $this->getRequest();
		$id = $request->getParam("fid");
		
		
		
	}

}
