<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(0);   
ini_set("memory_limit","800M");

class OrganisationsController extends Zend_Controller_Action
{
private $identity ;
private $UnionDetails;
private $AccessRights;
    public function init()
    {
    	
        /* Initialize action controller here */
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
        {
            $this->_redirect('/login/');
        }
        else
        {
            $this->identity = $auth->getIdentity();
        }
        
       
				
				
				$user = $auth->getIdentity();
				
				
					$db = new Model_Profile;
          	$this->identity = $db->getRow($user->UserID);
                
             if($this->identity->UnionType >2 ){
            
            if($this->identity->Administrator==1){
                }else{
           $author = $db->getRow($this->identity->author);
            if($author["UnionType"]<3){
                $this->_redirect('/union/first');
            }else{
                $this->_redirect('/union/');
            }
            }
	}				
	if($this->identity->Status <0)
        {
            $this->_redirect('/first');
	}
                
                
                
                $this->AccessRights = json_decode($this->identity->Role,true);
	$this->view->assign("AccessRoles",$this->AccessRights);
		
		// GET CURRENT REQUEST METHOD AND ACTIONS
		$this->view->assign("getControllerName",$this->getRequest()->getControllerName());
		$this->view->assign("getActionName",$this->getRequest()->getActionName());
		$this->view->assign("UserDetails",$this->identity);
		
		$UnionsDB = new Model_Unions;
		$this->UnionDetails = $UnionsDB->getRow($this->identity->UnionID);	
		$this->view->assign("UnionDetails",$this->UnionDetails);
                
                
    }




 public function addtestAction()
    {
    	$Model_Organisations = new Model_DbTable_Organisations;
    		//get Organisation Levels
    			
			$Levels	= $Model_Organisations->getLevels();
			$this->view->assign("Levels",$Levels);
			
			//get organisation Types
			$Types	= $Model_Organisations->getTypes();
			$this->view->assign("Types",$Types);
			
			//get school Types
			$SchoolTypes	= $Model_Organisations->getSchoolTypes();
			$this->view->assign("SchoolTypes",$SchoolTypes);
			
			//get association Types
			$AssociteTypes	= $Model_Organisations->getAssociationTypes();
			$this->view->assign("AssociateTypes",$AssociteTypes);
			
			//get organisations
			$AssociteTypes	= $Model_Organisations->getParents();
			$this->view->assign("Parents",$AssociteTypes);
			
			//GET COUNTRIES
			$CountryDB = new Model_DbTable_Country;
        	$Countries = $CountryDB->getAll();
       		$this->view->assign("CountryList",$Countries);
			
    	
    }

	public function getAllCities(){
		$CityDB = new Model_Cities;
        return $CityDB->getAll();
	}
	
	public function getAllSuburbs(){
		$SuburbsDB = new Model_Suburb;
        $Suburds = $SuburbsDB->getAll();
	}



    public function indexAction()
    {
       $this->AccessControll();
        $this->getInstitutionType();
    }
		
    public function indextestAction()
    {   
        $this->getInstitutionType();
    }	
    
		public function viewAction()
    {
                     echo "TIME: ".date("H:i:s");
       		$request = $this->getRequest();
					$id= $request->getParam("id");
				$UnionsDB = new Model_Unions;
					if($this->identity->UnionType ==3){
					
						$details = $UnionsDB->getRow($id);
						
						if($details["parentid"] != $this->identity->UnionID && $this->identity->UnionID !=$id){
							$id =$this->identity->UnionID;
						}
					
				  }
					 
					 
					if($id <1){
					$this->_redirect('/'.$this->getRequest()->getControllerName());
					 }
				
			
			
					// GET FIELD DETAILS
					
			$details = $UnionsDB->getRow($id);
			$this->view->assign("Row",$details);
			$Parentdetails = $UnionsDB->getRow($details["parentid"]);
			$this->view->assign("Parent",$Parentdetails);
					
			$dbUsers = new Model_Profile;
			$Personnal = $dbUsers->getAllByUnion($id);
			$this->view->assign("Personnellist",$Personnal->toArray());
                        
			$Players = $dbUsers->getAllByUnion($id,2);
			$this->view->assign("PlayersList",$Players->toArray());
                        
                        //Active Squads 
                        $SquadsDB = new Model_Squad;
                        $Squads = $SquadsDB->getActiveSquads($id);
                        $this->view->assign("ActiveSquads",count($Squads->toArray()));
                        
                        //Active Players
                        $Players = 0;
                        foreach ($Squads as $Squad) {
                            $Players = $Players+count(json_decode($Squad["Players"],true));
                        }
                         $this->view->assign("ActivePlayers",$Players);
                        //echo "<pre>";
                        //print_r($Squads->toArray());
			
                        
                        $this->getEnicity($id);
    }
    
    private function getEnicity($_id){
        $DB = new Model_Profile;
        
        $Administration = $DB->getAllByEnthnicity($_id,1);
       
      $this->view->assign("Administration",$Administration);
      
      $Coaches = $DB->getAllByEnthnicity($_id,3);
      $this->view->assign("Coaches",$Coaches);
      
      $Operational = $DB->getAllByEnthnicity($_id,49);
      $this->view->assign("Operational",$Operational);
      
      $Medicals = $DB->getAllByEnthnicity($_id,5);
      $this->view->assign("Medicals",$Medicals);
      
      $Referee = $DB->getAllByEnthnicity($_id,122);
      $this->view->assign("Referee",$Referee);
      $PLayers = $DB->getAllByEnthnicity($_id,2);
      $this->view->assign("PLayers",$PLayers);
      
    }
    
