<?
////////////////////////////////////////////////////
// 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");

if(!isset($_REQUEST['resId'])) header("Location:error.php");
$resId=$_REQUEST['resId'];
$_SESSION['currentRes']=$resId;
$action=isset($_REQUEST['_action']) ? $_REQUEST['_action'] : 'update';
$master=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);

$field_key=(string)$master->data->field_key;
$table=(string)$master->data->table;
$id=$_REQUEST['id'];

$ids=array();
$orderby=$master->data->orderby;
$sql=$master->data->sql;
$filtros=isset($master->filters) ? FilterProcess::getQuery($consulta,$master->filters) : '';	
$sql=str_replace("{@filters}",$filtros,$sql);
$sql=Content::parse($sql);
$sql=exclContent($sql);
$qm=mysql_query($sql . " ORDER BY " . $orderby) or die(mysql_error()."<br>" . $sql);
while($fm=mysql_fetch_assoc($qm)) $ids[]=$fm[$field_key];
$pos=array_search($id, $ids);	
$totalrows=count($ids);


$sql="SELECT * FROM $table WHERE $field_key='$id'";
$q=mysql_query($sql);
$f=mysql_fetch_assoc($q);
$_SESSION['form'][$resId]=$f;
Content::$data['main']=$f;
unset($_SESSION['currentFiles'][$resId]);


$ttitle=(string)$detail->pagetitle;
$tlogo="../".SYS_USER_STYLES_PATH . $_SESSION['application']['logo'];
$tappname=$_SESSION['application']['title'];
$tdate=date(CAL_DATETIME_FORMAT);
$treturnurl=$_REQUEST['mymasterpage'];
$tgofirst=$_SERVER['PHP_SELF']."?". changeUrlParam("id",$ids[0]);
$tgoprev=$_SERVER['PHP_SELF']."?".($pos>0 ? changeUrlParam("id",$ids[$pos-1]) : changeUrlParam("id",$ids[$pos]));
$tgonext=$_SERVER['PHP_SELF']."?".($pos<count($ids)-1 ? changeUrlParam("id",$ids[$pos+1]) : changeUrlParam("id",$ids[$pos]));
$tgolast=$_SERVER['PHP_SELF']."?". changeUrlParam("id",$ids[count($ids)-1]);
$tcounter=($pos+1)."/".$totalrows;


$template=file_get_contents("../templates/template_report_1.htm");
$template=str_replace("{{templ:title}}",$ttitle,$template);
$template=str_replace("{{templ:logo}}",$tlogo,$template);
$template=str_replace("{{templ:appname}}",$tappname,$template);
$template=str_replace("{{templ:date}}",$tdate,$template);
$template=str_replace("{{templ:returnurl}}",$treturnurl,$template);
$template=str_replace("{{templ:counter}}",$tcounter,$template);
$template=str_replace("{{templ:gofirst}}",$tgofirst,$template);
$template=str_replace("{{templ:goprev}}",$tgoprev,$template);
$template=str_replace("{{templ:gonext}}",$tgonext,$template);
$template=str_replace("{{templ:golast}}",$tgolast,$template);
$pattern="/<!--{{templ:recordset}}-->(.*?)<!--{{\/templ:recordset}}-->/s";
preg_match($pattern,$template, $matches);
if(count($matches)>0){
	$subt=$matches[1]; $cadena='';
	foreach($detail->tab as $tab){
		foreach($tab->control as $control){
			$valor=getValue($control, $f);
			if($valor===false) continue;
			$fila=$subt;
			$fila=str_replace("{{templ:celltitle}}",(string)$control->title,$fila);
			$fila=str_replace("{{templ:cellcontent}}",$valor,$fila);
			$cadena.=$fila;
		}
	}
	$template=str_replace($matches[0],$cadena,$template);
}
echo $template;


