<?php

class Dialer
{
	/**
	 * Database
	 *
	 * @var db
	 */
	private $db;
	protected $ManualTelephoneSelection;


	public function __construct($db)
	{
		$this->db = $db;
	}
	public function getTelData($idTel)
	{
		if(isset($this->telData)) return $this->telData;




		//$sql = "SELECT a.* FROM $telName a  INNER JOIN _AsteriskConnect b ON a.id = b.id_tel WHERE b.www_ids = ".$_SESSION['id_user'];
		$sql = "SELECT * FROM $this->telName WHERE id = $idTel";
		$this->db->LogWrite($sql,true,"did I go inside getTelData to get new number?");

		$this->telData = $this->db->fetchAssoc( $this->db->SQLexecute($sql) );
		foreach ($this->telData as $key => $td)
		{
			if(substr($key,0,4) == "tel_")
				$this->telData[ substr($key,4) ] = $td;
		}
		if($_SESSION['app_call_this_num'])
		{
			$num = explode('/',$_SESSION['app_call_this_num']);
			$this->telData['origNum'] = $this->telData['oms'].$this->telData['telephone'];
			$this->telData['oms'] = trim($num[0]);
			$this->telData['telephone'] = trim($num[1]);

		}

		$_SESSION['telData'] = $this->telData;

		$this->db->LogWrite(print_r($_SESSION['telData'],1),true,"SESSION telData inside getTelData, before my update of ID");

		return $this->telData;

	}


	public function setManualTelephoneSelection($where_manual_select = null) {
		if ($where_manual_select) $where_manual_select = " AND ".$where_manual_select;
		$this->ManualTelephoneSelection = $where_manual_select;
	}


	protected function getManualTelephoneSelection() {
		return $this->ManualTelephoneSelection;
	}


