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

$accion=$_REQUEST['action'];
$valor=$_REQUEST['valor'];
$control=$_REQUEST['control'];
$idioma=isset($_REQUEST['idioma']) ? $_REQUEST['idioma'] : NULL;

$resId=$_REQUEST['resId'];
$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);
$obj=NULL;		
$result="";		

function init($valor, $control){
	global $master; global $detail; global $idioma;
	$data=array(); $ids=array();
	
	$xml=$detail->xpath("//control[@name='{$control}']");
	$qinit=$detail->xpath("//control[@name='{$control}']/queries/query[@for='init']"); $sql1=(string)$qinit[0];
	$qsibs=$detail->xpath("//control[@name='{$control}']/queries/query[@for='getNodes']"); $sql2=(string)$qsibs[0];
	$sql1=str_replace("{@@@}",$valor,$sql1);
	$q=mysql_query($sql1) or die(mysql_error());
	$obj->result="OK";
	
	if(mysql_num_rows($q)>0){
		while($f=mysql_fetch_array($q)){
			$ids[]=$f[0];
			$sql3=str_replace("{@@@}",$f[1],$sql2);
			$q3=mysql_query($sql3) or die(mysql_error());
			$temp=array();
			while($f3=mysql_fetch_array($q3)){
				$temp[]=array("value"=>$f3[0], "label"=>$f3[1]);
			}
			$data[]=$temp;
		}
	}
	if($xml[0]->nodes[0]->count() > count($ids)){
		$ids[]="-1";	
		$sql4=str_replace("{@@@}",$valor,$sql2);
		$q4=mysql_query($sql4) or die(mysql_error());
		$temp=array();
		while($f4=mysql_fetch_array($q4)){
			$temp[]=array("value"=>$f4[0], "label"=>$f4[1]);
		}
		$data[]=$temp;
	}else if($xml[0]->nodes[0]->count() != count($ids)){
		$obj->result="KO";
	}
	$obj->breadcrumb=$ids;
	$obj->data=$data;
	return $obj;
}
switch($accion){
	case "init":
		$result=json_encode(init($valor, $control));
		break;
}
echo $result;
?>