<?
////////////////////////////////////////////////////
// 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("../phplib/phpmailer/class.phpmailer.php");
require_once("../core/plugins.php");



if(!isset($_REQUEST['resId'])) header("Location:error.php");
$resId=$_REQUEST['resId'];
$resultMessage='';
$_SESSION['currentRes']=$resId;
$detail=simplexml_load_file("../conf/forms/".$langs[$_SESSION['userlang']][0]."/".$_SESSION['conf'][$resId]->detailview);

$widget=new Controls();
$validation=new Validation($detail);
$process=new UserProcessing();
$comillas=$detail->metadata->aux_key['type']=="string" ? "'" : "";
$query="SELECT * FROM " . $detail->metadata->table . " WHERE " . $detail->metadata->aux_key['name'] . " = " . $comillas . Content::parse($detail->metadata->aux_key) . $comillas;
$q=mysql_query($query) or die("error mysql: " . $query);
$action=mysql_num_rows($q)>0 ? "edit" : "insert";
if(mysql_num_rows($q)>0) $f=mysql_fetch_array($q);

$clases_controles=$detail->xpath('//@class');
$hay_colorpicker=in_array("colorpicker",$clases_controles);
$hay_editor=in_array("editor",$clases_controles);
$hay_calendar=in_array("calendar",$clases_controles);
$hay_file=in_array("file",$clases_controles) || in_array("imageprocess",$clases_controles);
$hay_filelist=in_array("filelist",$clases_controles);

if($hay_file) $fops=new FileOps($resId);



function prepare($value,$node,$action){
	switch($node['type']){
		case "string":
		case "date":
		case "datetime":
		case "time":
			return "'" . anti_sql_inject($value) . "'";
		case "number":
			$valor=is_null($value) || $value=='' ? 'NULL' : $value;	
			return anti_sql_inject($valor);
			break;
		case "boolean":
			$valor=is_null($value) ? 0 : 1;
			return anti_sql_inject($valor);
			break;
		case "password":
			return "'" . Content::procPass($value, $node->method) . "'";
			break;
	}
}