	public function getTelId($idProject,$id_user,$userType,$limit = 1, $id_searched_tel = null)
	{

		unset($_SESSION['app_exists']);
		unset($_SESSION['app_middle']);
		unset($_SESSION['app_call_this_num']);
		unset($_SESSION['app_koment']);


		$this->idProject = $idProject;
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

		//get project data
		$sql = "SELECT * FROM _Projects WHERE id = $idProject";
		if(!$row = $this->db->fetchAssoc($this->db->SQLexecute($sql))){	return false;}
		$tren_tabl = $row['proj_name'];
		$this->table = $tren_tabl;
		$this->telIndexTable = $tren_tabl.'___telIndex';
		$tel_reserve = $row['tel_reserve'];

		$telselect = $row['telselect']; // select telephone number manualy
		$strictlock_manual = $row['strictlock_manual']; // use strict lock also at manual telephone selection
		$telnum_select_type = $row['telnum_select_type']; // how we select numbers from sample (1 - random, 2 - row by row)

		$num_max_call = $row['num_max_call'];
		$num_max_call_app = $row['num_max_call_app'];
		//if appointemnts are locked to users
		$this->lockAppToUser = $row['lock_app_to_user'];
		$this->id_user = $id_user;
		$this->user_type = $userType;
		$this->idLayer = $row['id_select_layer'];
		$this->id_telname = $row['id_telname'];

        $this->use_lowest = $row['use_lowest'];
        $this->use_lowest_layer = $row['use_lowest_layer'];
		$_SESSION['id_telname'] = $this->id_telname;
		//get the name of the telephone database


		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT a.name FROM _TelephoneTables a WHERE a.id = ".$this->id_telname;
		try {
		$row = $this->db->fetchAssoc( $this->db->SQLexecute($sql) );
		} catch(Exception $e)
		{
			echo "NO DATABASE SELECTED OR NO SAMPLES AVAILABLE!<br>$sql";
			exit;
		}
		$telName = 'tel___'.$row['name'];
		$this->telName = $telName;
		$_SESSION['telName'] = $this->telName;
		if($this->id_user)
		{

			//if there are any leftovers with status=-1
			$sql = "SELECT id_tel FROM $this->telIndexTable WHERE status = -1 AND id_ank = $this->id_user AND ank_user_type = $this->user_type";
			try {
			$res = $this->db->SQLexecute($sql);
			}
			catch (Exception $e)
			{
				exit;
			}
			while ($row = $this->db->fetchRow($res))
				$idTels[] = $row[0];
			if($idTels)
			{

				$sql = "UPDATE $this->telIndexTable SET status = 0 WHERE id_tel IN (".implode(',',$idTels).')';
				$this->db->SQLexecute($sql);
				$sql = "UPDATE $this->telName SET proj_status = 0 WHERE id IN (".implode(',',$idTels).')';
				$this->db->SQLexecute($sql);

			}
		}
		$this->useTable = $this->telIndexTable.' AS a';
		$this->useLockTable = $this->useTable;
		$strictlock_region_def = $this->getStrictLock();

		//if I already got id_tel from search the name... skip searching for id_tel
		if ($id_searched_tel) {
			$telnum_index = $id_searched_tel;

			// dodano od soulskiner!!! 13.6.2012
			// checked if searched number is appointment, if it is, load all app properties
			$sql_show_dogovor = "SELECT  app_koment, app_time, a.id, app_middle, last_call,app_call_this_num, status FROM $this->useTable WHERE id_tel = ".$telnum_index;
			$res = $this->db->SQLexecute($sql_show_dogovor);
			if($row = $this->db->fetchAssoc($res))
			{
				if ($row['status'] == 91) {
					$_SESSION['app_exists'] = true;
					$_SESSION['app_koment'] = $row['app_koment'];
					if($row['app_middle'])
					{
						$_SESSION['app_middle'] = $row['app_middle'];
						//TODO: checkforquotas under right conditions!
					}
					if($row['app_call_this_num'])
					{
						$_SESSION['app_call_this_num'] = $row['app_call_this_num'];
					}
				}
			}
			// konec  dodano  od soulskiner!!! 13.6.2012

		} else {
			//checking appointments
			if($limit != 1 OR !$telnum_index = $this->checkAppointment($strictlock_region_def,$num_max_call_app,$num_max_call))
			{

				//if no appointments, get quota lock statement
				$trenutni_cas = time();
				// always use for call not yet used (0), busy (22) and no answer (25)
				// I changed that also 22 and 25 are call inside appointment, there are no such numbers probably any more
				$statusWhere = "(status = 0 OR status = 22 OR status = 25)";

				// if I have random selection I must seed random number (1 =  random)
				if ( $telnum_select_type == 1 ) {
					$rand_start_telbase = mt_rand(1, $tel_reserve) - 1;
				}


				/*
				 * we have few options
				 * - manual selection of telephone parameters from telephone table
				 * a) random selection
				 * b) row by row
				 *
				 * - automatic selection  from telephone table
				 * a) random selection
				 * b) row by row
				 */
				// First I try from begining to the end to find valid id_tel
				// telselect = Select telephone number manually
				// strictlock_manual = use also quota lock when creating ManualTelephoneSelection
				// telnum_select_type = selection method how to get numbers out of the sample
				if ($telselect) {
					$manualTelephoneWhere = $this->getManualTelephoneSelection();
					$telMethod = 11; // manual, random
					if ($telnum_select_type == 2) $telMethod = 12; // manual, row by row
				} else {
					//$manualTelephoneWhere = 1;

					// by Tanis...
                    //if($this->use_lowest and $this->checkDefiniton())
                    // by Borut 2015.11.20
                    if($this->use_lowest)
                    {
                    	if(strlen($this->use_lowest_layer) <= 0)
						{
							print "You didn't select layer for equaly distributed telephone numbers!";
							exit();
						}

						// Borut, 2015.11.20, add check method, if layer exist and if it is active
						$layerNum = $this->checkDefiniton();
						if (!$layerNum) {
							print "Layer does not exist or it is not ative for equaly distributed telephone numbers!";
							exit();
						}

						$dialerSettngs = configLoader::loadConfig('dailer_settings');
						define("MAX_NUMBER_OF_INDEXES", $dialerSettngs['max_number_of_indexes_to_check']);

						$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

                        $quota = "TP_" . $this->use_lowest_layer;
						// Borut 2015.11.20, add WHERE id_layer = $layerNum, this ensure that only one and single quota layer is calculated
                        $sql = "SELECT q_value," . $quota . "
                        		FROM " . DB_WARPIT_WEBCATI_BASE . ".". $this->table . "___quotaLimits
                        		WHERE id_layer = $layerNum";
						//echo "sql limits: $sql<br>";
                        $res = $this->db->SQLexecute($sql);
                        $limits = array();
						$total = 0;
                        while ($row = $this->db->fetchAssoc($res))
                        {
                        	if($row['q_value'] > 0)
													{

	                        	$total += intval($row['q_value']);
    	                        $limits[$row[$quota]]['limit'] = intval($row['q_value']);
        	                    $limits[$row[$quota]]['done'] = 0;
            	                //$limits[$row[$quota]]['sub'] = $limits[$row[$quota]]['limit'];
            	                $limits[$row[$quota]]['sub'] = 0;
															$limits[$row[$quota]][$quota] = $row[$quota];
													}
                        }

                        $sql = "SELECT $quota,count(*) as cnt FROM " . DB_WARPIT_WEBCATI_BASE . ".". $this->table . "___quotaCalc WHERE " . $quota . " IS NOT NULL GROUP BY " . $quota;
						//echo "quota count = ".$sql."<br>";
						//echo "<pre>limits:";
						//var_dump($limits);
						//echo "<hr>";
                        $res = $this->db->SQLexecute($sql);
                        while ($row = $this->db->fetchAssoc($res))
                        {
													if($limits[$row[$quota]]['limit'] && intval($row['cnt']) < $limits[$row[$quota]]['limit'])
                          {
														 	$limits[$row[$quota]]['done'] = intval($row['cnt']);
															$limits[$row[$quota]]['sub'] = $limits[$row[$quota]]['done']/$limits[$row[$quota]]['limit'];
													}
													else
													{
														unset($limits[$row[$quota]]);
													}

                        }
												if(count($limits) > 0)
												{
														uasort($limits, function($first, $second){
															return $first['sub'] > $second['sub']?1:-1;
														});
														$randIndex = 0;
														if(count($limits) < MAX_NUMBER_OF_INDEXES)
														{
															$randIndex = rand(0, count($limits) - 1);
														}
														else
														{
															$randIndex = rand(0,MAX_NUMBER_OF_INDEXES - 1);
														}

														$minKey = array_slice($limits, $randIndex, 1);
														$minKey = $minKey[0][$quota];
												}
												else {
													$minKey = '""';
												}



				//		var_dump($this->use_lowest_layer);
				//		echo "quota = $quota <=> min key = $minKey<br>";
                        $this->setManualTelephoneSelection( $quota . ' = ' . $minKey);

						$manualTelephoneWhere = $this->getManualTelephoneSelection();

                      	//echo "</pre>";
						//exit();
                    }
					$telMethod = 21; // automatic, random
					if ($telnum_select_type == 2) $telMethod = 22; // automatic, row by row
				}



				switch ($telMethod) {
					case 11:
						$select_telnum_index = "SELECT id_tel FROM $this->useTable
												WHERE a.id > $rand_start_telbase AND $statusWhere $manualTelephoneWhere
													AND call_time < $trenutni_cas AND call_num < $num_max_call AND tdisable=0
												ORDER BY a.id LIMIT $limit";
						break;
					case 12:
						$select_telnum_index = "SELECT id_tel FROM $this->useTable
												WHERE $statusWhere $manualTelephoneWhere AND call_time < $trenutni_cas
													AND call_num < $num_max_call AND tdisable=0
												ORDER BY a.id LIMIT $limit";
						break;
					case 21:
						if (file_exists("../_config/regionCallConfig.php")) {
							include "../_config/regionCallConfig.php";
							$userCallFilter = $dilerDefine['region'][$id_user];
							if ($userCallFilter) $addCallFilter = "AND $dilerDefineVar IN ($userCallFilter)";
							$select_telnum_index = "SELECT id_tel FROM $this->useTable
												WHERE a.id > $rand_start_telbase AND $statusWhere $manualTelephoneWhere
													AND call_time < $trenutni_cas AND call_num < $num_max_call $strictlock_region_def
													AND tdisable=0
													$addCallFilter
												ORDER BY a.id LIMIT $limit";
						} else {
							$select_telnum_index = "SELECT id_tel FROM $this->useTable
												WHERE a.id > $rand_start_telbase AND $statusWhere  $manualTelephoneWhere
													AND call_time < $trenutni_cas AND call_num < $num_max_call $strictlock_region_def AND tdisable=0
												ORDER BY a.id LIMIT $limit";
						}
						break;
					case 22:
						$select_telnum_index = "SELECT id_tel FROM $this->useTable
												WHERE $statusWhere AND call_time < $trenutni_cas
													AND call_num<$num_max_call $strictlock_region_def AND tdisable=0
												ORDER BY a.id LIMIT $limit";
						break;
				}
				$this->db->LogWrite($select_telnum_index,true, "SQL s katerim pridem do id_tel 1st");

			//	echo $select_telnum_index . "<br>tel method: $telMethod<br>";
				$select_lock_index = "LOCK TABLES $this->useLockTable WRITE";
				//echo "ordinary search: $select_lock_index<br>";
				$this->db->SQLexecute($select_lock_index);

				$result_telnum_index = $this->db->SQLexecute($select_telnum_index);

				if ( ! $this->db->NumRows($result_telnum_index) AND $telnum_select_type == 1 ) {
					$rand_start_telbase++;
					// there is no need to try row by row since if number exist it must be found in first try
					switch ($telMethod) {
						case 11:
							$select_telnum_index = "SELECT id_tel FROM $this->useTable
													WHERE a.id < $rand_start_telbase $manualTelephoneWhere AND $statusWhere
														AND call_time < $trenutni_cas AND call_num < $num_max_call AND tdisable=0
													LIMIT $limit";
							break;
						case 21:
							if (file_exists("../_config/regionCallConfig.php")) {
								include "../_config/regionCallConfig.php";
								$userCallFilter = $dilerDefine['region'][$id_user];
								if ($userCallFilter) $addCallFilter = "AND $dilerDefineVar IN ($userCallFilter)";
								$select_telnum_index = "SELECT id_tel FROM $this->useTable
													WHERE a.id < $rand_start_telbase AND $statusWhere $manualTelephoneWhere
														AND call_time < $trenutni_cas AND call_num < $num_max_call $strictlock_region_def
														AND tdisable=0
														$addCallFilter
													LIMIT $limit";
							} else {
								$select_telnum_index = "SELECT id_tel FROM $this->useTable
													WHERE a.id < $rand_start_telbase AND $statusWhere $manualTelephoneWhere
														AND call_time < $trenutni_cas AND call_num < $num_max_call $strictlock_region_def AND tdisable=0
													LIMIT $limit";
							}
							break;
					}
					$this->db->LogWrite($select_telnum_index,true, "SQL s katerim pridem do id_tel 2nd");
					$result_telnum_index = $this->db->SQLexecute($select_telnum_index);

					if ( !$this->db->NumRows($result_telnum_index) ) {
						$index_sucess = "NO";
					}
				} elseif ( ! $this->db->NumRows($result_telnum_index) AND $telselect ) {
					$index_sucess = "NO";
				}
				if($index_sucess != "NO")
				{
					if($limit > 1)
					{
						while ($row_telnum_index = $this->db->fetchRow($result_telnum_index))
		  					$telnum_index[] = $row_telnum_index[0];
					}
					else
					{
						$row_telnum_index = $this->db->fetchRow($result_telnum_index);
		  				$telnum_index = $row_telnum_index[0];
					}
				}

			}
		}

		$this->db->LogWrite($telnum_index,true, "Na tem mestu imam id_tel, tako ali drugace");
		if($telnum_index)
		{
				$isArr = 	is_array($telnum_index);
  				if($isArr)
  				{
  					$cond = "IN (".implode(',',$telnum_index).')';
  				}
  				else
  				{
  					$cond = "=".$telnum_index;
  				}
  				$query_update_telnum_sts = "UPDATE $this->telIndexTable as a SET status='-1',status_rec='0', id_ank='$this->id_user',ank_user_type = $this->user_type WHERE id_tel ".$cond;
		//echo "$query_update_telnum_sts<br>";
				$this->db->SQLexecute($query_update_telnum_sts);
				$select_unlock_index = "UNLOCK TABLES";
				$this->db->SQLexecute($select_unlock_index);
				if(!$isArr) {

	  				//zapisem record v ___telLog tabelo!
	  				$this->getTelData($telnum_index);
	  				$this->db->LogWrite(print_r($_SESSION['telData'],1),true, "check SESSION telData inside getTelId, before write to log table");

	  				$oms = $this->telData['oms'];
	  				$telephone = $this->telData['telephone'];
	  				$idRecord = $_SESSION['id_record'];

	  				$this->db->LogWrite("telData session id-".$_SESSION['telData']['id']."  --- telData session telephone-".$_SESSION['telData']['telephone'],true, "check some SESSION telData inside getTelId");

	  				$sql = "INSERT INTO $tren_tabl"."___telLog (id_tel,id_telname,id_user,user_type,oms,telephone,status,call_time)VALUES($telnum_index,$this->id_telname,$this->id_user,$this->user_type,'$oms','$telephone',-1,".time() .")";
					$this->db->SQLexecute($sql);
					$_SESSION['id_tellog'] = $this->db->GetLastInsertId();
				}

  				return $telnum_index;
		}
		else
		{
			$this->db->LogWrite($telnum_index,true, "If I do not have id_tel (telnum_index), this is FATAL ERROR, I should clean SESSION???");
			unset($_SESSION['telData']);

			$select_unlock_index = "UNLOCK TABLES";
			$this->db->SQLexecute($select_unlock_index);
		}

		return false;


	}
	private function getStrictLock()
	{
		$sql = "SELECT distinct id_question,source,q_name FROM quota_layer a left join quota_layer_addon b ON a.layer = b.id WHERE id_project = $this->idProject AND telSelect = 1";
		$res = $this->db->SQLexecute($sql);
		//we have all the fields that we have to bind!
		while ($row = $this->db->fetchRow($res))
		{
			$telField = $row[2];
			if($row[1] == 1)
				$telField  = 'tel_'.$telField;
			$strictlock_region_def .= ' AND a.'.$telField.' = b.TP_'.$row[2];
		}
		if($strictlock_region_def)
		{
			$strictlock_region_def .= ' AND isLocked = 0';
			$this->useTable .= ','.$this->table.'___quotaLock as b';
			$this->useLockTable .= ' WRITE,'.$this->table.'___quotaLock as b ';
		}
		return $strictlock_region_def;

		// Borut on 20150602, there was 60 lines from here bellow which I think were not needed, I delete them all,
		// check backup before 20150602, if needed
	}