function getValue($xml, $f){
	global $lngs; global $field_key; global $table; global $id;
	$value=$f[(string)$xml['name']];		
	$valor=false;
	switch((string)$xml['class']){
		case "textfield":
		case "textarea":
		case "editor":
		case "editablemenu":
			$valor=Content::parse($value);
			if($xml['multilang']=="true") $valor=Content::extractLang($valor, SYS_USER_LOCALE);
			break;
		case "checkbox":
			$valor=$value==1 ? BUTTON_YES : BUTTON_NO;
			break;
		case "spinner":
		case "slider":
			$valor=$value;
			break;
		case "password":
			$hidden=isset($xml->hidden) && $xml->hidden=="false" ? FALSE : TRUE;
			$valor=!$hidden ? $value : false;
			break;
		case "calendar":
			$formats=array("date"=>CAL_DATE_FORMAT, "datetime"=>CAL_DATETIME_FORMAT, "time"=>CAL_TIME_FORMAT);
			$fecha = new DateTime($value);
			$control=(string)$xml['type'];
			$formato=$formats[$control];
			$fechanula=($value=='' || $value==NULL || $value=='0000-00-00' || $value=='0000-00-00 00:00:00' || $fecha===false);
			$valor=$fechanula ? '' : $fecha->format($formato);
			break;
		case "colorpicker":
			if($value==NULL){
				$valor='';
			}else{
				$valor="<div style='width:20px; height:20px; border:1px solid #000; background-color:#".substr("000000".dechex($value),-6)."'>&nbsp;&nbsp;</div>";
			}
			$temp=$value==NULL ? '' : dechex($value);
			break;
		case "map":
			if($value==NULL || $value==''){
				$valor='';
			}else{
				$temp=explode(",",$value);
				$url="http://maps.google.com/maps/api/staticmap?sensor=true&center={$temp[0]},{$temp[1]}&zoom={$temp[2]}&size=400x300&maptype=roadmap&language=".SYS_USER_LOCALE;
				$valor="<img src='$url' />";
			}
			break;
		case "relatedselect":
			if($value==NULL || $value==''){
				$valor='';
			}else{
				$sql=str_replace("{@@@}", $f[(string)$xml['name']], (string)$xml->queries->query[0]);
				$qq=mysql_query($sql);	
				$valor='';
				while($ff=mysql_fetch_array($qq)){
					$valor.=$ff['tit']." >> ";
				}
				$valor=rtrim($valor," >> ");
			}
			break;
		case "file":
		case "imageprocess":
			if($value==NULL || $value==''){
				$valor='';
			}else{
				if(isset($xml->preview_image) && $xml->subtype=="image"){
					$valor="<img src='../.." . SYS_BASE_PATH . SYS_BASE_UPLOAD. $xml->uploaddir . "/".$xml->preview_image.$value."' style='border:none; vertical-align:middle' /> ";
				}else{
					$valor=$value;
				}
			}
			break;
		case "menu":
			if($value==NULL || $value==''){
				$valor='';
			}else{
				$arr=array(); $process=new UserProcessing();
				foreach($xml->populate->option as $option){				
					if((string)$xml->populate['from']=="list") break;
					$arr[(string)$option['value']]=(string)$option;
				}
				if((string)$xml->populate['from']=="list"){				
					foreach($xml->populate->option as $op) $arr[(string)$op['value']]=(string)$op;
				}
				if((string)$xml->populate['from']=="sql"){				
					$qqq=mysql_query(Content::parse((string)$xml->populate->sql)) or die(mysql_error());
					while($fff=mysql_fetch_array($qqq)) $arr[(string)$fff[0]]=(string)$fff[1];
				}
				if($xml->multiple=="true"){
					preg_match_all('/"opt_(.*?)"/',$value,$matches);
					$valor='';
					for($i=0;$i<count($matches[1]);$i++){
						$valor.=$arr[$matches[1][$i]]."<br />";
					}
				}else{
					$valor=$arr[(string)$value];
				}
			}
			break;
		case "dummy":
			if(isset($xml->datasource)){
				$sql=str_replace("{param}",$param,$xml->datasource->sql);
				$q=@mysql_query(Content::parse($sql));
				if(@mysql_num_rows($q)>0){
					$fet=mysql_fetch_assoc($q);
					$teststr=(string)$xml->text;
					preg_match_all("/{(.*?)}/", $teststr, $arr2);
					for($i=0;$i<count($arr2[0]);$i++){
						$teststr=str_replace($arr2[0][$i],$fet[$arr2[1][$i]],$teststr);
					}
				}else{
					$teststr="<em>No disponible</em>";
				}
				$valor.=$teststr;
			}else{
				$valor=Content::parse((string)$xml->text);
			}
			break;
	}
	return $valor;
}
?>