<?php
include('../../../php/sessionStart.php');
include('../../../php/db/dbExec.php');
include_once('../../../php/functions.php');
include_once('../../../php/maxExecTime.php');

echo buscar();

function buscar() {
	global $empCod;
	$txtDescb=utf8_decode(TRIM($_POST['txtDescb']));
	$txtCodb=utf8_decode(TRIM($_POST['txtCodb']));
	$txtDesdb=utf8_decode(TRIM($_POST['txtDesdb']));
	$empCod=$_SESSION['empCod'];

	$func = new functions();

	# QUERYS
	$sArtic = "SELECT *, 
			TRIM(art.art_desc) AS art_desc,
			TRIM(art.art_desd)  AS art_desd,
			TRIM(art.art_cod) AS art_cod,
			TRIM(art.art_codf) AS art_codf
			FROM artic art
			WHERE art_emp='$empCod' AND art_desc LIKE '%$txtDescb%' AND art_cod LIKE '%$txtCodb%' AND art_desd LIKE '%$txtDesdb%'";

	function uArtic($codd,$epas1,$epas2,$epas3,$epas4) { 
		global $empCod, $usuNom;
		return "UPDATE artic SET art_epas1=$epas1,art_epas2=$epas2,art_epas3=$epas3,art_epas4=$epas4 WHERE art_emp='$empCod' AND art_cod='$codd'";
	}

	function sExiart($codd) { 
		global $empCod, $usuNom;
		return "SELECT *, SUM(ea_exist) AS ea_sumexist FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' GROUP BY ea_emp,ea_cod,ea_bod";
	}

	# EJECUCION DE QUERYS
	$db = new dbExec();
	$select["artice"] = $db->query($sArtic);
	while ($rec = $db->fetchAssoc($select["artice"])) {
        $ttcod=$rec["art_cod"];
		$epas1=0;
		$epas2=0;
		$epas3=0;
		$epas4=0;		
		$select["exiart"] = $db->query(sExiart($ttcod));
		while ($recexi = $db->fetchAssoc($select["exiart"])) {
			if ($recexi["ea_bod"]=='0010') {
				$epas1=$recexi["ea_sumexist"];
			}
			if ($recexi["ea_bod"]=='0020') {
				$epas2=$recexi["ea_sumexist"];
			}
			if ($recexi["ea_bod"]=='0030') {
				$epas3=$recexi["ea_sumexist"];
			}
			if ($recexi["ea_bod"]=='0040') {
				$epas4=$recexi["ea_sumexist"];
			}
		}
		$db->query(uArtic($ttcod,$epas1,$epas2,$epas3,$epas4));
	}
	$resp["artic"] = $db->sFetchAll($sArtic);
	$db->close();

	$func = new functions();
	return $func->jsonEncodeArray($resp, "artic");
}
?>