	/**
	 * do not do something like this never in your life
	 * it will rearange SQL lock for bottom appointments locking mechanisem, from a,b table I will create a,b,c,d,e,f tables
	 * Borut, 20150602
	 */
	private function make_locking_string($str) {
		$str = str_replace(" WRITE", "", $str);
		$tmp = explode(",",$str);
		foreach($tmp AS $item) {
			$combined[] = "$item WRITE";
		}
		foreach($tmp AS $item) {
			$item = str_replace(array("as a","as b","AS a","AS b"), array("as c","as d","as c","as d"), $item);
			$combined[] = "$item WRITE";
		}
		foreach($tmp AS $item) {
			$item = str_replace(array("as a","as b","AS a","AS b"), array("as e","as f","as e","as f"), $item);
			$combined[] = "$item WRITE";
		}

		return "LOCK TABLES ".implode(",", $combined);
	}


	private function checkAppointment($quotas,$num_max_call,$num_max_call_busy)
	{
		unset($_SESSION['app_exists']);
		unset($_SESSION['app_middle']);
		unset($_SESSION['app_call_this_num']);
		unset($_SESSION['app_koment']);


		if ( $this->lockAppToUser) {
			$where = " AND id_ank = $this->id_user AND ank_user_type = $this->user_type";
		} else {
			// Borut, 20150531, if there is no lock to user, it can happen that two users at the same time click to check
			// for the new appointment, busy, no answer
			// I need to lock down also this procedure
			$select_lock_index = $this->make_locking_string($this->useLockTable);
			//echo "$select_lock_index<br>";
			$this->db->SQLexecute($select_lock_index);
		}

		// add also manual selection if it is set
		$manualTelephoneWhere = $this->getManualTelephoneSelection();

		$tren_cas = time();
		//tole sem vrgel 2013.03.04 ven iz spodnjega SQLa: $manual_region_where, BORUT
		// 2013.03.22 spremenil SQL za izbiro prvega naslednjega klica, da lahko loceno izberem za zasedene in dogovore
		// preko variabl $num_max_call in $num_max_call_busy
		//$sql_show_dogovor = "SELECT id_tel, app_koment, app_time, a.id, app_middle, last_call,app_call_this_num, status FROM $this->useTable WHERE status IN (22,25,91) $where AND app_time<'$tren_cas' AND call_num<$num_max_call AND tdisable=0 $quotas ORDER by status DESC,app_time LIMIT 1";

		$useTable_cd = str_replace(array("as a","as b","AS a","AS b"), array("as c","as d","as c","as d"), $this->useTable);
		$useTable_ef = str_replace(array("as a","as b","AS a","AS b"), array("as e","as f","as e","as f"), $this->useTable);

		$quotas_cd = str_replace(array("a.","b.","a.","b."), array("c.","d.","c.","d."), $quotas);
		$quotas_ef = str_replace(array("a.","b.","a.","b."), array("e.","f.","e.","f."), $quotas);

		$sql_show_dogovor =
		"SELECT * FROM (
			(SELECT id_tel, app_koment, app_time, a.id, app_middle, last_call,app_call_this_num, status, callback
				FROM $this->useTable
				WHERE callback>0 AND status IN (91) $where  $manualTelephoneWhere AND app_time<'$tren_cas' AND call_num<$num_max_call AND tdisable=0 $quotas
				ORDER BY app_time
				LIMIT 1
			)
		UNION ALL
			(SELECT id_tel, app_koment, app_time, c.id, app_middle, last_call,app_call_this_num, status, callback
				FROM $useTable_cd
				WHERE status IN (91) $where  $manualTelephoneWhere AND app_time<'$tren_cas' AND call_num<$num_max_call AND tdisable=0 $quotas_cd
				ORDER BY app_time
				LIMIT 1
			)
		UNION ALL
			(SELECT id_tel, app_koment, app_time, e.id, app_middle, last_call,app_call_this_num, status, callback
				FROM $useTable_ef
				WHERE status IN (22,25) $where  $manualTelephoneWhere AND app_time<'$tren_cas' AND call_num<$num_max_call_busy AND tdisable=0 $quotas_ef
				ORDER BY app_time
				LIMIT 1
			)
		) x
		ORDER BY status DESC, callback DESC
		LIMIT 1";
		//echo "$sql_show_dogovor<br>";


