<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


include("../conf/preferences.php");
session_name(SYS_APP_SESSNAME);
session_start();
include("../conf/langs/".$langs[$_SESSION['userlang']][0]."/MAIN.php");
include("../conf/connections.php");
include("../phplib/auth.php");
require_once("../phplib/utils.php");
require_once("../core/plugins.php");


$resId=$_REQUEST['resId'];
$conf=simplexml_load_file("../conf/resources/".$langs[$_SESSION['userlang']][0]."/".$_SESSION['conf'][$resId]->masterview);
$detail=simplexml_load_file("../conf/forms/".$langs[$_SESSION['userlang']][0]."/".$_SESSION['conf'][$resId]->detailview);
$accion=$_REQUEST['action'];

$campos=array();
$nodos=$detail->xpath('//control');	
foreach($nodos as $nodo){
	$campos[]=$nodo['name'];
}

$obj=NULL;		
$result="";		

switch($accion){
	case "getData":
		
		$table=array();										
		unset($_SESSION['uploads'][$resId]);				
		$errores=array();									
		$cols=0;											
		$_SESSION['current_master_page']=$_SERVER['REQUEST_URI'];
		$page=isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;										
		$pagesize=(isset($_REQUEST['pagesize']) && $_REQUEST['pagesize']!="0") ? $_REQUEST['pagesize'] : $conf->data->pagesize;		
		$orderby=isset($_REQUEST['orderby']) ? $_REQUEST['orderby'] : $conf->data->orderby;			
		$sortby=isset($_REQUEST['sortby']) ? $_REQUEST['sortby'] : $conf->data->sortby;				
		
		$consulta=(string)$conf->data->sql;
		$filtros=isset($conf->filters) ? FilterProcess::getQuery($consulta,$conf->filters) : '';	
		$consulta=str_replace("{@filters}",$filtros,$consulta);
		$consulta=Content::parse($consulta);														
		$consulta=exclContent($consulta);															
		
		$q=mysql_query($consulta . " ORDER BY " . $orderby) or die(mysql_error()."<br>" . $consulta . " ORDER BY " . $orderby);
		$totalrows=mysql_num_rows($q);
		$pages=ceil($totalrows/$pagesize);
		if((int)$page>=$pages-1 || (string)$page=='last') $page=$pages-1;
		if((int)$page<0 || (string)$page=='first') $page=0;
		$qlimit=((int)$pagesize>0) ? " LIMIT " . ($pagesize*$page) . "," . $pagesize : "";
		$q=mysql_query($consulta . " ORDER BY " . $orderby . " " . $sortby . " " . $qlimit) or die(mysql_error());
		$currows=mysql_num_rows($q);		
		
		foreach($conf->column_model->column as $columna){ $cols++; }		
		$cols+= (((string)$conf->layout->col_edit=="true") || ((string)$conf->layout->col_details=="true")) + ((string)$conf->layout->col_check=="true") + (isset($conf->data->field_sort));
		while($f=mysql_fetch_assoc($q)){
			$f["_".(string)$conf->data->field_key]=$f[(string)$conf->data->field_key];
			$tabla[]=$f;
			Content::$data['main']=$f;
		}
		
		
		$obj->paginator=getPaginator($page,$pages,7);	// APLAZADO
		$obj->paginator=str_replace("XHR.master9.php?","template_master_9.php?resId={$resId}&",$obj->paginator);
		
		$obj->data=$tabla;
		$obj->result="ok";
		$result=json_encode($obj);
		break;
	case "insertRecord":
		$process=new UserProcessing();
		$cadena="";
		$validation=new Validation($detail);
		$validation->values=$_POST['params'];
		$validation->data=$conf->data;
		$validation->action=$accion;
		$validation->proceed();
		if($validation->errors==NULL){
			$claves=array(); $valores=array();
			$campoclave=(string)$conf->data->field_key;
			foreach($_POST['params'] as $clave=>$valor){
				$claves[]=$clave;
				$valores[]="'$valor'";	
			}
			$sql="INSERT INTO ".$conf->data->table . " (".implode(", ",$claves) . ") VALUES (" . implode(", ",$valores) . ")";
			$cadena=$sql;
			
			if(isset($conf->data->events)){
				foreach($conf->data->events->event as $evento){
					if((string)$evento['type']!='onAfterInsert' || $accion!="insertRecord") continue;
					$recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM ".$conf->data->table." ORDER BY $campoclave DESC LIMIT 0,1"));
					if(!estaArchivoIncluido((string)$evento['src'])) include_once("../".$evento['src']);
					$nombreclase=(string)$evento['class'];
					$metodo=(string)$evento['method'];
					if(isset($evento['params'])){
						$params=explode("@@@",(string)$evento['params']);
						for($i=0;$i<count($params);$i++) $params[$i]=replaceSpecialParams($params[$i]);
					}else{
						$params=NULL;
					}
					$objeto2=new $nombreclase();
					$objeto2->resId=$resId;
					$objeto2->recordset=$recordset;
					$objeto2->old_recordset=NULL;
					$objeto2->mail=$mail;
					$objeto2->$metodo($params);
				}
			}
			
			$obj->result="ok";
		}else{
			$cadena="ERROR DE VALIDACIÓN\nHan ocurrido los siguientes errores:\n\n";
			foreach($validation->errors as $erroritem){$cadena.= "- ".$erroritem."\n"; }
			$obj->result="ko";
		}
		$obj->data=$cadena;
		$result=json_encode($obj);
		break;
	case "updateRecord":
		$process=new UserProcessing();
		$cadena="";
		$validation=new Validation($detail);
		$validation->values=$_POST['params'];
		$validation->data=$conf->data;
		$validation->action="edit";
		$validation->proceed();
		if($validation->errors==NULL){
			$clausulas=array();
			$campoclave=(string)$conf->data->field_key;
			foreach($_POST['params'] as $clave=>$valor){
				if(!in_array($clave,$campos)) continue;
				$clausulas[]="$clave='$valor'";
			}
			$sql="UPDATE ".$conf->data->table . " SET ".implode(", ",$clausulas) . " WHERE $campoclave='" . $_POST['params']['_'.$campoclave] . "'";
			$old_recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM " . $conf->data->table . " WHERE $campoclave='" . $_POST['params']['_'.$campoclave] . "'"));

			if(isset($conf->data->events)){
				foreach($conf->data->events->event as $evento){
					if((string)$evento['type']!='onBeforeUpdate' || $accion!="updateRecord") continue;
					$clavetemp=is_numeric($_REQUEST['id']) ? $_REQUEST['id'] : "'" . $_REQUEST['id'] . "'";
					$recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM ".$conf->data->table." WHERE $campoclave='" . $_POST['params']['_'.$campoclave] . "'"));
					if(!estaArchivoIncluido((string)$evento['src'])) include_once("../".$evento['src']);
					$nombreclase=(string)$evento['class'];
					$metodo=(string)$evento['method'];
					if(isset($evento['params'])){
						$params=explode("@@@",(string)$evento['params']);
						for($i=0;$i<count($params);$i++) $params[$i]=replaceSpecialParams($params[$i]);
					}else{
						$params=NULL;
					}
					$objeto=new $nombreclase();
					$objeto->resId=$resId;
					$objeto->recordset=$recordset;
					$objeto->mail=$mail;
					$objeto->$metodo($params);
				}
			}

			$q=mysql_query($sql) or die(mysql_error() . '\n' . $sql . '\n');
			
			if(isset($conf->data->events)){
				foreach($conf->data->events->event as $evento){
					if((string)$evento['type']!='onAfterUpdate' || $accion!="updateRecord") continue;
					$recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM ".$conf->data->table." WHERE $campoclave='" . $_POST['params']['_'.$campoclave] . "'"));
					if(!estaArchivoIncluido((string)$evento['src'])) include_once("../".$evento['src']);
					$nombreclase=(string)$evento['class'];
					$metodo=(string)$evento['method'];
					if(isset($evento['params'])){
						$params=explode("@@@",(string)$evento['params']);
						for($i=0;$i<count($params);$i++) $params[$i]=replaceSpecialParams($params[$i]);
					}else{
						$params=NULL;
					}
					$objeto2=new $nombreclase();
					$objeto2->resId=$resId;
					$objeto2->recordset=$recordset;
					$objeto2->old_recordset=$old_recordset;
					$objeto2->mail=$mail;
					$objeto2->$metodo($params);
				}
			}
			
			$obj->result="ok";
		}else{
			$cadena="ERROR DE VALIDACIÓN\nHan ocurrido los siguientes errores:\n\n";
			foreach($validation->errors as $erroritem){$cadena.= "- ".$erroritem."\n"; }
			$obj->result="ko";
		}
		$obj->data=$cadena;
		$obj->sql=$sql;
		$result=json_encode($obj);
		break;
	case "deleteRecord":
		$table=$conf->data->table;
		$campoclave=(string)$conf->data->field_key;
		
		$sql="SELECT * FROM $table WHERE $campoclave='{$_POST['key']}'";
		$recordset=mysql_fetch_assoc(mysql_query($sql));
		
		if(isset($conf->data->events)){
			foreach($conf->data->events->event as $evento){
				if((string)$evento['type']!='onBeforeDelete') continue;
				if(!estaArchivoIncluido((string)$evento['src'])) include_once("../".$evento['src']);
				$nombreclase=(string)$evento['class'];
				$metodo=(string)$evento['method'];
				if(isset($evento['params'])){
					$params=explode("@@@",(string)$evento['params']);
					for($i=0;$i<count($params);$i++) $params[$i]=Content::parse($params[$i]);
				}else{
					$params=NULL;
				}
				$objeto=new $nombreclase();
				$objeto->resId=$resId;
				$objeto->recordset=$recordset;
				$objeto->mail=$mail;
				$objeto->$metodo($params);
			}
		}

		$sql="SELECT * FROM " . SYS_MEDIA_TABLE . " WHERE idres=$resId AND idrec IN('{$_POST['key']}')";
		$q=mysql_query($sql);
		while($item=mysql_fetch_assoc($q)){
			if($item['readonly']!=1){
				@unlink($item['filename']);
				mysql_query("DELETE FROM " . SYS_MEDIA_TABLE . " WHERE id={$item['id']}");
			}
		}

		$sql="DELETE FROM $table WHERE $campoclave='{$_POST['key']}'";
		$q=mysql_query($sql);
		
		if(SYS_LOG_OPS==true){
			registerLog($resId,3);
		}

		if(isset($conf->data->events)){
			foreach($conf->data->events->event as $evento){
				if((string)$evento['type']!='onAfterDelete') continue;
				if(!estaArchivoIncluido((string)$evento['src'])) include_once("../".$evento['src']);
				$nombreclase=(string)$evento['class'];
				$metodo=(string)$evento['method'];
				if(isset($evento['params'])){
					$params=explode("@@@",(string)$evento['params']);
					for($i=0;$i<count($params);$i++) $params[$i]=Content::parse($params[$i]);
				}else{
					$params=NULL;
				}
				$objeto2=new $nombreclase();
				$objeto2->resId=$resId;
				$objeto2->recordset=$recordset;
				$objeto2->mail=$mail;
				$objeto2->$metodo($params);
			}
		}
		
		$obj->data="";
		$obj->result="ok";
		$result=json_encode($obj);
		break;
}
echo $result;
?>