<?php
set_time_limit(300);
include_once('conex.php');

$tabla = "";
if (isset($_REQUEST['t']))
	$tabla = $_REQUEST['t'];

$anoy = date("Y");
if (isset($_REQUEST['a']))
	$anoy = $_REQUEST['a'];

if (empty($anoy))
	$anoy = date("Y");
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
function lista_ven01(){
	$SqlTmp = "SELECT extract(year from A.fec_docu) as ano, A.cdg_tdoc, B.des_item, sum(A.val_ftot) as val_ftot 
		FROM m_doccli AS A
		INNER JOIN d_tablas AS B 
		ON A.cdg_tdoc = B.num_item 
		AND B.cdg_tab = 'TDC'
		WHERE extract(year from A.fec_docu) = 2018 
		AND A.swt_est <> 'A'
		GROUP BY 1,2,3
		ORDER BY A.cdg_tdoc ";
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo (reportes01): ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;
		echo "DELETE FROM reportes01" . "\n";
		$XvCabecera = "INSERT INTO reportes01 (ano,cdg_tdoc,des_item,val_ftot) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "(".$data['ano'] . ",'" .
				rtrim($data['cdg_tdoc']) . "','" .
				rtrim($data['des_item']) . "'," .
				$data['val_ftot'] .")";
				
			if ($XvGrupoF >= 499 || $XvConteo>=$XvCantFila){
				$XvCadena = $XvCadena . "\n";
				$XvGrupoF = -1;
				echo $XvCadena;
				if (($XvConteo+2) < $XvCantFila)
					echo $XvCabecera;
			}else{
				$XvCadena = $XvCadena . ",";
				echo $XvCadena;
			}
			$XvConteo++;
			$XvGrupoF++;
		}
	}	
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='ventas01'){
	lista_ven01();
}
pg_close($con);
?>