<?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');

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

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

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

	$func = new functions();

	$dtFeci=$_POST['dtFeci'];

	# QUERYS
	$sArtic = "SELECT * FROM artic WHERE art_emp='$empCod' AND art_bienser='B'";

	function sCierresi($codd) { 
	    global $empCod, $usuNom, $dtFeci;
	    return "SELECT * FROM cierresi WHERE ci_emp='$empCod' AND ci_cod='$codd' AND ci_fec='$dtFeci'";
	}

	function uCierresi($codd, $costop) { 
	    global $empCod, $usuNom, $dtFeci;
	    return "UPDATE cierresi SET ci_cosp='$costop',ci_ulcam='$usuNom' WHERE ci_emp='$empCod' AND ci_cod='$codd' AND ci_fec='$dtFeci'";
	}

	function iCierresi($codd, $costop) { 
	    global $empCod, $usuNom, $dtFeci;
	    return "INSERT INTO cierresi (ci_emp,ci_cod,ci_fec,ci_cosp,ci_ulcam) VALUES('$empCod','$codd','$dtFeci','$costop','$usuNom')";
	}

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$select["artic"] = $db->query($sArtic);

	while ($rec = $db->fetchAssoc($select["artic"])) {
	    $codd=$rec["art_cod"];
	    $costop=$rec["art_cosp"];
	   
	    $select["cierresi"] = $db->query(sCierresi($codd));
	    $fetchAssoc["cierresi"] = $db->fetchAssoc($select["cierresi"]);
    	if ($db->numRows($select["cierresi"]) > 0) {
			$resp = $db->uEx(uCierresi($codd,$costop));
	    } else {
			$resp = $db->iEx(iCierresi($codd,$costop));
	    }
	}

	$db->iEx($func->iBitacora(utf8_decode("Se Cerro costo al: $dtFeci Usuario: ").$usuNom, $bitMod, $bitForm));

	$db->close();

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

	return json_encode($resp);
}
?>