   private function calculetepercent(){
       
   }
    
    
		public function viewtestAction()
    {
                   
       		$request = $this->getRequest();
			$id= $request->getParam("id");
			$UnionsDB = new Model_Unions;
			if($this->identity->UnionType ==3){
				$details = $UnionsDB->getRow($id);
				if($details["parentid"] != $this->identity->UnionID && $this->identity->UnionID !=$id){
							$id =$this->identity->UnionID;
				}
					
			}
					 
					 
			if($id <1){
				$this->_redirect('/'.$this->getRequest()->getControllerName());
			}
				
			
			
					// GET FIELD DETAILS
					
					$details = $UnionsDB->getRow($id);
					$this->view->assign("Row",$details);
                                        $Parentdetails = $UnionsDB->getRow($details["parentid"]);
					$this->view->assign("Parent",$Parentdetails);
					
					$dbUsers = new Model_Profile;
			 		$list = $dbUsers->getAllByUnion($id);
					$this->view->assign("list",$list->toArray());
			
    }
	
    
 public function listtestAction()
    {
     $UnionsDB = new Model_Unions;
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->layout->disableLayout();
     
     $order = $_GET["order"][0]["dir"];
     $column= $_GET["order"][0]["column"];
     $searchSQL = null;
     $search = @$_GET["search"]["value"];
									
									
     switch ($column) 
     {
         case 0:
             $column = 'un_name';
         break;
         case 1:
             $column = 'un_name';
         break;
         case 2:
             $column = 'un_city';
         break;
         case 3:
             $column = 'Text';			
         break;
         case 4:
             $column = 'un_email';
         break;
         case 5:
             $column = 'un_tel';
         break;
         default:
             $column = 'un_name';
         break;
				
     
     }

     if($search){
         $searchSQL = $search;
         
     }
      $request = $this->getRequest();
      $type = $request->getParam("type");
      $orgid = $request->getParam("org");
                                
									if($search){
										$searchSQL = $search;
									}
    	
									$orglist = $UnionsDB->getAll($searchSQL,$column,$order,$type,$orgid);
   
     $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($orglist->toArray()));
     $paginator->setCurrentPageNumber(($_GET["start"]/$_GET["length"])+1);
     $paginator->setItemCountPerPage($_GET["length"]);
     $table = '{"draw":'.($_GET["draw"]+1).',"recordsTotal":'.count($orglist).',"recordsFiltered":'.count($orglist).',
						  		"data": [';
                                $i = 0;
                                $n = $_GET["start"]+1;
                                foreach($paginator as $data){
											$c = ",";
											if($i ==0){
												$c = "";
											}
											
											
											$table .=$c.'[
												"'.$n.'",
									      "<a href=/organisations/view/id/'.$data["un_id"].' >'.$data["un_name"].'</a>",
									      "'.$data["City"].'",
									       "'.$data["Text"].'",
									      "'.$data["un_email"].'",
									      "'.$data["un_tel"].'",
									       "<a class=isb-edit href=/organisations/edit/id/'.$data["un_id"].'></a><a class=isb-delete id='.$data["un_id"].' onclick=delete_acc(this) data-content=my test content  data-placement=top ></a>"
									       ]';
											
											$i++;
											$n++;
										}
									  $table .= '] }';
			echo $table;
				
		}   
    
    
		public function listAction()
     {
     $UnionsDB = new Model_Unions;
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->layout->disableLayout();
     
     $order = $_GET["order"][0]["dir"];
     $column= $_GET["order"][0]["column"];
     
    
									
									
     switch ($column) 
     {
         case 0:
             $column = 'un_name';
         break;
         case 1:
             $column = 'un_name';
         break;
         case 2:
             $column = 'un_city';
         break;
         case 3:
             $column = 'Text';			
         break;
         case 4:
             $column = 'un_email';
         break;
         case 5:
             $column = 'un_tel';
         break;
         default:
             $column = 'un_name';
         break;
				
     
     }
 
     
      $request = $this->getRequest();
      $DATA = $request->getParams();
      $type = $request->getParam("type");
      $orgid = $request->getParam("org");
       $search = $request->getParam("key");
      
      
                                
									if(!isset($DATA["key"])){
										$search= "";
									}
    	//
									$orglist = $UnionsDB->getAllByFilter($search,$column,$order,$type,$orgid);
   
     $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($orglist->toArray()));
     $paginator->setCurrentPageNumber(($_GET["start"]/$_GET["length"])+1);
     $paginator->setItemCountPerPage($_GET["length"]);
     $table = '{"draw":'.($_GET["draw"]+1).',"recordsTotal":'.count($orglist).',"recordsFiltered":'.count($orglist).',
						  		"data": [';
                                $i = 0;
                                $n = $_GET["start"]+1;
                                foreach($paginator as $data){
											$c = ",";
											if($i ==0){
												$c = "";
											}
											
											
											$table .=$c.'[
												"'.$n.'",
									      "<a href=/organisations/view/id/'.$data["un_id"].' >'.$data["un_name"].'</a>",
									      "'.$data["City"].'",
									       "'.$data["Type"].'",
									      "'.$data["un_email"].'",
									      "'.$data["un_tel"].'",
									       "<a class=isb-edit href=/organisations/edit/id/'.$data["un_id"].'></a><a class=isb-delete id='.$data["un_id"].' onclick=delete_acc(this) data-content=my test content  data-placement=top ></a>"
									       ]';
											
											$i++;
											$n++;
										}
									  $table .= '] }';
			echo $table;
				
		}   
    
    
		private function getInstitutionType(){
		
			$Instdb = new Model_IntuitutionTypes;
			$UnionsDB = new Model_Unions;
			//$union = $UnionsDB->GetUnion($this->identity->UnionID);
			
		 	$this->view->assign("Institution",$Instdb->listInstByUserLogin($this->identity));
			$this->view->assign("Unions",$UnionsDB->listUnionsByUserLogin($this->identity));
			
			
	}
		
	
		
		public function addAction()
    {
    	$dbSchool = new Model_Schools;
			$request = $this->getRequest();
			if($request->isPost()){
						
						
					
				
				
					$Data = $request->getParam("data");
					//if affilianted 
					$unId = $Data["UnqId"];
					//unset($Data["UnqId"]);
					if($Data["un_affiliate"]==1){
						$Data["parentid"] = 0;
						$Data["un_type"] = 11;
						
					}
					
					if($Data["un_type"]==0){
						$Data["un_type"] = 11;
					}
					$DistrictsWrapa = $request->getParam("DistrictsWrapa");
					/*
					echo "<pre>";
					print_r($Data);
					exit;
					 * */
					$uniMunDB = new Model_UnionMunicipality;
					$UnionsDB = new Model_Unions;
					
					$Data["AuthorID"] = $this->identity->UserID;
					$Data["un_name"] = str_replace("'", "`", $Data["un_name"]);
			$id = $UnionsDB->insertData($Data);
			
			
			
			if($id>0){
				
			$this->_helper->viewRenderer->setNoRender();
      		$this->_helper->layout->disableLayout();
			
			//INsert Members
				$db = new Model_Profile;
				$memberDATA = $request->getParam("admin");
				$memberDATA["UnionID"] = $id;
				$memberDATA["FullName"] = $memberDATA["FirstName"]." ".$memberDATA["LastName"];
				$memberDATA["UnionType"] =$Data["un_type"];
				$memberDATA["Admin"] =1;
				$memberDATA["JobType"] =1;
				$memberDATA["JobTitle"] =147;
				
				if(!empty($memberDATA["FirstName"]) && !empty($memberDATA["LastName"]) ){
					$UserID = $db->insertData($memberDATA);
				}
				
			
			
			
			if(count($DistrictsWrapa)>0){
				foreach($DistrictsWrapa as $District){
				$Disdata = array("UnionID"=>$id,"MunID"=>$District,"Type"=>1);
				$uniMunDB->insertData($Disdata);
			}
			
			}
			
			
			$Municipality = $request->getParam("MunicipalityWrapa");
			if(count($Municipality)>0){
			foreach($Municipality as $Municipal){
				$Mundata = array("UnionID"=>$id,"MunID"=>$Municipal,"Type"=>2);
				$uniMunDB->insertData($Mundata);
			}
			}
		
				
				$dbSchool->updateData(array("hide"=>1),"Institution ='".$Data["un_name"]."'");
				
				$historyDB = new Model_PlayersHistory;
				
							$password = $this->getPassword();
							$dbCredentials = new Model_Credentials;
							
							
							$insertToDb = $dbCredentials->insertData(
							array("Username"=>$memberDATA["Email"],"Password"=>md5($password),"UserID"=>$UserID,"EFLogin"=>1)
							);
							if($insertToDb){
								$EmailContent = new PG_Controller_Plugin_EmailLayout;
								$EmailContent->EmailTemplate($memberDATA["Email"],$UserID,1,1,$password);
								 
							}
							$MESSAGE = $this->identity->FirstName." ".$this->identity->LastName." create this account and a signed login details";
							$hdata = array("UserID"=>$insert,"Details"=>json_encode(array(array("DATE"=>date("Y-m-d H:i:s"),"CONTENT"=>$memberDATA))),"History"=>json_encode(array(array("DATE"=>date("Y-m-d H:i:s"),"MESSAGE"=>$MESSAGE))));
							$historyDB->insertData($hdata);
				
				
				
					
					$this->_redirect('/organisations/view/id/'.$id);
					}else{
						$this->view->assign("Row",$Data);
	$this->view->assign("error",'<div class="alert alert-danger">                
                    <h4 style="background:none">Error!</h4>
                   The Organisation could not be created,  Orgnisation ('.$Data["un_name"].') already exists
                </div>');
	
					}
			}
			
    		
					
    		$this->getInstitutionType();
                
                
                 $CountryDB = new Model_Country;
        $Countries = $CountryDB->getAll();
        $this->view->assign("CountryList",$Countries);
    }
    

    
    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 autocompleteAction()
    {
    	$this->_helper->viewRenderer->setNoRender();
      		$this->_helper->layout->disableLayout();
			
			
    			$request = $this->getRequest();
					$keyword = $request->getParam("keyword");
    			
					$dbSchool = new Model_Schools;
					$json = $dbSchool->getAutocomplete($keyword)->toArray() ;
					
				
					
					/*
					$arr = array();
					foreach ($json as $schools) {
						$arr[]= ucfirst($schools["Institution"]);
					}
					echo "<pre>";
					print_r($json);
					
					*/
					$provinceDB = new Model_Province;
					$MunicipalityDB = new Model_Municipality;
					$citiesDB = new Model_Cities;
		
					$json1 = array();
					$array = "[";
					$i=0;
						foreach($json as $v){
							
							$province = $provinceDB->fetchRow("Short ='".$v["Province"]."'");
							$Municipality = $MunicipalityDB->fetchRow("Code ='".$v["LMunCode"]."'");
							$un_cities = $citiesDB->fetchRow("City_id ='".$Municipality["CityID"]."'");
							$city = $explodAddress[count($explodAddress)-2];
							if($un_cities["City_id"]>0){
								$city = $un_cities["City"];
							}
							$c = ",";
							if($i==0){
								$c = "";
							}
							$explodAddress = explode(",", $v["StreetAddress"]);
							
							$array .= $c."{\"Institution\":\"".$this->transliterateString($v["Institution"])."\",
							\"ID\":\"".$v["SID"]."\",
							\"PID\":\"".$province["Province"]."\",
							\"Latitude\":\"".$v["Latitude"]."\",
							\"Longitude\":\"".$v["Longitude"]."\",
							\"District\":\"".strtoupper($v["District"])."\",
							\"DistrictLocal\":\"".strtoupper($Municipality["District"])."\",
							\"Code\":\"".$explodAddress[count($explodAddress)-1]."\",
							\"Suburb\":\"".$v["SP_Name"]."\",
							\"City\":\"".strtoupper($city)."\",
							\"Street\":\"".$explodAddress[0]."\",
							\"Init\":\"".$v["AddrInit"]."\",
							\"Surname\":\"".$v["Addressee"]."\",
							\"Telephone\":\"".$v["Telephone"]."\",
							\"cellno\":\"".$v["cellno"]."\"
							}";
						
							$i++;
							
						}
						 $array .= "]";
						
						// echo "<br />";
						
					
header('Content-Type: application/json;charset=utf-8');
echo $array;
				
					
		}
		
		function transliterateString($txt) {
    $transliterationTable = array('á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A', 'ă' => 'a', 'Ă' => 'A','Ë' => 'E',
     'â' => 'a', 'Â' => 'A', 'å' => 'a', 'Å' => 'A', 'ã' => 'a', 'Ã' => 'A', 'ą' => 'a', 'Ą' => 'A', 'ā' => 'a',
      'Ā' => 'A', 'ä' => 'ae', 'Ä' => 'AE', 'æ' => 'ae', 'Æ' => 'AE', 'ḃ' => 'b', 'Ḃ' => 'B', 'ć' => 'c', 'Ć' => 'C',
       'ĉ' => 'c', 'Ĉ' => 'C', 'č' => 'c', 'Č' => 'C', 'ċ' => 'c', 'Ċ' => 'C', 'ç' => 'c', 'Ç' => 'C', 'ď' => 'd',
        'Ď' => 'D', 'ḋ' => 'd', 'Ḋ' => 'D', 'đ' => 'd', 'Đ' => 'D', 'ð' => 'dh', 'Ð' => 'Dh', 'é' => 'e', 'É' => 'E', 'è' => 'e', 'È' => 'E', 'ĕ' => 'e', 'Ĕ' => 'E', 'ê' => 'e', 'Ê' => 'E', 'ě' => 'e', 'Ě' => 'E', 'ë' => 'e', 'Ë' => 'E', 'ė' => 'e', 'Ė' => 'E', 'ę' => 'e', 'Ę' => 'E', 'ē' => 'e', 'Ē' => 'E', 'ḟ' => 'f', 'Ḟ' => 'F', 'ƒ' => 'f', 'Ƒ' => 'F', 'ğ' => 'g', 'Ğ' => 'G', 'ĝ' => 'g', 'Ĝ' => 'G', 'ġ' => 'g', 'Ġ' => 'G', 'ģ' => 'g', 'Ģ' => 'G', 'ĥ' => 'h', 'Ĥ' => 'H', 'ħ' => 'h', 'Ħ' => 'H', 'í' => 'i', 'Í' => 'I', 'ì' => 'i', 'Ì' => 'I', 'î' => 'i', 'Î' => 'I', 'ï' => 'i', 'Ï' => 'I', 'ĩ' => 'i', 'Ĩ' => 'I', 'į' => 'i', 'Į' => 'I', 'ī' => 'i', 'Ī' => 'I', 'ĵ' => 'j', 'Ĵ' => 'J', 'ķ' => 'k', 'Ķ' => 'K', 'ĺ' => 'l', 'Ĺ' => 'L', 'ľ' => 'l', 'Ľ' => 'L', 'ļ' => 'l', 'Ļ' => 'L', 'ł' => 'l', 'Ł' => 'L', 'ṁ' => 'm', 'Ṁ' => 'M', 'ń' => 'n', 'Ń' => 'N', 'ň' => 'n', 'Ň' => 'N', 'ñ' => 'n', 'Ñ' => 'N', 'ņ' => 'n', 'Ņ' => 'N', 'ó' => 'o', 'Ó' => 'O', 'ò' => 'o', 'Ò' => 'O', 'ô' => 'o', 'Ô' => 'O', 'ő' => 'o', 'Ő' => 'O', 'õ' => 'o', 'Õ' => 'O', 'ø' => 'oe', 'Ø' => 'OE', 'ō' => 'o', 'Ō' => 'O', 'ơ' => 'o', 'Ơ' => 'O', 'ö' => 'oe', 'Ö' => 'OE', 'ṗ' => 'p', 'Ṗ' => 'P', 'ŕ' => 'r', 'Ŕ' => 'R', 'ř' => 'r', 'Ř' => 'R', 'ŗ' => 'r', 'Ŗ' => 'R', 'ś' => 's', 'Ś' => 'S', 'ŝ' => 's', 'Ŝ' => 'S', 'š' => 's', 'Š' => 'S', 'ṡ' => 's', 'Ṡ' => 'S', 'ş' => 's', 'Ş' => 'S', 'ș' => 's', 'Ș' => 'S', 'ß' => 'SS', 'ť' => 't', 'Ť' => 'T', 'ṫ' => 't', 'Ṫ' => 'T', 'ţ' => 't', 'Ţ' => 'T', 'ț' => 't', 'Ț' => 'T', 'ŧ' => 't', 'Ŧ' => 'T', 'ú' => 'u', 'Ú' => 'U', 'ù' => 'u', 'Ù' => 'U', 'ŭ' => 'u', 'Ŭ' => 'U', 'û' => 'u', 'Û' => 'U', 'ů' => 'u', 'Ů' => 'U', 'ű' => 'u', 'Ű' => 'U', 'ũ' => 'u', 'Ũ' => 'U', 'ų' => 'u', 'Ų' => 'U', 'ū' => 'u', 'Ū' => 'U', 'ư' => 'u', 'Ư' => 'U', 'ü' => 'ue', 'Ü' => 'UE', 'ẃ' => 'w', 'Ẃ' => 'W', 'ẁ' => 'w', 'Ẁ' => 'W', 'ŵ' => 'w', 'Ŵ' => 'W', 'ẅ' => 'w', 'Ẅ' => 'W', 'ý' => 'y', 'Ý' => 'Y', 'ỳ' => 'y', 'Ỳ' => 'Y', 'ŷ' => 'y', 'Ŷ' => 'Y', 'ÿ' => 'y', 'Ÿ' => 'Y', 'ź' => 'z', 'Ź' => 'Z', 'ž' => 'z', 'Ž' => 'Z', 'ż' => 'z', 'Ż' => 'Z', 'þ' => 'th', 'Þ' => 'Th', 'µ' => 'u', 'а' => 'a', 'А' => 'a', 'б' => 'b', 'Б' => 'b', 'в' => 'v', 'В' => 'v', 'г' => 'g', 'Г' => 'g', 'д' => 'd', 'Д' => 'd', 'е' => 'e', 'Е' => 'E', 'ё' => 'e', 'Ё' => 'E', 'ж' => 'zh', 'Ж' => 'zh', 'з' => 'z', 'З' => 'z', 'и' => 'i', 'И' => 'i', 'й' => 'j', 'Й' => 'j', 'к' => 'k', 'К' => 'k', 'л' => 'l', 'Л' => 'l', 'м' => 'm', 'М' => 'm', 'н' => 'n', 'Н' => 'n', 'о' => 'o', 'О' => 'o', 'п' => 'p', 'П' => 'p', 'р' => 'r', 'Р' => 'r', 'с' => 's', 'С' => 's', 'т' => 't', 'Т' => 't', 'у' => 'u', 'У' => 'u', 'ф' => 'f', 'Ф' => 'f', 'х' => 'h', 'Х' => 'h', 'ц' => 'c', 'Ц' => 'c', 'ч' => 'ch', 'Ч' => 'ch', 'ш' => 'sh', 'Ш' => 'sh', 'щ' => 'sch', 'Щ' => 'sch', 'ъ' => '', 'Ъ' => '', 'ы' => 'y', 'Ы' => 'y', 'ь' => '', 'Ь' => '', 'э' => 'e', 'Э' => 'e', 'ю' => 'ju', 'Ю' => 'ju', 'я' => 'ja', 'Я' => 'ja');
    return str_replace(array_keys($transliterationTable), array_values($transliterationTable), $txt);
}
	function CheckLetters($field){
    $replace = [
    '&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
    '&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'Ae',
    '&Auml;' => 'A', 'Å' => 'A', 'Ā' => 'A', 'Ą' => 'A', 'Ă' => 'A', 'Æ' => 'Ae',
    'Ç' => 'C', 'Ć' => 'C', 'Č' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'Ď' => 'D', 'Đ' => 'D',
    'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ē' => 'E',
    'Ę' => 'E', 'Ě' => 'E', 'Ĕ' => 'E', 'Ė' => 'E', 'Ĝ' => 'G', 'Ğ' => 'G',
    'Ġ' => 'G', 'Ģ' => 'G', 'Ĥ' => 'H', 'Ħ' => 'H', 'Ì' => 'I', 'Í' => 'I',
    'Î' => 'I', 'Ï' => 'I', 'Ī' => 'I', 'Ĩ' => 'I', 'Ĭ' => 'I', 'Į' => 'I',
    'İ' => 'I', 'Ĳ' => 'IJ', 'Ĵ' => 'J', 'Ķ' => 'K', 'Ł' => 'K', 'Ľ' => 'K',
    'Ĺ' => 'K', 'Ļ' => 'K', 'Ŀ' => 'K', 'Ñ' => 'N', 'Ń' => 'N', 'Ň' => 'N',
    'Ņ' => 'N', 'Ŋ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
    'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'Ō' => 'O', 'Ő' => 'O', 'Ŏ' => 'O',
    'Œ' => 'OE', 'Ŕ' => 'R', 'Ř' => 'R', 'Ŗ' => 'R', 'Ś' => 'S', 'Š' => 'S',
    'Ş' => 'S', 'Ŝ' => 'S', 'Ș' => 'S', 'Ť' => 'T', 'Ţ' => 'T', 'Ŧ' => 'T',
    'Ț' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'Ū' => 'U',
    '&Uuml;' => 'Ue', 'Ů' => 'U', 'Ű' => 'U', 'Ŭ' => 'U', 'Ũ' => 'U', 'Ų' => 'U',
    'Ŵ' => 'W', 'Ý' => 'Y', 'Ŷ' => 'Y', 'Ÿ' => 'Y', 'Ź' => 'Z', 'Ž' => 'Z',
    'Ż' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
    'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'ā' => 'a', 'ą' => 'a', 'ă' => 'a',
    'æ' => 'ae', 'ç' => 'c', 'ć' => 'c', 'č' => 'c', 'ĉ' => 'c', 'ċ' => 'c',
    'ď' => 'd', 'đ' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
    'ë' => 'e', 'ē' => 'e', 'ę' => 'e', 'ě' => 'e', 'ĕ' => 'e', 'ė' => 'e',
    'ƒ' => 'f', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g', 'ĥ' => 'h',
    'ħ' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ī' => 'i',
    'ĩ' => 'i', 'ĭ' => 'i', 'į' => 'i', 'ı' => 'i', 'ĳ' => 'ij', 'ĵ' => 'j',
    'ķ' => 'k', 'ĸ' => 'k', 'ł' => 'l', 'ľ' => 'l', 'ĺ' => 'l', 'ļ' => 'l',
    'ŀ' => 'l', 'ñ' => 'n', 'ń' => 'n', 'ň' => 'n', 'ņ' => 'n', 'ŉ' => 'n',
    'ŋ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
    '&ouml;' => 'oe', 'ø' => 'o', 'ō' => 'o', 'ő' => 'o', 'ŏ' => 'o', 'œ' => 'oe',
    'ŕ' => 'r', 'ř' => 'r', 'ŗ' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
    'û' => 'u', 'ü' => 'ue', 'ū' => 'u', '&uuml;' => 'ue', 'ů' => 'u', 'ű' => 'u',
    'ŭ' => 'u', 'ũ' => 'u', 'ų' => 'u', 'ŵ' => 'w', 'ý' => 'y', 'ÿ' => 'y',
    'ŷ' => 'y', 'ž' => 'z', 'ż' => 'z', 'ź' => 'z', 'þ' => 't', 'ß' => 'ss',
    'ſ' => 'ss', 'ый' => 'iy', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G',
    'Д' => 'D', 'Е' => 'E', 'Ё' => 'YO', 'Ж' => 'ZH', 'З' => 'Z', 'И' => 'I',
    'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
    'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F',
    'Х' => 'H', 'Ц' => 'C', 'Ч' => 'CH', 'Ш' => 'SH', 'Щ' => 'SCH', 'Ъ' => '',
    'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'YU', 'Я' => 'YA', 'а' => 'a',
    'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo',
    'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l',
    'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's',
    'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch',
    'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e',
    'ю' => 'yu', 'я' => 'ya'
];

$field = str_replace(array_keys($replace), $replace, $field);  
    return $field;
}	
		
		
public function editAction()
    {
    	/*if($this->identity->UserID != 1){
    		
    	
    	echo "We currently working on this section!";
			$this->_helper->viewRenderer->setNoRender();
      		//$this->_helper->layout->disableLayout();
			}else{
				
			*/
    	$request = $this->getRequest();
				$id= $request->getParam("id");
				$UnionsDB = new Model_Unions;
			
			
			if($this->UnionDetails->un_type ==3 && $this->UnionDetails->parentid == 0){
				$UnionDetails = $UnionsDB->getRow($this->identity->UnionID);
			}else if($this->UnionDetails->un_type ==3 && $this->UnionDetails->parentid == $this->identity->UnionID){
				$UnionDetails = $UnionsDB->getRow($id);
			}else if($this->UnionDetails->un_type ==3 && $this->UnionDetails->parentid != 0 && $this->UnionDetails->parentid != $this->identity->UnionID){
				$this->_redirect('/organisations/');
			}else{
				$UnionDetails = $UnionsDB->getRow($id);
			}
			
			if($request->isPost()){
				$this->_helper->viewRenderer->setNoRender();
      		$this->_helper->layout->disableLayout();
					$Data = $request->getParam("data");
					
					//if affilianted 
					if($Data["un_affiliate"]==1){
						$Data["parentid"] = 0;
						$Data["un_type"] = 0;
					}
					  if($Data["un_type"]==0){
						$Data["un_type"] = 11;
					}
						$Data["un_name"] = str_replace("'", "`", $Data["un_name"]);
					
					$DistrictsWrapa = $request->getParam("DistrictsWrapa");
					
					
					
					$uniMunDB = new Model_UnionMunicipality;
					
			$save= $UnionsDB->updateData($Data, $id);
			$uniMunDB->delete("UnionID ='".$id."'");
			foreach($DistrictsWrapa as $District){
				$Disdata = array("UnionID"=>$id,"MunID"=>$District,"Type"=>1);
				$uniMunDB->insertData($Disdata);
			}
			
			
			$Municipality = $request->getParam("MunicipalityWrapa");
			
			foreach($Municipality as $Municipal){
				$Mundata = array("UnionID"=>$id,"MunID"=>$Municipal,"Type"=>2);
				$uniMunDB->insertData($Mundata);
			}
		
				
				if($save){
					$this->_redirect('/organisations/view/id/'.$id);
				}
					
					
			}
			
			
			$this->view->assign("Row",$UnionDetails);
    		$MunicipalityDB = new Model_Municipality;
				
		$citiesDB = new Model_Cities;
		$un_cities = $citiesDB->fetchAll();
		$db = new Model_Province;
		$ds =$db->fetchAll();
				
				
				$this->view->assign("DistrictArray",$MunicipalityDB->fetchAll()->toArray());
				$this->view->assign("MunicipalityArray",$MunicipalityDB->getMunicipality()->toArray());
				$this->view->assign("CitiesArray",$un_cities->toArray());
				
				$this->view->assign("District",json_encode($MunicipalityDB->getDistrict()->toArray()));
				$this->view->assign("Municipality",json_encode($MunicipalityDB->getMunicipality()->toArray()));
				$this->view->assign("Cities",json_encode($un_cities->toArray()));
				$this->view->assign("Provinces",$ds->toArray());
    		$this->getInstitutionType();
                
                // new 
                 $CountryDB = new Model_Country;
        $Countries = $CountryDB->getAll();
        $this->view->assign("CountryList",$Countries);
                
                
                
    	//	}
    }
		public function testAction()
    {
       
    }
		
		public function deleteAction()
    {
    	$this->_helper->viewRenderer->setNoRender();
    	$this->_helper->layout->disableLayout();
			
			
    			$request = $this->getRequest();
					echo $id = $request->getParam("id");
					$UnionsDB = new Model_Unions;
					$delete = $UnionsDB->delete("un_id ='".$id."'");
		}
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("/");
			}
		
	}
}
public function getorgsAction()
    {
    	$this->_helper->viewRenderer->setNoRender();
      $this->_helper->layout->disableLayout();
			
   		$request = $this->getRequest();
			
                        $search = $request->getParam("search");
				$UnionsDB = new Model_Unions;
				$unionss = $UnionsDB->search($search);
                                echo '<li style="height: 18px; clear: both; overflow: hidden" onclick="steptwo(this)" did="0"><span class="pull-left name">All Organisations</span> <span class="icon-ok pull-right" style="display: none"></span></li>';
				foreach ($unionss as $data) {
                                    if($data["un_id"]>0 && $data["un_name"]!=""){
                                        echo '<li style="height: 18px; clear: both; overflow: hidden" onclick="steptwo(this)" did="'.$data["un_id"].'"><span class="pull-left name">'.$data["un_name"].'</span> <span class="icon-ok pull-right" style="display: none"></span></li>';
					
                                    }
				}				
}
	
	public function csvAction()
    {
    	$this->_helper->viewRenderer->setNoRender();
      $this->_helper->layout->disableLayout();
	$csvData ='Abaqulusi Local Municipality,KZN263,KwaZulu-Natal,Zululand,Vryheid,"4,314","243,795",56.5
Albert Luthuli Local Municipality,MP301,Mpumalanga,Gert Sibande,Carolina,"5,559","187,629",33.7
Alfred Duma Local Municipality,KZN238,KwaZulu-Natal,Uthukela,Ladysmith,"3,764","356,274",94.6
Amahlathi Local Municipality,EC124,Eastern Cape,Amathole,Stutterheim,"4,505","101,826",22.6
Ba-Phalaborwa Local Municipality,LIM334,Limpopo,Mopani,Phalaborwa,"7,489","168,937",22.6
Beaufort West Local Municipality,WC053,Western Cape,Central Karoo,Beaufort West,"21,917","51,080",2.3
Bela-Bela Local Municipality,LIM366,Limpopo,Waterberg,Bela-Bela,"3,406","76,296",22.4
Bergrivier Local Municipality,WC013,Western Cape,West Coast,Piketberg,"4,407","67,474",15.3
Big Five Hlabisa Local Municipality,KZN276,KwaZulu-Natal,Umkhanyakude,Hlabisa,"3,466","116,622",33.6
Bitou Local Municipality,WC047,Western Cape,Eden,Plettenberg Bay,992,"59,157",59.60
Blouberg Local Municipality,LIM351,Limpopo,Capricorn,Senwabarwana,"9,540","172,601",18.10
Blue Crane Route Local Municipality,EC102,Eastern Cape,Sarah Baartman,Somerset East,"11,068","36,063",3.3
Breede Valley Local Municipality,WC025,Western Cape,Cape Winelands,Worcester,"3,834","176,578",46.1
Buffalo City Metropolitan Municipality,BUF,Eastern Cape,,East London,"2,750","834,997",303.6
Bushbuckridge Local Municipality,MP325,Mpumalanga,Ehlanzeni,Bushbuckridge,"10,248","546,215",53.3
Cape Agulhas Local Municipality,WC033,Western Cape,Overberg,Bredasdorp,"3,471","36,000",10.4
Cederberg Local Municipality,WC012,Western Cape,West Coast,Clanwilliam,"8,007","52,949",6.60
City of Cape Town Metropolitan Municipality,CPT,Western Cape,,Cape Town,"2,446","4,005,016","1,637.60"
City of Johannesburg Metropolitan Municipality,JHB,Gauteng,,Johannesburg,"1,645","4,949,347","3,008.80"
City of Matlosana Local Municipality,NW403,North West,Dr Kenneth Kaunda,Klerksdorp,"3,602","417,282",115.8
City of Tshwane Metropolitan Municipality,TSH,Gauteng,,Pretoria,"6,298","3,275,152",520
Collins Chabane Local Municipality,LIM345,Limpopo,Vhembe,Malamulele,"5,003","347,974",69.6
Dannhauser Local Municipality,KZN254,KwaZulu-Natal,Amajuba,Dannhauser,"1,707","105,341",61.7
Dawid Kruiper Local Municipality,NC087,Northern Cape,ZF Mgcawu,Upington,"44,231","107,161",2.4
Dihlabeng Local Municipality,FS192,Free State,Thabo Mofutsanyana,Bethlehem,"4,868","140,044",28.8
Dikgatlong Local Municipality,NC092,Northern Cape,Frances Baard,Barkly West,"7,316","48,473",6.6
Dipaleseng Local Municipality,MP306,Mpumalanga,Gert Sibande,Balfour,"2,645","45,232",17.1
Ditsobotla Local Municipality,NW384,North West,Ngaka Modiri Molema,Lichtenburg,"6,387","181,865",28.5
Dr Beyers Naudé Local Municipality,EC101,Eastern Cape,Sarah Baartman,Graaff-Reinet,"28,653","82,197",2.9
Dr JS Moroka Local Municipality,MP316,Mpumalanga,Nkangala,Siyabuswa,"1,416","246,016",173.7
Dr Nkosazana Dlamini Zuma Local Municipality,KZN436,KwaZulu-Natal,Harry Gwala,Creighton,"3,602","118,480",32.9
Drakenstein Local Municipality,WC023,Western Cape,Cape Winelands,Paarl,"1,538","280,195",182.2
eDumbe Local Municipality,KZN261,KwaZulu-Natal,Zululand,Paulpietersburg,"1,943","89,614",46.1
Ekurhuleni Metropolitan Municipality,EKU,Gauteng,,Germiston,"1,975","3,379,104","1,710.60"
Elias Motsoaledi Local Municipality,LIM472,Limpopo,Sekhukhune,Groblersdal,"3,713","268,256",72.2
Elundini Local Municipality,EC141,Eastern Cape,Joe Gqabi,Maclear,"5,019","144,929",28.9
eMadlangeni Local Municipality,KZN253,KwaZulu-Natal,Amajuba,Utrecht,"3,539","36,869",10.4
Emakhazeni Local Municipality,MP314,Mpumalanga,Nkangala,Belfast,"4,736","48,149",10.2
Emalahleni Local Municipality,EC136,Eastern Cape,Chris Hani,Lady Frere,"3,484","124,532",35.7
Emalahleni Local Municipality,MP312,Mpumalanga,Nkangala,eMalahleni,"2,678","455,228",170
Emfuleni Local Municipality,GT421,Gauteng,Sedibeng,Vanderbijlpark,966,"733,445",759.3
Emthanjeni Local Municipality,NC073,Northern Cape,Pixley ka Seme,De Aar,"13,472","45,404",3.4
Endumeni Local Municipality,KZN241,KwaZulu-Natal,Umzinyathi,Dundee,"1,610","76,639",47.6
Engcobo Local Municipality,EC137,Eastern Cape,Chris Hani,Ngcobo,"2,484","162,014",65.2
Enoch Mgijima Local Municipality,EC139,Eastern Cape,Chris Hani,Queenstown,"13,584","267,011",19.7
Ephraim Mogale Local Municipality,LIM471,Limpopo,Sekhukhune,Marble Hall,"2,011","127,168",63.2
eThekwini Metropolitan Municipality,ETH,KwaZulu-Natal,,Durban,"2,556","3,702,231","1,448.50"
Fetakgomo/Greater Tubatse Local Municipality,LIM476,Limpopo,Sekhukhune,Apel,"5,693","489,902",86
Ga-Segonyana Local Municipality,NC452,Northern Cape,John Taolo Gaetsewe,Kuruman,"4,495","104,408",23.2
Gamagara Local Municipality,NC453,Northern Cape,John Taolo Gaetsewe,Kathu,"2,648","53,656",20.3
George Local Municipality,WC044,Western Cape,Eden,George,"5,191","208,237",40.1
Govan Mbeki Local Municipality,MP307,Mpumalanga,Gert Sibande,Secunda,"2,955","340,091",115.1
Great Kei Local Municipality,EC123,Eastern Cape,Amathole,Komga,"1,700","31,692",18.6
Greater Giyani Local Municipality,LIM331,Limpopo,Mopani,Giyani,"4,172","256,127",61.4
Greater Kokstad Local Municipality,KZN433,KwaZulu-Natal,Harry Gwala,Kokstad,"2,680","76,753",28.6
Greater Letaba Local Municipality,LIM332,Limpopo,Mopani,Modjadjiskloof,"1,891","218,030",115.3
Greater Taung Local Municipality,NW394,North West,Dr Ruth Segomotsi Mompati,Taung,"5,639","167,827",29.8
Greater Tzaneen Local Municipality,LIM333,Limpopo,Mopani,Tzaneen,"2,897","416,146",143.7
Hantam Local Municipality,NC065,Northern Cape,Namakwa,Calvinia,"39,085","21,540",0.6
Hessequa Local Municipality,WC042,Western Cape,Eden,Riversdale,"5,733","54,237",9.5
Impendle Local Municipality,KZN224,KwaZulu-Natal,uMgungundlovu,Impendle,"1,610","29,526",18.3
Ingquza Hill Local Municipality,EC153,Eastern Cape,OR Tambo,Flagstaff,"2,477","303,379",122.5
Inkosi Langalibalele Local Municipality,KZN237,KwaZulu-Natal,Uthukela,Estcourt,"3,399","215,182",63.3
Intsika Yethu Local Municipality,EC135,Eastern Cape,Chris Hani,Cofimvaba,"2,873","152,159",53
Inxuba Yethemba Local Municipality,EC131,Eastern Cape,Chris Hani,Cradock,"11,663","70,493",6
Joe Morolong Local Municipality,NC451,Northern Cape,John Taolo Gaetsewe,Mothibistad,"20,180","84,201",4.2
Jozini Local Municipality,KZN272,KwaZulu-Natal,Umkhanyakude,Jozini,"3,442","198,215",57.6
Kagisano-Molopo Local Municipality,NW397,North West,Dr Ruth Segomotsi Mompati,Ganyesa,"23,827","102,703",4.3
Kai !Garib Local Municipality,NC082,Northern Cape,ZF Mgcawu,Kakamas,"26,377","68,929",2.6
Kamiesberg Local Municipality,NC064,Northern Cape,Namakwa,Garies,"14,208","9,605",0.7
Kannaland Local Municipality,WC041,Western Cape,Eden,Ladismith,"4,765","24,168",5.1
Kareeberg Local Municipality,NC074,Northern Cape,Pixley ka Seme,Carnarvon,"17,701","12,772",0.7
Karoo Hoogland Local Municipality,NC066,Northern Cape,Namakwa,Williston,"30,230","13,009",0.4
Kgatelopele Local Municipality,NC086,Northern Cape,ZF Mgcawu,Daniëlskuil,"2,478","20,691",8.3
Kgetlengrivier Local Municipality,NW374,North West,Bojanala,Koster,"3,973","59,562",15
Khâi-Ma Local Municipality,NC067,Northern Cape,Namakwa,Pofadder,"15,715","12,333",0.8
!Kheis Local Municipality,NC084,Northern Cape,ZF Mgcawu,Groblershoop,"11,107","16,566",1.5
King Sabata Dalindyebo Local Municipality,EC157,Eastern Cape,OR Tambo,Mthatha,"3,019","488,349",161.8
Knysna Local Municipality,WC048,Western Cape,Eden,Knysna,"1,109","73,835",66.6
Kopanong Local Municipality,FS162,Free State,Xhariep,Trompsburg,"15,645","49,999",3.2
Kou-Kamma Local Municipality,EC109,Eastern Cape,Sarah Baartman,Kareedouw,"3,642","43,688",12
Kouga Local Municipality,EC108,Eastern Cape,Sarah Baartman,Jeffreys Bay,"2,670","112,941",42.3
KwaDukuza Local Municipality,KZN292,KwaZulu-Natal,iLembe,KwaDukuza,735,"276,719",376.5
Laingsburg Local Municipality,WC051,Western Cape,Central Karoo,Laingsburg,"8,784","8,895",1
Langeberg Local Municipality,WC026,Western Cape,Cape Winelands,Ashton,"4,518","105,483",23.3
Lekwa Local Municipality,MP305,Mpumalanga,Gert Sibande,Standerton,"4,557","123,419",27.1
Lekwa-Teemane Local Municipality,NW396,North West,Dr Ruth Segomotsi Mompati,Christiana,"3,654","56,025",15.3
Lepelle-Nkumpi Local Municipality,LIM355,Limpopo,Capricorn,Chuniespoort,"3,484","235,380",67.6
Lephalale Local Municipality,LIM362,Limpopo,Waterberg,Lephalale,"13,794","140,240",10.2
Lesedi Local Municipality,GT423,Gauteng,Sedibeng,Heidelberg,"1,484","112,472",75.8
Letsemeng Local Municipality,FS161,Free State,Xhariep,Koffiefontein,"9,828","40,044",4.1
Madibeng Local Municipality,NW372,North West,Bojanala,Brits,"3,720","536,110",144.1
Mafube Local Municipality,FS205,Free State,Fezile Dabi,Frankfort,"3,971","57,574",14.5
Magareng Local Municipality,NC093,Northern Cape,Frances Baard,Warrenton,"1,546","24,059",15.6
Mahikeng Local Municipality,NW383,North West,Ngaka Modiri Molema,Mahikeng,"3,646","314,394",86.2
Makana Local Municipality,EC104,Eastern Cape,Sarah Baartman,Grahamstown,"4,376","82,060",18.8
Makhado Local Municipality,LIM344,Limpopo,Vhembe,Louis Trichardt,"7,605","416,728",54.8
Makhuduthamaga Local Municipality,LIM473,Limpopo,Sekhukhune,Jane Furse,"2,110","284,435",134.8
Maluti-a-Phofung Local Municipality,FS194,Free State,Thabo Mofutsanyana,Phuthaditjhaba,"4,338","353,452",81.5
Mamusa Local Municipality,NW393,North West,Dr Ruth Segomotsi Mompati,Schweizer-Reneke,"3,614","64,000",17.7
Mandeni Local Municipality,KZN291,KwaZulu-Natal,iLembe,Mandeni,545,"147,808",271
Mangaung Metropolitan Municipality,MAN,Free State,,Bloemfontein,"9,886","787,803",79.7
Mantsopa Local Municipality,FS196,Free State,Thabo Mofutsanyana,Ladybrand,"4,291","53,525",12.5
Maphumulo Local Municipality,KZN294,KwaZulu-Natal,iLembe,Maphumulo,896,"89,969",100.4
Maquassi Hills Local Municipality,NW404,North West,Dr Kenneth Kaunda,Wolmaransstad,"4,671","82,012",17.6
Maruleng Local Municipality,LIM335,Limpopo,Mopani,Hoedspruit,"3,563","99,946",28.1
Masilonyana Local Municipality,FS181,Free State,Lejweleputswa,Theunissen,"6,618","62,770",9.5
Matatiele Local Municipality,EC441,Eastern Cape,Alfred Nzo,Matatiele,"4,352","219,447",50.4
Matjhabeng Local Municipality,FS184,Free State,Lejweleputswa,Welkom,"5,690","429,113",75.4
Matzikama Local Municipality,WC011,Western Cape,West Coast,Vredendal,"12,981","71,045",5.5
Mbhashe Local Municipality,EC121,Eastern Cape,Amathole,Dutywa,"3,303","277,250",84
Mbizana Local Municipality,EC443,Eastern Cape,Alfred Nzo,Bizana,"2,415","319,948",132.5
Mbombela Local Municipality,MP326,Mpumalanga,Ehlanzeni,Nelspruit,"7,141","695,913",97.4
Merafong City Local Municipality,GT484,Gauteng,West Rand,Carletonville,"1,631","188,843",115.8
Metsimaholo Local Municipality,FS204,Free State,Fezile Dabi,Sasolburg,"1,717","163,564",95.3
Mhlontlo Local Municipality,EC156,Eastern Cape,OR Tambo,Qumbu,"2,880","189,176",65.7
Midvaal Local Municipality,GT422,Gauteng,Sedibeng,Meyerton,"1,722","111,612",64.8
Mkhambathini Local Municipality,KZN226,KwaZulu-Natal,uMgungundlovu,Camperdown,868,"57,075",65.7
Mkhondo Local Municipality,MP303,Mpumalanga,Gert Sibande,Piet Retief,"4,882","189,036",38.7
Mnquma Local Municipality,EC122,Eastern Cape,Amathole,Gcuwa,"3,137","246,813",78.7
Modimolle/Mookgophong Local Municipality,LIM368,Limpopo,Waterberg,Modimolle,"10,367","107,699",10.4
Mogalakwena Local Municipality,LIM367,Limpopo,Waterberg,Mokopane,"6,156","325,291",52.8
Mogale City Local Municipality,GT481,Gauteng,West Rand,Krugersdorp,"1,342","383,864",286
Mohokare Local Municipality,FS163,Free State,Xhariep,Zastron,"8,776","35,840",4.1
Molemole Local Municipality,LIM353,Limpopo,Capricorn,Dendron,"3,628","125,327",34.5
Moqhaka Local Municipality,FS201,Free State,Fezile Dabi,Kroonstad,"7,925","154,732",19.5
Moretele Local Municipality,NW371,North West,Bojanala,Makapanstad,"1,498","191,306",127.7
Moses Kotane Local Municipality,NW375,North West,Bojanala,Mogwase,"5,726","243,648",42.5
Mossel Bay Local Municipality,WC043,Western Cape,Eden,Mossel Bay,"2,001","94,135",47
Mpofana Local Municipality,KZN223,KwaZulu-Natal,uMgungundlovu,Mooi River,"1,757","37,391",21.3
Msinga Local Municipality,KZN244,KwaZulu-Natal,Umzinyathi,Tugela Ferry,"2,375","184,494",77.7
Msukaligwa Local Municipality,MP302,Mpumalanga,Gert Sibande,Ermelo,"6,016","164,608",27.4
Msunduzi Local Municipality,KZN225,KwaZulu-Natal,uMgungundlovu,Pietermaritzburg,751,"679,039",904.1
Mthonjaneni Local Municipality,KZN285,KwaZulu-Natal,King Cetshwayo,Melmoth,"1,639","78,883",48.1
Mtubatuba Local Municipality,KZN275,KwaZulu-Natal,Umkhanyakude,Mtubatuba,"1,970","202,176",102.6
Musina Local Municipality,LIM341,Limpopo,Vhembe,Musina,"10,347","132,009",12.8
Nala Local Municipality,FS185,Free State,Lejweleputswa,Bothaville,"4,129","78,515",19
Naledi Local Municipality,NW392,North West,Dr Ruth Segomotsi Mompati,Vryburg,"7,030","68,803",9.8
Nama Khoi Local Municipality,NC062,Northern Cape,Namakwa,Springbok,"17,990","46,512",2.6
Ndlambe Local Municipality,EC105,Eastern Cape,Sarah Baartman,Port Alfred,"1,841","63,180",34.3
Ndwedwe Local Municipality,KZN293,KwaZulu-Natal,iLembe,Ndwedwe,"1,093","143,117",131
Nelson Mandela Bay Metropolitan Municipality,NMA,Eastern Cape,,Port Elizabeth,"1,957","1,263,051",645.4
Newcastle Local Municipality,KZN252,KwaZulu-Natal,Amajuba,Newcastle,"1,856","389,117",209.7
Ngqushwa Local Municipality,EC126,Eastern Cape,Amathole,Peddie,"2,115","63,694",30.1
Ngwathe Local Municipality,FS203,Free State,Fezile Dabi,Parys,"7,055","118,907",16.9
Nkandla Local Municipality,KZN286,KwaZulu-Natal,King Cetshwayo,Nkandla,"1,828","114,284",62.5
Nketoana Local Municipality,FS193,Free State,Thabo Mofutsanyana,Reitz,"5,611","64,893",11.6
Nkomazi Local Municipality,MP324,Mpumalanga,Ehlanzeni,Malalane,"4,787","410,907",85.8
Nongoma Local Municipality,KZN265,KwaZulu-Natal,Zululand,Nongoma,"2,182","211,892",97.1
Nqutu Local Municipality,KZN242,KwaZulu-Natal,Umzinyathi,Nquthu,"1,962","171,325",87.3
Ntabankulu Local Municipality,EC444,Eastern Cape,Alfred Nzo,Ntabankulu,"1,385","128,848",93.1
Nyandeni Local Municipality,EC155,Eastern Cape,OR Tambo,Libode,"2,474","309,702",125.2
Okhahlamba Local Municipality,KZN235,KwaZulu-Natal,Uthukela,Bergville,"3,971","135,132",34
Oudtshoorn Local Municipality,WC045,Western Cape,Eden,Oudtshoorn,"3,540","97,509",27.5
Overstrand Local Municipality,WC032,Western Cape,Overberg,Hermanus,"1,675","93,407",55.8
Phokwane Local Municipality,NC094,Northern Cape,Frances Baard,Hartswater,828,"60,168",72.7
Phumelela Local Municipality,FS195,Free State,Thabo Mofutsanyana,Vrede,"8,196","50,054",6.1
Pixley ka Seme Local Municipality,MP304,Mpumalanga,Gert Sibande,Volksrust,"5,227","85,395",16.3
Polokwane Local Municipality,LIM354,Limpopo,Capricorn,Polokwane,"5,054","797,127",157.7
Port St Johns Local Municipality,EC154,Eastern Cape,OR Tambo,Port St Johns,"1,291","166,779",129.2
Prince Albert Local Municipality,WC052,Western Cape,Central Karoo,Prince Albert,"8,153","14,272",1.8
Ramotshere Moiloa Local Municipality,NW385,North West,Ngaka Modiri Molema,Zeerust,"7,323","157,690",21.5
Rand West City Local Municipality,GT485,Gauteng,West Rand,Randfontein,"1,115","265,887",238.5
Ratlou Local Municipality,NW381,North West,Ngaka Modiri Molema,Setlagole,"4,884","106,108",21.7
Ray Nkonyeni Local Municipality,KZN216,KwaZulu-Natal,Ugu,Port Shepstone,"1,487","348,533",234.4
Raymond Mhlaba Local Municipality,EC129,Eastern Cape,Amathole,Alice,"6,357","159,515",25.1
Renosterberg Local Municipality,NC075,Northern Cape,Pixley ka Seme,Petrusville,"5,529","11,818",2.1
Richmond Local Municipality,KZN227,KwaZulu-Natal,uMgungundlovu,Richmond,"1,231","71,322",57.9
Richtersveld Local Municipality,NC061,Northern Cape,Namakwa,Port Nolloth,"9,608","12,487",1.3
Rustenburg Local Municipality,NW373,North West,Bojanala,Rustenburg,"3,416","626,522",183.4
Sakhisizwe Local Municipality,EC138,Eastern Cape,Chris Hani,Cala,"2,318","63,846",27.5
Saldanha Bay Local Municipality,WC014,Western Cape,West Coast,Vredenburg,"2,015","111,173",55.2
Senqu Local Municipality,EC142,Eastern Cape,Joe Gqabi,Lady Grey,"7,329","140,720",19.2
Setsoto Local Municipality,FS191,Free State,Thabo Mofutsanyana,Ficksburg,"5,431","117,362",21.6
Siyancuma Local Municipality,NC078,Northern Cape,Pixley ka Seme,Douglas,"16,753","35,941",2.1
Siyathemba Local Municipality,NC077,Northern Cape,Pixley ka Seme,Prieska,"14,727","23,075",1.6
Sol Plaatje Local Municipality,NC091,Northern Cape,Frances Baard,Kimberley,"3,145","255,041",81.1
Stellenbosch Local Municipality,WC024,Western Cape,Cape Winelands,Stellenbosch,831,"173,197",208.4
Steve Tshwete Local Municipality,MP313,Mpumalanga,Nkangala,Middelburg,"3,976","278,749",70.1
Sundays River Valley Local Municipality,EC106,Eastern Cape,Sarah Baartman,Kirkwood,"5,995","59,793",10
Swartland Local Municipality,WC015,Western Cape,West Coast,Malmesbury,"3,707","133,762",36.1
Swellendam Local Municipality,WC034,Western Cape,Overberg,Swellendam,"3,835","40,211",10.5
Thaba Chweu Local Municipality,MP321,Mpumalanga,Ehlanzeni,Lydenburg,"5,719","101,895",17.8
Thabazimbi Local Municipality,LIM361,Limpopo,Waterberg,Thabazimbi,"11,190","96,232",8.6
Theewaterskloof Local Municipality,WC031,Western Cape,Overberg,Caledon,"3,259","117,167",36
Thembelihle Local Municipality,NC076,Northern Cape,Pixley ka Seme,Hopetown,"8,023","16,230",2
Thembisile Hani Local Municipality,MP315,Mpumalanga,Nkangala,eMpumalanga,"2,384","333,331",139.8
Thulamela Local Municipality,LIM343,Limpopo,Vhembe,Thohoyandou,"2,642","497,237",188.2
Tokologo Local Municipality,FS182,Free State,Lejweleputswa,Boshof,"9,326","29,149",3.1
Tsantsabane Local Municipality,NC085,Northern Cape,ZF Mgcawu,Postmasburg,"18,290","39,345",2.2
Tswaing Local Municipality,NW382,North West,Ngaka Modiri Molema,Delareyville,"5,875","129,052",22
Tswelopele Local Municipality,FS183,Free State,Lejweleputswa,Bultfontein,"6,524","47,373",7.3
Ubuhlebezwe Local Municipality,KZN434,KwaZulu-Natal,Harry Gwala,Ixopo,"1,669","118,346",70.9
Ubuntu Local Municipality,NC071,Northern Cape,Pixley ka Seme,Victoria West,"20,393","19,471",1
Ulundi Local Municipality,KZN266,KwaZulu-Natal,Zululand,Ulundi,"3,250","205,762",63.3
Umdoni Local Municipality,KZN212,KwaZulu-Natal,Ugu,Scottburgh,994,"144,551",145.5
uMfolozi Local Municipality,KZN281,KwaZulu-Natal,King Cetshwayo,KwaMbonambi,"1,300","144,363",111.1
uMhlabuyalingana Local Municipality,KZN271,KwaZulu-Natal,Umkhanyakude,Kwangwanase,"4,977","172,077",34.6
uMhlathuze Local Municipality,KZN282,KwaZulu-Natal,King Cetshwayo,Richards Bay,"1,233","410,465",332.8
uMlalazi Local Municipality,KZN284,KwaZulu-Natal,King Cetshwayo,Eshowe,"2,214","223,140",100.8
uMngeni Local Municipality,KZN222,KwaZulu-Natal,uMgungundlovu,Howick,"1,520","109,867",72.3
uMshwathi Local Municipality,KZN221,KwaZulu-Natal,uMgungundlovu,Wartburg,"1,866","111,645",59.8
Umsobomvu Local Municipality,NC072,Northern Cape,Pixley ka Seme,Colesberg,"6,813","30,883",4.5
uMuziwabantu Local Municipality,KZN214,KwaZulu-Natal,Ugu,Harding,"1,089","108,576",99.7
Umvoti Local Municipality,KZN245,KwaZulu-Natal,Umzinyathi,Greytown,"2,705","122,423",45.3
Umzimkhulu Local Municipality,KZN435,KwaZulu-Natal,Harry Gwala,Umzimkhulu,"2,436","197,286",81
Umzimvubu Local Municipality,EC442,Eastern Cape,Alfred Nzo,Mount Frere,"2,579","199,620",77.4
Umzumbe Local Municipality,KZN213,KwaZulu-Natal,Ugu,Mtwalume,"1,221","151,676",124.2
uPhongolo Local Municipality,KZN262,KwaZulu-Natal,Zululand,Pongola,"3,110","141,247",45.4
Ventersdorp/Tlokwe Local Municipality,NW405,North West,Dr Kenneth Kaunda,Potchefstroom,"6,398","243,527",38.1
Victor Khanye Local Municipality,MP311,Mpumalanga,Nkangala,Delmas,"1,568","84,151",53.7
Walter Sisulu Local Municipality,EC145,Eastern Cape,Joe Gqabi,Burgersdorp,"13,269","87,263",6.6
Witzenberg Local Municipality,WC022,Western Cape,Cape Winelands,Ceres,"10,753","130,548",12.1';
echo "<pre>";
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}

