<?php
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."webuserspool/UsersPoolinit.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.gridData.php");

class showVariablesManipulator extends GridDataManipulator
{
	
	public function selectAction()
	{
		$projId = $_POST['id_project'];
		if($_POST['grid'] == 'status')
		{
			$sql = "SELECT a.id as id_var,a.opis as name,b.show_status,a.show_default,isPublic,masterStatus FROM  _TelephoneStatus a LEFT JOIN _TelephoneStatusProject b ON b.id_status = a.id AND id_project = $projId";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			while ($row = $this->db->fetchAssoc($res))
			{
				//if show is net set, the default is true
				if($row['show_status'] == NULL)
					if($row['isPublic'])
						$row['show_status'] = $row['show_default'];
					else
						continue;
				$this->arr[] = $row;
			}
		}
		else 
		{
			$sql = "SELECT a.id as id_var,a.name,b.show_var FROM  _TelephoneTblDefaultVar a LEFT JOIN _TelephoneTblAddonProject b ON is_addon = 0 AND b.id_var = a.id AND id_project = $projId";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			while ($row = $this->db->fetchAssoc($res))
			{
				//if show is net set, the default is true
				$row['is_addon'] = 0;
				if($row['show_var'] == NULL) $row['show_var'] = true;
				$this->arr[] = $row;
			}
			$sql = "SELECT a.id as id_var,a.name,c.show_var,a.is_default FROM _TelephoneTablesAddon a INNER JOIN _Projects b ON a.id_telbaza = b.id_telname LEFT JOIN _TelephoneTblAddonProject c ON is_addon = 1 AND id_var = a.id AND c.id_project = $projId WHERE b.id = $projId ORDER BY a.orderBy";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			while ($row = $this->db->fetchAssoc($res))
			{
				//if show is net set, the default is true
				$row['is_addon'] = 1;
				if($row['show_var'] == null) $row['show_var'] = $row['is_default'];
				$this->arr[] = $row;
			}
		}
		return parent::selectAction();
	}
	public function updateAction()
	{
		$projId = $_POST['id_project'];
		$idVar = $_POST['id_var'];
		$val = $_POST['value'];
		if($_POST['grid'] == 'status')
		{
			if($_POST['field'] == 'name')
				$sql = "UPDATE _TelephoneStatus SET opis = '$val' WHERE id = $idVar"; 
			else
				$sql = "INSERT INTO _TelephoneStatusProject VALUES($projId,$idVar,$val) ON DUPLICATE KEY UPDATE show_status = $val";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();	
		}
		else
		{
			$isAddon = $_POST['isA'];
			$var = $_POST['name'];
			$sql = "INSERT INTO $this->table VALUES($idVar,$isAddon,$projId,$val) ON DUPLICATE KEY UPDATE show_var = $val";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
		}
		return "{success:true}";
	}
	public function insertStatusAction()
	{
		$status = $_POST['status'];
		$status_rec = $_POST['status_rec'];
		$autoDis = $_POST['autodial_disable'] ? 1 : 0;
		$show_default = $_POST['show_default'] ? 1 : 0;
		$isPublic = $_POST['isPublic'] ? 1 : 0;
		$sql = "(SELECT MAX(orderBy) FROM _TelephoneStatus)";
		$row = $this->db->fetchRow($this->db->SQLexecute($sql));
		$orderBy = $row[0] + 1;
		//$checkStat = $this->db->SQLexecut("SELECT id FROM _TelephoneStatus WHERE status = $status AND status_rec = $status_rec");
		$sql = "INSERT INTO _TelephoneStatus VALUES (null,$orderBy ,$autoDis,$status,$status_rec,'{$_POST['opis']}',$show_default,0,$isPublic )";
		$this->db->SQLexecute($sql);
		
		$id = $this->db->GetLastInsertId();
		
		$sql = "INSERT INTO _TelephoneStatusProject VALUES ({$_POST['id_project']},$id,1 )";
		$this->db->SQLexecute($sql);
		
		
		
		return "{success:true }";
		
	}
	public function changeDatabaseAction()
	{
		include (PATH_TO_ROOT.'config.php');
		$projId = $_POST['id_project'];
		$projName = $_POST['projName'];
		$value = $_POST['value'];
		
		if($this->db->TableExists($projName.'_structure' ))
		{
			//lets get the old value so that we can delete records that won't be used anymore!
			$sql = "SELECT id_telname FROM _Projects WHERE id = $projId";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			$row = $this->db->fetchRow($res);
			$oldTel = $row[0];
			if(!$oldTel > 0)
			{//no database selected...we have to create the basic tel fields
				$addFields[] = 'id_tel int(8)';
				$addFields[] = 'INDEX id_tel(id_tel)';
				$addFields[] = 'id_telname int(8)';
				$addFields[] = 'INDEX id_telname(id_telname)';
				$sql = "SELECT name FROM _TelephoneTblDefaultVar WHERE use_in_index = 1";
				if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
				while($row = $this->db->fetchRow($res))
					$addFields[] = 'TP_'.$row[0].' INT(10)';
			}
			else
			{//we have to delete all extra fields
				$sql = "SELECT name FROM _TelephoneTablesAddon WHERE id_telbaza = $oldTel";
				if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
				while($row = $this->db->fetchRow($res))
				{
					$sql = "ALTER TABLE {$projName}_structure DROP TP_".$row[0];
					if(!$this->db->SQLexecute($sql)) return $this->db->JsonError();
				}
				//remove project from old and delete telIndex table...
				$oldTelName = $this->db->get('_TelephoneTables',$oldTel,'name');
				if($oldTelName)
				{
					$sql = "UPDATE tel___$oldTelName SET proj_reserved = 0 WHERE proj_reserved = $projId";
					$this->db->SQLexecute($sql);
					//delete telIndex table!
					//$sql = 'DROP TABLE IF EXISTS '.$projName.'___telIndex';
					$bckDate = date("YmdHis");
					$this->db->RenameTable($projName.'___telIndex',$projName.'___telIndex'.$bckDate);
					//$this->db->RenameTable($projName.'___telLog',$projName.'___telLog'.$bckDate);
					$this->db->dropTable($projName.'___telLock');
					//delete all recodations
					$sql = "DELETE FROM recode WHERE id_project = $projId AND source != 2";
					$this->db->SQLexecute($sql);
					$sql = "DELETE FROM recolabel WHERE id_project = $projId AND source != 2";
					$this->db->SQLexecute($sql);
						
					
					//get all layers that use table data
					$sql = "SELECT DISTINCT layer FROM quota_layer WHERE id_project = $projId AND source != 2";
					$res = $this->db->SQLexecute($sql);
					while($row = $this->db->fetchRow($res))
						$layers[] = $row[0];
						
					if($layers)
					{
						$sql = "DELETE FROM quota_layer WHERE layer IN (".implode(',',$layers).")";
						$this->db->SQLexecute($sql);
						$sql = "DELETE FROM quota_layer_addon WHERE id IN (".implode(',',$layers).")";
						$this->db->SQLexecute($sql);
						if($this->db->TableExists($projName.'___quotaLimits'))
						{
							$sql = "DELETE FROM $projName"."___quotaLimits WHERE id_layer IN (".implode(',',$layers).")";
							$this->db->SQLexecute($sql);
						
						}
					}
				}
				
				
			}
			$sql = "SELECT name,type FROM _TelephoneTablesAddon WHERE id_telbaza = $value";
			if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();
			while($row = $this->db->fetchRow($res))
				$addFields[] = 'TP_'.$row[0].' '.getDataType($row[1]);
			if($addFields)
			{	
				$sql = "ALTER TABLE {$projName}_structure ADD (".implode(',',$addFields).')';
				$this->db->LogWrite($sql,true,"ALTER TABLE add id_tel...");
				if(!$this->db->SQLexecute($sql)) return $this->db->JsonError();
			}
		}
		$sql = "UPDATE _Projects SET id_telname = $value WHERE id = $projId";
		if(!$res = $this->db->SQLexecute($sql)) return $this->db->JsonError();

		
		// get tel table name
		$telTable_array = $this->db->get('_TelephoneTables',"id=".$value,'name',DB_WARPIT_WEBCATI_BASE);
		$telTable_name = $telTable_array[0];

		// create index and log if not yet created
		include_once (PATH_TO_ROOT.'webcati/_class/class.sampler.php');
		$cidx = new sampler($projId, $this->db, 0);
		
		$td = $this->db->describe("tel___".$telTable_name);
		if(substr($td['telephone']['type'],0,3) == 'int') {
			$telType = 'int';
		} else {
			$telType = 'varchar(30)';
		}
		
		foreach($cidx->table_fields as $key ) {
			if($key == 'oms' && $telType != 'int') {
				$columns.="`" . $key . "` varchar(7) NOT NULL DEFAULT '0',";
			} else {
				$columns.="`" . $key . "` int(7) NOT NULL DEFAULT '0',";
			}
			$keys.="KEY `" . $key . "` (`" . $key . "`),";
		}
		
		$cidx->createIndexTable($cidx->proj_name,$columns,$keys);
		$cidx->createLogTable($cidx->proj_name,$telType);
		
		
		return "{success:true}";
	}
}

$db->ChangeDatabase($_POST['database']);

$manipulator = new showVariablesManipulator($db,$_REQUEST['RMtable']);


$comm = $_POST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else 
{
	
	Echo '{success:false,error:"Unknown action!"}';	
	
}


?>