if($_SERVER['REQUEST_METHOD']=='POST'){
	$_SESSION['form'][$resId]=$_POST;
	$validation->values=$_SESSION['form'][$resId];
	$validation->data=$detail->metadata;
	$validation->action=$action;
	$validation->proceed();
	if($validation->errors==NULL){
		$nodos=$detail->xpath('//control');	
		
		if(isset($master->metadata->events)){
		foreach($master->metadata->events->event as $evento){
			if((string)$evento['type']!='onBeforeUpdate') continue;
			if($action!="edit") continue;
			$clavetemp=is_numeric($_REQUEST['id']) ? $_REQUEST['id'] : "'" . $_REQUEST['id'] . "'";
			$recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM ".$master->data->table." WHERE ".$master->data->field_key."=".$clavetemp));
			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);
		}
		}
		
		if($action=="insert"){
			$cadena="INSERT INTO " . $detail->metadata->table . "(";
			$cadena2="";
			foreach($nodos as $nodo){
				if($nodo['name']==NULL || $nodo['class']=='dummy' || $nodo['class']=='related' || $nodo['aux']=='true') continue;
				$perfiles=explode(",",$nodo['profile']);
				if($nodo['profile']!=NULL & !in_array($_SESSION[session_id()]['grupo'],$perfiles)) continue;
				
				$cadena.=$nodo['name'] . ",";
				$cadenatemp=$_SESSION['form'][$resId][(string)$nodo['name']];
				if($nodo->preprocess){			
					$metodo=(string)$nodo->preprocess["method"];
					$cadenatemp=$process->$metodo($cadenatemp,(string)$nodo->preprocess)->content;
				}
				if($nodo['multilang']=="true"){
					$caux="";
					foreach($lngs as $lng=>$cont){
						$caux.="<!-- lang:{$lng} -->".$_POST[$nodo['name'] . "_h_".$lng]."<!-- /lang:{$lng} -->";
					}
					$cadena2.=prepare($caux,$nodo,$action) . ",";
				}else{
					$cadena2.=prepare($cadenatemp,$nodo,$action) . ",";
				}
				if($hay_file) $fops->prepareFile($cadenatemp,$nodo,$action);
			}
			if(isset($detail->metadata->field_author)){
				$cadena.=(string)$detail->metadata->field_author.",";
				$cadena2.=$_SESSION[session_id()]['id'].",";
			}
			$cadena=rtrim($cadena,",");
			$cadena2=rtrim($cadena2,",");
			$cadena.=") VALUES(";
			$cadena.=$cadena2 . ")";
			$resultMessage=MESG_INSERT_OK;
			
		}else if($action=="edit"){
			$cadena="UPDATE " . $detail->metadata->table . " SET ";
			foreach($nodos as $nodo){
				if($nodo['name']==NULL || $nodo['class']=='dummy' || $nodo['class']=='related' || $nodo['aux']=='true') continue;
				$perfiles=explode(",",$nodo['profile']);
				if($nodo['profile']!=NULL & !in_array($_SESSION[session_id()]['grupo'],$perfiles)) continue;
				if($nodo['class']=="password" && isset($_POST[(string)$nodo['name'] . "_check"])){continue;}
				
				$cadenatemp=$_SESSION['form'][$resId][(string)$nodo['name']];
				if($nodo->preprocess){		
					$metodo=(string)$nodo->preprocess["method"];
					$cadenatemp=$process->$metodo($cadenatemp,(string)$nodo->preprocess)->content;
				}
				if($nodo['multilang']=="true"){
					$caux="";
					foreach($lngs as $lng=>$cont){
						$caux.="<!-- lang:{$lng} -->".$_POST[(string)$nodo['name'] . "_h_".$lng]."<!-- /lang:{$lng} -->";
					}
					$cadena.=$nodo['name'] . "=" . prepare($caux,$nodo,$action) . ",";
				}else{
					$cadena.=$nodo['name'] . "=" . prepare($cadenatemp,$nodo,$action) . ",";
				}
				if($hay_file){
					$fops->recId=$clavetemp;
					$fops->prepareFile($cadenatemp,$nodo,$action);
				}
			}
			if(isset($detail->metadata->field_author)){
				$cadena.=(string)$detail->metadata->field_author."=".$_SESSION[session_id()]['id'].",";
			}
			$cadena=rtrim($cadena,",");
			$cadena.=" WHERE " . $detail->metadata->aux_key['name'] . "=" . $comillas . Content::parse($detail->metadata->aux_key) . $comillas;
			$resultMessage=MESG_EDIT_OK;
		}
		
		$q=mysql_query($cadena) or die(mysql_error() . '<br />' . $cadena . '<br/>');
		if($action=="insert"){
			$li=mysql_fetch_assoc(mysql_query("SELECT LAST_INSERT_ID() AS lid FROM " . $master->data->table));
			$sql="UPDATE " . SYS_MEDIA_TABLE . " SET temp=0, idrec={$li['lid']} WHERE temp=1 AND idrec IS NULL AND idres=$resId";
			mysql_query($sql);
		}
		if(SYS_LOG_OPS==true){
			$cadenalink=($action=="insert")? "" : basename($_SERVER['SCRIPT_NAME'])."?_action=edit&resId=$resId&id=$clavetemp&mymasterpage=$returnURL";
			echo registerLog($resId,($action=="insert" ? 1 : 2),($action=="insert" ? "" : $clavetemp),$cadenalink );
		}
		if(isset($master->metadata->events)){
		foreach($master->metadata->events->event as $evento){
			if((string)$evento['type']!='onAfterInsert' && (string)$evento['type']!='onAfterUpdate') continue;
			if((string)$evento['type']=='onAfterInsert' && $action!="insert") continue;
			if((string)$evento['type']=='onAfterUpdate' && $action!="edit") continue;
			if($action=="insert"){
				$recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM ".$master->data->table." ORDER BY ".$master->data->field_key." DESC LIMIT 0,1"));
			}else if($action=="edit"){
				$recordset=mysql_fetch_assoc(mysql_query("SELECT * FROM ".$master->data->table." WHERE ".$master->data->field_key."=".$clavetemp));
			}	
			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->mail=$mail;
			$objeto2->$metodo($params);
		}
		}
		unset($_SESSION['uploads'][$resId]);
		unset($_SESSION['form']);		// ojo con este!!
		$exito=true;
	}
}else{



	if($action=="edit"){
		$_SESSION['form'][$resId]=$f;
		unset($_SESSION['currentFiles'][$resId]);
		if($detail->reserveId!=''){
			$_SESSION[(string)$detail->reserveId]=$_REQUEST['id'];
		}
	}
}



