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

$bitForm = "inv1050";
$bitMod = "inv";
$empCod = $_SESSION['empCod'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);

switch ($_POST['action']) {
	case 'proceso':
		echo proceso();
		break;
}

function proceso() {
	global $empCod, $usuNom, $bitMod, $bitForm, $dtFeci;

	$func = new functions();

	$selBodega=$_POST['selBodega'];
	$Bodeganom=$_POST['BodegaNom'];
	
	# QUERYS
	$sInvefis = "SELECT *, SUM(ifd.infd_cant) AS infd_sumcant
				 FROM invefis inf LEFT JOIN invefdet ifd ON inf.if_emp=ifd.infd_emp AND inf.if_tipo=ifd.infd_tipo AND inf.if_num=ifd.infd_num
				 WHERE if_emp='$empCod' AND if_bod='$selBodega' AND if_proc!='S' GROUP BY inf.if_fec,ifd.infd_cod";

	$uInvefis = "UPDATE invefis SET if_proc='S' WHERE if_emp='$empCod' AND if_bod='$selBodega' AND if_proc!='S'";

	$uExiart00 = "UPDATE exiart set ea_exist=0 WHERE ea_emp='$empCod'";

	$sBodegas = "SELECT * FROM bodegas WHERE bod_emp='$empCod'";

	$sArtic = "SELECT * FROM artic WHERE art_emp='$empCod'";

	function sArtic($codd) { 
		global $empCod, $usuNom;
		return "SELECT * FROM artic WHERE art_emp='$empCod' AND art_cod='$codd'";
	}
	function sCorrTdoci($tipo) { 
		global $empCod, $usuNom;
		return "SELECT * FROM corrtdoci WHERE ctdi_emp='$empCod' AND ctdi_tipo='$tipo'";
	}
	function iCorrTdoci($tipo,$nuevocorr) { 
		global $empCod, $usuNom;
		return "INSERT INTO corrtdoci(ctdi_emp, ctdi_tipo, ctdi_corr) VALUES ('$empCod','$tipo',$nuevocorr)";
	}
	function uCorrTdoci($tipo,$nuevocorr) { 
		global $empCod, $usuNom, $selTdoci;
		return "UPDATE corrtdoci SET ctdi_corr=$nuevocorr WHERE ctdi_emp='$empCod' and ctdi_tipo='$tipo'";
	} 
	function iDoctose($tipo,$num,$fec,$bod,$obs) { 
		global $empCod, $usuNom;
		return "INSERT INTO doctose(de_emp, de_tipo, de_num, de_fec, de_fecapli, de_bodent, de_tcam, de_serieoc, de_numoc, de_obs, de_total, de_prorsn, de_ulcam) VALUES ('$empCod','$tipo','$num','$fec','$fec','$bod',1,'',0,'$obs', 0,'N','$usuNom')";
	} 
	function iDoce_det($tipo,$num,$fec,$codd, $descd, $cantd, $unimed, $medid, $cosud, $numtot, $exiant, $nuevaexist) { 
		global $empCod, $usuNom;
		return "INSERT INTO doce_det(ded_emp, ded_tipo, ded_num, ded_fec, ded_fecapli, ded_cod, ded_cant, ded_boni, ded_desc, ded_med, ded_unimed, ded_cosu, ded_cost, ded_exesn, ded_exiant, ded_exipos) VALUES('$empCod','$tipo','$num','$fec','$fec','$codd','$cantd',0,'$descd','$unimed','$medid','$cosud','$numtot','N','$exiant','$nuevaexist')";
	}

	function iDoctoss($tipo,$num,$fec,$bod,$obs) { 
		global $empCod, $usuNom;
		return "INSERT INTO doctoss(ds_emp, ds_tipo, ds_num, ds_fec, ds_fecapli, ds_bodsal, ds_tcam, ds_obs, ds_total, ds_ulcam) VALUES ('$empCod','$tipo','$num','$fec','$fec','$bod',1,'$obs', 0,'$usuNom')";
	} 

	function iDocs_det($tipo,$num,$fec,$codd, $descd, $cantd, $unimed, $medid, $cosud, $numtot, $cosmovi, $exiant, $nuevaexist) { 
		global $empCod, $usuNom;
		return "INSERT INTO docs_det(dsd_emp, dsd_tipo, dsd_num, dsd_fec, dsd_fecapli, dsd_cod, dsd_cant, dsd_desc, dsd_med, dsd_unimed, dsd_unit, dsd_monto, dsd_cosu, dsd_exiant, dsd_exipos) VALUES('$empCod','$tipo','$num','$fec','$fec','$codd','$cantd','$descd','$unimed','$medid','$cosud','$numtot', '$cosmovi', '$exiant','$nuevaexist')";
	}


	function iMovii($tipo,$num,$fec,$codd,$bodentra,$bodsale,$cantentra,$cantsale, $cosud, $precio) { 
		global $empCod, $usuNom;
		return "INSERT INTO movii (mov_emp, mov_tipo, mov_num, mov_fec, mov_fecapli, mov_cod, mov_bodent, mov_bodsal, mov_entra, mov_sale, mov_cosu, mov_preu) VALUES ('$empCod','$tipo','$num','$fec','$fec','$codd','$bodentra','$bodsale','$cantentra','$cantsale','$cosud','$precio')";
	}

	function sMoviie0($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_entra) AS mov_sentra
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$bodega' GROUP BY '$empCod','$bodega','$codd'";
	}

	function sMoviis0($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_sale) AS mov_ssale
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$bodega' GROUP BY '$empCod','$bodega','$codd'";
	}

	function sExiart($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}

	function uExiart($codd, $bodega, $nexist) { 
		global $empCod, $usuNom;
		return "UPDATE exiart SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}
	function iExiart($codd, $bodega, $nexist) { 
		global $empCod, $usuNom;
		return "INSERT INTO exiart(ea_emp,ea_cod,ea_bod,ea_exist) VALUES('$empCod','$codd','$bodega','$nexist')";
	}

	function sMoviiei($codd, $bodega, $fecha) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_entra) AS mov_sentra
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$bodega' AND mov_fec>'$fecha' GROUP BY '$empCod','$bodega','$codd'";
	}

	function sMoviisi($codd, $bodega, $fecha) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_sale) AS mov_ssale
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$bodega' AND mov_fec>'$fecha'  GROUP BY '$empCod','$bodega','$codd'";
	}


	# EJECUCION DE QUERYS 
	$db = new dbExec();
	// Primero se hace revision de todas las existencias
	$resp = $db->query($uExiart00);
	$select["artic"] = $db->query($sArtic);
	while ($rec = $db->fetchAssoc($select["artic"])) {
	    $codd=$rec["art_cod"];
	    $select["bodegas"] = $db->query($sBodegas);
		while ($recbod = $db->fetchAssoc($select["bodegas"])) {
			$bodega=$recbod["bod_cod"];

	        $select["movii"] = $db->query(sMoviie0($codd,$bodega));
	        $recme0 = $db->fetchAssoc($select['movii']);
	        $sEntramov=$recme0["mov_sentra"];

	        $select["movii"] = $db->query(sMoviis0($codd,$bodega));
	        $recms0 = $db->fetchAssoc($select['movii']);
	        $sSalemov=$recms0["mov_ssale"];

	        $nexist=($sEntramov-$sSalemov);

		    $select["exiart"] = $db->query(sExiart($codd,$bodega));
		    $fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
	    	if ($db->numRows($select["exiart"]) > 0) {
				$resp = $db->uEx(uExiart($codd,$bodega,$nexist));
		    } else {
		    	if ($nexist!=0) {
				  $resp = $db->iEx(iExiart($codd,$bodega,$nexist));
				}
		    }
		}
	}
	// Para preparar Correlativos
	$tipoe="0030";
	$tipos="0130";
	$select["corrtdocie"] = $db->query(sCorrTdoci($tipoe));
	if ($db->numRows($select["corrtdocie"])>0) {
		$nume = ($db->fetchAssoc($select["corrtdocie"])["ctdi_corr"]);
	} else {
		$nume = 1;
	}
	$nuevocorre=$nume+1;
	$select["corrtdocis"] = $db->query(sCorrTdoci($tipos));
	if ($db->numRows($select["corrtdocis"])>0) {
		$nums = ($db->fetchAssoc($select["corrtdocis"])["ctdi_corr"]);
	} else {
		$nums = 1;
	}
	$nuevocorrs=$nums+1;
	$obs="Ajuste por Toma fisica";
	// Ahora se procesan las existencias
	$lineae=1;
	$lineas=1;
	$pasoe="N";
	$pasos="N";
	$select["invefis"] = $db->query($sInvefis);
	while ($rec = $db->fetchAssoc($select["invefis"])) {
	    $codd=$rec["infd_cod"];
	    $fecd=$rec["if_fec"];
	    $bodd=$rec["if_bod"];
	    $sumcant=$rec["infd_sumcant"];
	    $descd=$rec["infd_desc"];
	    $medd=$rec["infd_med"];
	    $unimedd=$rec["infd_unimed"];

	    $select["artic"] = $db->query(sArtic($codd));
	    $artic01=$db->fetchAssoc($select["artic"]);
	    $cosp = $artic01["art_cosp"];
	    $pre1 = $artic01["art_pre1"];

        $select["movii"] = $db->query(sMoviiei($codd,$bodd,$fecd));
        $recmei = $db->fetchAssoc($select['movii']);
        $sEntramovi=$recmei["mov_sentra"];

        $select["movii"] = $db->query(sMoviisi($codd,$bodd,$fecd));
        $recmsi = $db->fetchAssoc($select['movii']);
        $sSalemovi=$recmsi["mov_ssale"];

	    $select["exiart"] = $db->query(sExiart($codd,$bodd));
	    $exist = ($db->fetchAssoc($select["exiart"])["ea_exist"]);
	    $nexist=$exist;
	    $existant = ($exist+$sSalemovi)-$sEntramovi;

	    $ajustee=0;
	    $ajustes=0;
	    if ($existant>$sumcant) {
	    	$ajustes=$existant-$sumcant;
	    	$nexist=$exist-$ajustes;
	    	$bodentra="";
	    	$bodsale=$bodd;
	    	$cantentra=0;
	    	$cantsale=$ajustes;
	    	$costot=($cantsale*$cosp);

			$db->query(iDoctoss($tipos,$nums,$fecd,$bodd,$obs));
			$db->query(iDocs_det($tipos,$nums,$fecd,$codd, $descd, $cantsale, $medd, $unimedd, $cosp, $costot, $cosp, $exist, $nexist));
			$db->query(iMovii($tipos,$nums,$fecd,$codd,$bodentra,$bodsale,$cantentra,$cantsale, $cosp, $pre1));

			// Aqui cambia la existencia si es ajuste de salida
			$resp = $db->uEx(uExiart($codd,$bodd,$nexist));
			$pasos="S";
		}
	    if ($existant<$sumcant) {
	    	$ajustee=$sumcant-$existant;
	    	$nexist=$exist+$ajustee;
	    	$bodentra=$bodd;
	    	$bodsale="";
	    	$cantentra=$ajustee;
	    	$cantsale=0;
	    	$costot=($cantentra*$cosp);

			$db->query(iDoctose($tipoe,$nume,$fecd,$bodd,$obs));
			$db->query(iDoce_det($tipoe,$nume,$fecd,$codd, $descd, $cantentra, $medd, $unimedd, $cosp, $costot, $exist, $nexist));
			$db->query(iMovii($tipoe,$nume,$fecd,$codd,$bodentra,$bodsale,$cantentra,$cantsale, $cosp, $pre1));

			// Aqui cambia la existencia si es ajuste de entrada
			$resp = $db->uEx(uExiart($codd,$bodd,$nexist));
			$pasoe="S";
		}
	}
	// Cambia los correlativos
    if ($pasoe=='S') {
		if ($db->numRows($select["corrtdocie"])>0) {
			$db->query(uCorrTdoci($tipoe,$nuevocorre));
		} else {
			$db->query(iCorrTdoci($tipoe,$nuevocorre));
		}
	}
    if ($pasos=='S') {
		if ($db->numRows($select["corrtdocis"])>0) {
			$db->query(uCorrTdoci($tipos,$nuevocorrs));
		} else {
			$db->query(iCorrTdoci($tipos,$nuevocorrs));
		}
	}
	// Marca de procesadas las tomas fisicas
	$db->query($uInvefis);

	$db->close();

	//$func->unlinkEmpCod($empCod, $txtCod, '../imgArticulos');

	return json_encode($resp);
}
?>