foreach ($array as $line) {
	$Model_City = new Model_Cities;
	$Model_District = new Model_DbTable_DistrictMunicipalities;
	$City = $Model_City->fetchRow("City ='".$line[4]."'");
	
	$local = ' District Municipality';
	if(!empty($line[3])){
		$district = $line[3].$local;
	}else{
		$district = $line[0];
	}
	$Distric = $Model_District->fetchRow("Name ='".$district."'");
	$LocalDistrict = new Model_DbTable_LocalMunicipalities;
	
	
	$line[3] = $Distric["ID"];
	$line[9] = $line[2];
	$line[4] = $City["City_id"];
	$line[2] = $City["ProvinceID"];
	$line[8] = $City["City"];
	$data["Name"] = $line[0];
	$data["Code"] = $line[1];
	$data["Province"] = $line[2];
	$data["District"] = $line[3];
	$data["City"] = $line[4];
	$data["Area"] = $line[5];
	$data["Population"] = $line[6];
	$data["Density"] = $line[7];
	
	
	//$LocalDistrict->insertData($data);
   print_r($data);
}





}

public function addfromgoogleAction(){
	 $this->_helper->viewRenderer->setNoRender();
     $this->_helper->layout->disableLayout();
	 
	 $CountryDB = new Model_DbTable_Country;
	 $ProvinceDB = new Model_DbTable_Province;
	 $CitiesDB = new Model_DbTable_Cities;
	 $SuburbDB = new Model_DbTable_Suburb;
	 
	 $OK = array();
	 $request = $this->getRequest();
	 if($request->isPost()){
	 	$p = $request->getParam("p");
	 	$c = $request->getParam("c");
		$countryName = $request->getParam("country");
		$cityName = $request->getParam("city");
		$subName    = $request->getParam("sub");
		$postal_code    = $request->getParam("postal_code");
		$opt = $request->getParam("opt");
		
			//add province
			$country = $CountryDB->fetchRow("country_code ='".$c."'");
			$countryID = 0;
			$provinceID = 0;
			$cityID = 0;
			if(count($country)>0){
				$countryID = $country["id"];
			}else{
				$countryID = $CountryDB->insertData(array("country_name"=>$countryName,"country_code"=>$c));
			}
			
			$Province = $ProvinceDB->fetchRow("Province ='".$p."' AND CountryID ='".$countryID."'");
			if(count($Province)>0){
				//dont save
				$provinceID = $Province["province_id"];
			}else{
				if($opt==1){
				$provinceID = $ProvinceDB->insertData(array("Province"=>$p,"CountryID"=>$countryID));
				$OK = array("OK"=>1);
				}
			}
			
			if(!empty($cityName)){
			$City = $CitiesDB->fetchRow("City ='".$cityName."' AND   ProvinceID ='".$provinceID."'  AND CountryID ='".$countryID."' ");
			if(count($City)>0){
				//dont save
				$cityID = $City["City_id"];
			}else{
				if($opt>1){
				$cityID = $CitiesDB->insertData(array("City"=>$cityName,"ProvinceID"=>$provinceID,"CountryID"=>$countryID));
				$OK = array("OK"=>1);
				}
			}
			}
			
			if(!empty($subName)){
			$Suburb = $SuburbDB->fetchRow("Suburb ='".$subName."' AND CityID ='".$cityID."' AND   ProvinceID ='".$provinceID."'  AND CountryID ='".$countryID."' ");
			if(count($Suburb)>0){
				//dont save
				//$cityID = $Suburb["City_id"];
			}else{
				if($opt==3){
					//
				$SuburbDB->insertData(array("PostalCode"=>$postal_code,"Suburb"=>$subName,"CityID"=>$cityID,"ProvinceID"=>$provinceID,"CountryID"=>$countryID));
				$OK = array("OK"=>1);
				}
			}
			}
		
	 	
	 }
	 
	 echo json_encode($OK);
	 
}