$form_caption=$action=='insert' ? $detail->formcaption_insert : $detail->formcaption_update;
$page_caption=$detail->pagetitle;
$tabs=0;
$cadenatabs='';
$widget->process=$process;
foreach($detail->tab as $tab){
	if($tab['selected']=='true'){
		$cadenatabs.='<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#section'.$tabs.'">' . $tab['title'] . '</a></li>';
	}else{
		$cadenatabs.='<li class="ui-state-default ui-corner-top"><a href="#section'.$tabs.'">' . $tab['title'] . '</a></li>';
	}
	$tabs++;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title><? echo $_SESSION['application']['title'] ?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="../resources/themes/default/common.css" rel="stylesheet" type="text/css" media="screen" />
	<link href="../resources/themes/default/form_screen.css" rel="stylesheet" type="text/css" />
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.custom.css" rel="stylesheet" />
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.ekain.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/jquery-1.7.2.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.blockUI.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/js/jquery-ui-1.8.21.custom.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/jquery.ui.selectmenu.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.textarea.min.js" ></script>
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery.ui.selectmenu.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/fancybox/jquery.fancybox-1.3.4.pack.js" ></script>
	<link rel="stylesheet" href="../jslib/jq/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
	
	<script type="text/javascript" src="../jslib/utils.js"></script>
	<script src="../jslib/swfobject2.js" type="text/javascript"></script>
	
	<? if($hay_editor){ ?>
	<script type="text/javascript" src="../jslib/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
	<script type="text/javascript">
		tinyMCE.init({
		<?
		if(isset($detail->editor_config)){
			echo $detail->editor_config;
		}else{
			echo EDITOR_DEF_CONFIG;
		}
		?>
		});
		var fbconfig={};
		function elFinderBrowser (field_name, url, type, win) {
			var fbc=tinyMCE.activeEditor.getElement().id;
			var rf='';
			if(fbconfig[fbc]!=undefined && fbconfig[fbc]!=null){
				if(fbconfig[fbc].rootfolder!=undefined && fbconfig[fbc].rootfolder!=''){
					rf='?rootfolder='+fbconfig[fbc].rootfolder;
				}
			}
			var elfinder_url = '<? echo BASE_PATH ?>admin/jslib/elfinder/elfinder.php'+rf;    
			tinyMCE.activeEditor.windowManager.open({
				file: elfinder_url,
				title: 'elFinder 2.0',
				width: 900,  
				height: 450,
				resizable: 'yes',
				popup_css: false, 
				close_previous: 'no'
			}, {
				window: win,
				input: field_name
			});
			return false;
		}
	</script>
	<!-- /tinyMCE -->
	<? } ?>
	
	<? if($hay_colorpicker){ ?>
	<script type="text/javascript" src = "../jslib/jq/jpicker/jpicker-1.1.6.min.js" ></script>
	<link href="../jslib/jq/jpicker/css/jPicker-1.1.6.min.css" rel="stylesheet" type="text/css" />
	<? } ?>
	
	<? if(count($hay_map)>0){ ?>
	<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
	<script type="text/javascript">
	$(document).ready(function(){
		for(var item in mapas){
			createMap(item,mapas[item].data);
			updateMapControls(item);
		}
	});
	</script>
	<style type="text/css">
	<?
	foreach($hay_map as $ctrl){
		$anchura=(int)$ctrl->width;
		$altura=(int)$ctrl->height;
		$nombre=$ctrl['name'];
		$cadena="#".$nombre."_container{width:{$anchura}px; height:".($altura+32)."px}".chr(13);
		$cadena.="#".$nombre."_container .map_canvas{width:{$anchura}px; height:{$altura}px !important}".chr(13);
		$cadena.="#".$nombre."_container .map_shadow{width:{$anchura}px; height:{$altura}px !important}".chr(13);
		$cadena.="#".$nombre."_container .map_crosshair{top:".((int)($altura/2)-34)."px; left:".((int)($anchura/2)-10)."px;}".chr(13);
		$cadena.="#".$nombre."_container .map_area{top:".((int)($altura/2)-16)."px; left:".((int)($anchura/2)-16)."px;}".chr(13);
		$cadena.="#".$nombre."_container .map_controls{top:".($altura+10)."px;}".chr(13);
		echo $cadena;
	}
	?>
	</style>
	<? } ?>
	
	<? if($hay_calendar){ ?>
	<script type="text/javascript" src = "../jslib/jq/ui/i18n/jquery.ui.datepicker-<? echo $langs[$_SESSION['userlang']][0] ?>.js" ></script>
	<script type="text/javascript" src="../jslib/jq/ui.timepicker/jquery-ui-timepicker-addon.js"></script>
	<link type="text/css" href="../jslib/jq/ui.timepicker/jquery-ui-timepicker-addon.css" />
	<script type="text/javascript">
	var cal_date_format="<? echo CAL_DATE_FORMAT ?>";
	var cal_invalid_date="<? echo CAL_INVALID_DATE ?>";
	</script>
	<? } ?>

	<script type="text/javascript" src="../jslib/controls.js"></script>
	<script type="text/javascript">
	$(document).ready(function(){
		$('#tabla').tabs();
		$('#tipo').focus();
		$('select:not(.select_multiple), select:not(.select_editable)').selectmenu();
		$('button, input:submit, input:button, input:reset, .button, .link_button').button();
	});
	
	function presubmit(){
		<? if($hay_editor){ ?>tinyMCE.triggerSave();<? } ?>
		return true;
	}

	<?
	$tmplngs=array();
	foreach($lngs as $key=>$cont){$tmplngs[]=$key;}
	?>
	var langs=new Array("<? echo implode('","',$tmplngs) ?>")
	

	<? if(isset($detail->inline_scripts)) echo $detail->inline_scripts;	?>
	</script>
</head>
<body id="page_cuerpo" class="<? echo isset($detail->layout->class)? $detail->layout->class : 'bkg-detail-1' ?>">
<table width="100%" cellspacing="0" cellpadding="0" border="0" id="outer_table">
<tr>
	<td class="pageBar" height="1" >
	<h1><? echo $page_caption ?></h1>
	<div style="position:absolute; right:5px; top:3px;">
	<? if($detail->layout->help_topic!="" && $detail->layout->help_topic!=NULL){ ?><a href="#" onclick="javascript:openPopupWindow('../help/loader.php?topic=<? echo $detail->layout->help_topic ?>','helpWindow',500,500,true,'scrollbars')"><img src="../resources/themes/default/icon_help.png" style="border:0" /></a><? } ?>
	<? include("../jslib/layoutBtns.htm") ?>
	</div>
	</td>
</tr>
<tr>
	<td id="contenedor_cell" valign="bottom" align="center">
		<form action="template_detail_3.php" method="post" name="dataform" id="dataform" onsubmit="return presubmit();" class="ui-form">
		<? if($resultMessage!=''){ ?>
		<div class="introbox sombra roundcorners bkg_icon_info wpx220">
			<? echo $resultMessage ?>
		</div>
		<? }else{ ?>
		<? if(isset($detail->intro)) echo "<div class='introbox sombra roundcorners bkg_icon_info'>" . $detail->intro . "</div>" ?>
		<table width="<? echo $detail->layout->width ?>" border="0" align="center" cellspacing="0" cellpadding="0" id="tabla" class="sombra tablaformulario ui-corner-top">
		
		
		<thead>
		<tr>
			<td colspan="2" class="header_caption header_caption_bkg ui-corner-top"><? echo $form_caption ?></td>
		</tr>
		<tr>
			<td colspan="2" class="ui-tabs ui-widget ui-widget-content ui-corner-all header_tabbar" id="tabscell">
				<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
					<? echo $cadenatabs ?>
				</ul>
			</td>
		</tr>
		</thead>
		
		
		<?
		$cuenta=0;
		foreach($detail->tab as $currenttab){
		?>
		<tbody id="section<? echo $cuenta ?>" class="innertbody">
			<?
			$estilofila=0;
			foreach($currenttab->control as $control){
				if((string)$control['profile']!=''){
					$perfiles=explode(",",(string)$control['profile']);		
					if(!in_array($_SESSION[session_id()]['grupo'],$perfiles)) continue;
				}
				$rowstyle=$estilofila/2== floor($estilofila/2) ? "row1" : "row2";
				if(isset($control['group'])) $rowstyle.=" ".$control['group'];
				if($validation->errors[(string)$control['name']]!='') $rowstyle="row_ko";	
				$hidden=$control['class']=="hidden" ? ' style="display:none"' : '';
			?>
			<tr class="<? echo $rowstyle ?>" <? echo $hidden ?>>
				<td align="right" style="white-space:nowrap; min-width:150px"><? echo $control->title ?></td>
				<td valign="top" width="100%">
					<?
					$campo=$_SESSION['form'][$resId][(string)$control['name']];
					echo $widget->getControl($control,$campo,$action,$resId,$f['id']);
					?>
				</td>
			</tr>
			<?
				if($control['class']!='hidden')$estilofila++;
			}
			?>
		</tbody>
		<? 
		$cuenta++;
		} 
		?>
		
		<tfoot>
		<? if($validation->errors){ ?>
		<tr>
			<td colspan="2" class="validacion">
				<ul>
				<?
				foreach($validation->errors as $erroritem){
					echo '<li>' . $erroritem . '</li>';
				}
				?>
				</ul>
			</td>
		</tr>
		<? } ?>
		<tr>
			<td colspan="2" class="ui-state-default  footer">
				<? if(($action=="insert" && $permissions[1]==1) || ($action=="edit" && $permissions[2]==1)){ ?>
				<? if($detail->layout->but_submit=="true"){ ?><input type="submit" name="Submit" value="<? echo BUTTON_SEND ?>" class="but_medium bold" /><? } ?>
				<? } ?>
				<input type="reset" value="<? echo BUTTON_RESET ?>" class="but_medium grad_orange" />
				<input type="hidden" name="_action" value="<? echo $action ?>" />
				<input type="hidden" name="resId" value="<? echo $_REQUEST['resId'] ?>" />
				<?
				if(isset($detail->metadata->field_author)){
				?>
				<input type="hidden" name="<? echo $detail->metadata->field_author ?>" value="<? echo $_SESSION[session_id()]['id'] ?>" />
				<? } ?>
				<? if($action=='edit'){ ?>
				<input type="hidden" name="id" value="<? echo $_REQUEST['id'] ?>" />
				<? } ?>
			</td>
		</tr>
		</tfoot>
		</table>
		<? } ?>
		</form>
	</td>
</tr>
</table>
</body>
</html>
<?
unset($_SESSION['form'][$resId]);
?>