		$res = $this->db->SQLexecute($sql_show_dogovor);
		if($row = $this->db->fetchAssoc($res))
		{
			if ($row['status'] == 91) {
				$_SESSION['app_exists'] = true;
				$_SESSION['app_koment'] = $row['app_koment'];
				if($row['app_middle'])
				{
					$_SESSION['app_middle'] = $row['app_middle'];
					//TODO: checkforquotas under right conditions!
				}
				if($row['app_call_this_num'])
				{
					$_SESSION['app_call_this_num'] = $row['app_call_this_num'];
				}
			}


			return $row['id_tel'];

		}

		if ( !$this->lockAppToUser) {
			$select_unlock_index = "UNLOCK TABLES";
			//echo "$select_unlock_index";
			$this->db->SQLexecute($select_unlock_index);
		}

		return false;
	}

	private function checkDefiniton()
	{
		// Borut, 2015.11.20, create new SQL for check, because I need also layer
		// and I need to check only specifiy layer for use equaly distributed

		// Tanis's
	    /*
	    $sql = "SELECT distinct id_question,q_name
		 		FROM " . DB_WARPIT_WEBCATI_BASE . ".quota_layer a
               	LEFT JOIN " . DB_WARPIT_WEBCATI_BASE . ".quota_layer_addon b
		 		ON a.layer = b.id
		 		WHERE id_project = " . $this->idProject . " AND telSelect = 1";
        */

		// Borut's
		$sql = "SELECT layer
		 		FROM " . DB_WARPIT_WEBCATI_BASE . ".quota_layer a
               	LEFT JOIN " . DB_WARPIT_WEBCATI_BASE . ".quota_layer_addon b
		 		ON a.layer = b.id
		 		WHERE id_project = " . $this->idProject . " AND q_name = '".$this->use_lowest_layer."' AND active = 1";
		//echo "check Definition: $sql<br>";
		$res = $this->db->SQLexecute($sql);
		$row = $this->db->fetchAssoc($res);

        return $row[layer];

	}


}
?>