public function countrydetailsAction()
{
    
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->layout->disableLayout();
	 
	 $CountryID = $this->getRequest()->getParam("id");
	 
	 $DATA = array();
	 
	 
	 //GET PROVINCES
			$ProvinceDB = new Model_DbTable_Province;
        	$Province = $ProvinceDB->get_All_By_Country_ID($CountryID);
			if(count($Province)>0){
				$Province = $Province->toArray();
				$DATA["Province"] = $Province;
			}
			
       		
			
			//GET LOCAL MONICIPALITIES
			$MonicipalitiesDB = new Model_DbTable_LocalMunicipalities;
        	$Local = $MonicipalitiesDB->get_All_CountryID($CountryID);
       		
			if(count($Local)>0){
				$Local = $Local->toArray();
				$DATA["Districts"] = $Local;
			}
			
			//GET CITIES
			$CityDB = new Model_DbTable_Cities;
      		$Cities = $CityDB->getAll_CountryID($CountryID);
			if(count($Cities)>0){
				$Cities = $Cities->toArray();
				$DATA["Cities"] = $Cities;
			}
       		
			
			
			//GET SUBURBS
			$SuburbDB = new Model_DbTable_Suburb;
      		$Suburbs = $SuburbDB->getAll_CountryID($CountryID);
			if(count($Suburbs)>0){
				$Suburbs = $Suburbs->toArray();
				$DATA["Suburbs"] = $Suburbs;
			}
			
			echo json_encode($DATA);
			//print_r($DATA);
}






}

