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

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

$linea = '';
if (isset($_REQUEST['l']))
	$linea = $_REQUEST['l'];

$codart = '';
if (isset($_REQUEST['c']))
	$codart = $_REQUEST['c'];

$codven = '';
if (isset($_REQUEST['v']))
	$codven = $_REQUEST['v'];

$codcli = '';
if (isset($_REQUEST['cli']))
	$codcli = $_REQUEST['cli'];

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

if (ini_get('default_charset')=='UTF-8')
	ini_set('default_charset', 'Windows-1251');

/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='valconex'){
	echo "GCTS";
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
function lista_alm(){
	$SqlTmp = "SELECT NUM_ITEM, DES_ITEM, SWT_ITEM
		FROM d_tablas
		WHERE CDG_TAB = 'ARE' 
		AND swt_item = 1 
		ORDER BY NUM_ITEM ";
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo (Almacen): ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM almacen" . "\n";
		$XvCabecera = "INSERT INTO almacen (cod_alm, des_alm, activo, cod_loc) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['num_item']) . "','" .
				rtrim($data['des_item']) . "'," .
				$data['swt_item'] .", '')";
				
			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++;
		}
	}	
}
/*-------------------------------------------------------*/
function lista_resp(){
	$SqlTmp = "SELECT cdg_resp, des_resp, swt_resp
		FROM m_respon
		ORDER BY des_resp ";
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo (m_respon): ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM m_respon" . "\n";
		$XvCabecera = "INSERT INTO m_respon (cod_res, des_res, activo) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_resp']) . "','" .
				rtrim($data['des_resp']) . "'," .
				$data['swt_resp'] .")";
				
			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=='listprecios'){
	lista_pre();
}
/*-------------------------------------------------------*/
if ($tabla=='resp'){
	lista_resp();
}
/*-------------------------------------------------------*/
if ($tabla=='alm'){
	lista_alm();
}
/*-------------------------------------------------------*/
if ($tabla=='stock'){
	lista_stock();
}
/*-------------------------------------------------------*/
if ($tabla=='stockart'){
	lista_paremp();
	lista_mon();
	lista_user();
	lista_ven();
	lista_fpag();
	lista_alm();
	lista_resp();
	lista_lin();
	lista_art();
	lista_pre();
	lista_permiUser();
	lista_permiUser2();
	lista_desc();
	if ($img == 'S'){
		lista_fotart();
	}	
	lista_stock();
}
//***********************************************************************************
function lista_stock(){
	$SqlTmp = "SELECT art.CDG_PROD, ingeso.ALMA, ingeso.DES_ITEM, SUM(ingeso.Cantidad) AS Cantidad
		FROM M_PRODUC AS art 
		LEFT OUTER JOIN
                          (SELECT A.CDG_AREA AS ALMA, ALMA.DES_ITEM, B.CDG_PROD, SUM(B.CAN_DGUI) AS Cantidad
                            FROM M_GUIA AS A 
							INNER JOIN D_GUIA 	AS B ON A.CDG_TPG = B.CDG_TPG AND A.NUM_GUIA = B.NUM_GUIA 
							INNER JOIN D_TABLAS AS ALMA ON A.CDG_AREA = ALMA.NUM_ITEM AND ALMA.CDG_TAB = 'ARE'
                            WHERE (A.swt_est <>'A') 
							AND (A.CDG_TPG = '001') 
							AND (B.cdg_tpg = '001') 
							AND (ALMA.swt_item = 1) 
                            GROUP BY A.CDG_AREA, B.CDG_PROD, ALMA.DES_ITEM
                            UNION ALL
                            SELECT A.ORI_AREA AS ALMA, ALMA.DES_ITEM, B.CDG_PROD, SUM(B.CAN_DGUI * - 1) AS Cantidad
                            FROM M_GUIA AS A 
							INNER JOIN D_GUIA AS B ON A.CDG_TPG = B.CDG_TPG AND A.NUM_GUIA = B.NUM_GUIA 
							INNER JOIN D_TABLAS AS ALMA ON A.ORI_AREA = ALMA.NUM_ITEM AND ALMA.CDG_TAB = 'ARE'
                            WHERE (A.swt_est <>'A') 
							AND (A.CDG_TPG <> '001') 
							AND (B.cdg_tpg <> '001') 
							AND (ALMA.swt_item = 1) 
                            GROUP BY A.ORI_AREA, B.CDG_PROD, ALMA.DES_ITEM) AS ingeso ON art.CDG_PROD = ingeso.CDG_PROD
		WHERE (art.SWT_PROD = 1) 
		AND (art.SWT_VTA = 1) 
		AND (NOT (ingeso.ALMA IS NULL))
		GROUP BY art.CDG_PROD, ingeso.ALMA, ingeso.DES_ITEM
		HAVING      (SUM(ingeso.Cantidad) <> 0)
		ORDER BY art.CDG_PROD";

	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM stock_art" . "\n";
		$XvCabecera = "INSERT INTO stock_art (co_art, co_alma, des_alma, stock_act) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('". rtrim(str_replace("'","",$data['cdg_prod'])) . "','" .
				rtrim(str_replace("'","",$data['alma'])) ."','".
				rtrim(str_replace("'","",$data['des_item'])) ."',".
				$data['cantidad'] . ")";		

			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++;
		}
	}	
}
//***********************************************************************************
// dct_pprd = Colocar el descuento de la lista
// dct_fic = Colocar descuento manual

function lista_desc(){
	$SqlTmp = "SELECT NUM_ITEM, DES_ITEM, SWT_ITEM, val_item
		FROM d_tablas
		WHERE CDG_TAB = 'FIC' 
		ORDER BY NUM_ITEM ";
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo (Ficha de Descuentos): ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM descuentos" . "\n";
		$XvCabecera = "INSERT INTO descuentos (cod_desc,des_desc,activo,val_desc) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['num_item']) . "','" .
				rtrim($data['des_item']) . "'," .
				$data['swt_item'] .", " . 
				$data['val_item'] .")";
				
			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++;
		}
	}
}
//***********************************************************************************
function lista_permiUser2(){
	$SqlTmp = "SELECT cdg_usr, cdg_opc, num_item, num_cor, prm_cor 
		FROM t_usuari 
		WHERE cdg_opc = 'CLI' 
		AND num_item = '001'
		AND num_cor = '001'
		ORDER BY cdg_usr";

	// prm_cor = 0 (Sin Permiso) -  1 (Consulta) - 2 (Actualizar)

	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo (t_usuari): ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM t_usuari" . "\n";
		$XvCabecera = "INSERT INTO t_usuari (cdg_usr, cdg_opc, prm_cor) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_usr']) . "'," . 
				"'" . rtrim($data['cdg_opc']) . "'," .
				$data['prm_cor'] .")";
				
			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++;
		}
	}		
}
//***********************************************************************************
function lista_permiUser(){
	$SqlTmp = "SELECT x_usuari.cdg_usr, x_usuari.num_cor, x_usuari.swt_cor
		FROM x_usuari 
		INNER JOIN m_usuari ON x_usuari.cdg_usr = m_usuari.cdg_usr
		WHERE x_usuari.swt_cor = 1 
		AND m_usuari.swt_usr = 1 
		ORDER BY x_usuari.cdg_usr ";
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo (x_usuari): ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM x_usuari" . "\n";
		$XvCabecera = "INSERT INTO x_usuari (cdg_usr,num_cor,swt_cor) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_usr']) . "'," . 
				"'" . rtrim($data['num_cor']) . "'," .
				$data['swt_cor'] .")";
				
			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++;
		}
	}
}
//***********************************************************************************
function lista_ven(){
	$SqlTmp = "SELECT cdg_vend, des_vend, swt_vend, swt_usr, cdg_usr 
		FROM m_vended
		ORDER BY cdg_vend ";
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM vendedor" . "\n";
		$XvCabecera = "INSERT INTO vendedor (cod_ven,des_ven,activo,swt_usr,cod_usr) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$DesVend = limpiarcadena($data['des_vend']);
			$XvCadena = "('".rtrim($data['cdg_vend']) . "','" .
				$DesVend . "'," .
				$data['swt_vend'] ."," .
				$data['swt_usr'] .",'" .
				rtrim(ltrim($data['cdg_usr'])) ."')";
			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++;
		}
	}
}
//***********************************************************************************
function lista_emp(){
	$SqlTmp = "SELECT CDG_EMP, DES_EMP, 
		CASE WHEN ele_emp <> '' THEN ele_emp ELSE PAS_EMP END AS pas_emp ,swt_emp
		FROM m_emple
		ORDER BY CDG_EMP ";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM m_emple" . "\n";
		$XvCabecera = "INSERT INTO m_emple (cdg_emp, des_emp, pas_emp, swt_emp) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_emp']) . "','" .
				rtrim($data['des_emp']) . "','" .
				rtrim($data['pas_emp']) ."'," .
				$data['swt_emp'] .")";
				
			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++;
		}
	}
}
//***********************************************************************************
function lista_act(){
	$SqlTmp = "SELECT NUM_ITEM, DES_ITEM, SWT_ITEM
		FROM d_tablas
		WHERE CDG_TAB = 'APR' 
		AND SWT_ITEM = 1 
		ORDER BY NUM_ITEM ";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM m_actividad" . "\n";
		$XvCabecera = "INSERT INTO m_actividad (cdg_act, des_act, swt_act) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['num_item']) . "','" .
				rtrim($data['des_item']) . "'," .
				$data['swt_item'] .")";
				
			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++;
		}
	}
}
//***********************************************************************************
function lista_partidas(){
	$SqlTmp = "SELECT p.cdg_part, l.des_lin, p.cdg_cct
		FROM t_lincgt l 
		INNER JOIN d_presup p ON p.cdg_part = l.cdg_lin
		WHERE l.swt_lin=1 
		AND l.tar_lin=1 
		ORDER BY l.des_lin";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM m_partida" . "\n";
		$XvCabecera = "INSERT INTO m_partida (cdg_part, des_part, cdg_pres) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_part']) . "','" .
				rtrim($data['des_lin']) . "','" .
				$data['cdg_cct'] ."')";
				
			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++;
		}
	}
}	
//***********************************************************************************
function lista_ccosto(){
	$SqlTmp = "SELECT CDG_CCT, DES_CCT, CDG_TCCT, SWT_CCT
		FROM m_ccosto
		ORDER BY CDG_CCT ";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM m_ccosto" . "\n";
		$XvCabecera = "INSERT INTO m_ccosto (CDG_CCT, DES_CCT, CDG_TCCT, SWT_CCT) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_cct']) . "','" .
				rtrim($data['des_cct']) . "','" .
				rtrim($data['cdg_tcct']) . "'," .
				$data['swt_cct'] .")";
				
			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++;
		}
	}
}
//***********************************************************************************
function lista_user(){
	$SqlTmp = "do $$
		BEGIN
		  if NOT EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'm_usuari' AND column_name='psw_web') then
			ALTER TABLE m_usuari ADD COLUMN psw_web VARCHAR;
			UPDATE m_usuari SET psw_web = 'bcac154ae92f0812fdb305187c16bb4b' WHERE cdg_usr = 'SUPERVISOR';
		  end if;
		end$$";
	$XqTabla = pg_query( $SqlTmp)  or die('La consulta fallo: ' . pg_last_error());
	//-------------------------------------------------------------------------------
	$XvConteo = 1;
	$XvGrupoF = 0;		
	$SqlTmp = "SELECT cdg_usr, des_usr, suc_usr, ema_usr, psw_web, swt_usr, vnd_usr FROM m_usuari ";
	$XqTabla = pg_query( $SqlTmp)  or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		echo "DELETE FROM usuario" . "\n";
		$XvCabecera = "INSERT INTO usuario (usuario,nombre,co_sucu,email,clave,activo,codasociado) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('".rtrim($data['cdg_usr']) . "','" .
				rtrim($data['des_usr']) . "','" .
				rtrim($data['suc_usr']) . "','" .
				rtrim($data['ema_usr']) . "','" .
				rtrim($data['psw_web']) . "', " .
				$data['swt_usr'] . ",'" .
				rtrim($data['vnd_usr']) . "')";

			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++;
		}
	}
}
//***********************************************************************************
function lista_paremp(){
	$SqlTmp = "SELECT clc_tot, por_tigv, mon_ped, can_dec, pre_dec FROM t_params ";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "UPDATE par_emp SET ".
				"clc_tot=" . $data['clc_tot'] .
				",por_tigv=" . $data['por_tigv'] .
				",can_dec=" . $data['can_dec'] .
				",pre_dec=" . $data['pre_dec'] .
				",mon_ped='".$data['mon_ped'] ."'" . "\n";
			echo $XvCadena;
		}
	}
}
//***********************************************************************************
function lista_mon(){
	$SqlTmp = "SELECT A.NUM_ITEM, A.DES_ITEM, A.abr_item, A.SWT_ITEM, A.tip_item 
		FROM D_TABLAS AS A
		WHERE (A.CDG_TAB = 'MON') 
		AND A.SWT_ITEM = 1 
		ORDER BY A.DES_ITEM";

	$XvConteo = 1;
	$XvGrupoF = 0;		
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		echo "DELETE FROM moneda"."\n";
		$XvCabecera = "INSERT INTO moneda (cod_moneda,des_moneda,abr_moneda,activo,tip_item) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$clides = str_replace(';','',str_replace('"','',str_replace("'","",$data['des_item'])));
			$clides = str_replace('\R', ' ', $clides);
			$clides = str_replace('\R\N', ' ', $clides);
			$clides = str_replace('\N', ' ', $clides);
			$clides = str_replace('\r', ' ', $clides);
			$clides = str_replace('\r\n', ' ', $clides);
			$clides = str_replace('\n', ' ', $clides);
			$clides = str_replace(chr(13), ' ', $clides);
			$clides = str_replace(chr(10), ' ', $clides);
				
			$XvCadena = "('".str_replace("'","",rtrim($data['num_item'])) . "','" .
				rtrim($clides) . "','" .
				rtrim($data['abr_item']) . "'," .
				$data['swt_item'] . "," .
				"'" . ltrim(rtrim($data['tip_item'])) . "')";

			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++;
		}
	}
}
//***********************************************************************************
function lista_art(){
	global $linea, $codart;
	$SqlTmp = "SELECT A.cdg_prod, A.des_prod, A.cdg_linp, A.swt_prod, A.swt_igv, A.cdg_prv, 
			F.fot_prod, U.abr_item AS unidad
			FROM M_PRODUC AS A 
			LEFT JOIN h_produc AS F ON A.cdg_prod = F.cdg_prod 
			LEFT JOIN d_tablas AS U ON A.cdg_umed = U.num_item AND U.cdg_tab = 'UNM'
			WHERE A.SWT_VTA = 1 ";

	if ($linea != '')
		$SqlTmp = $SqlTmp . " AND A.cdg_linp = '$linea' ";
		
	if ($codart != '')
		$SqlTmp = $SqlTmp . " AND A.cdg_prod = '$codart' ";
		
	$SqlTmp = $SqlTmp . " ORDER BY A.cdg_prod ";

	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;

		echo "DELETE FROM art" . "\n";
		$XvCabecera = "INSERT INTO art (co_art,art_des,co_lin,activo,stock_act,stock_com,swt_igv,ref,uni_venta) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvDesArt = ltrim(rtrim(str_replace("'","",$data['des_prod'])));
			$XvCadena = "('".rtrim($data['cdg_prod']) . "',".
				"'" . $XvDesArt . "',".
				"'" . rtrim($data['cdg_linp']) ."',".
				"" . $data['swt_prod'] . ",".
				"10000,0,".
				"" . $data['swt_igv'] . ",".
				"'" . rtrim($data['cdg_prv']) . "',".
				"'" . rtrim($data['unidad']) . "')";

			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++;
		}
	}
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
function lista_fotart(){
	global $linea, $codart;
	
	include 'defvar.php';
	
	$SqlTmp = "SELECT A.cdg_prod, F.fot_prod 
			FROM M_PRODUC AS A 
			LEFT JOIN h_produc AS F ON A.cdg_prod = F.cdg_prod 
			WHERE A.SWT_VTA = 1 
			AND F.fot_prod <> '' ";

	if ($linea != '')
		$SqlTmp = $SqlTmp . " AND A.cdg_linp = '$linea' ";
		
	if ($codart != '')
		$SqlTmp = $SqlTmp . " AND A.cdg_prod = '$codart' ";
		
	$SqlTmp = $SqlTmp . " ORDER BY A.cdg_prod ";

	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		echo "DELETE FROM art_foto" . "\n";
		while ($data = pg_fetch_array($XqTabla)){
			$imdata = "";
			$FotoBase = "";
			$FotoBaseFin = "";
			if (!is_null($data['fot_prod'])){
				$FotoBase = rtrim(ltrim($data['fot_prod']));
				if (!empty($FotoBase)){
					$FotoBase = str_replace(chr(92), "/", $FotoBase);
					$FotoBase = str_replace("//", "/", $FotoBase);
					if (substr($FotoBase, 1, 1)==":"){
						$FotoBaseFin = $ip_server . substr($FotoBase, 2);
					}else{
						$FotoBaseFin = $ip_server . $FotoBase;
					}
				}
				
				if (!empty($FotoBaseFin)){
					if (file_exists($FotoBaseFin)) {
						$img_origen = imagecreatefromjpeg($FotoBaseFin);
						$ancho_origen = imagesx($img_origen);
						$alto_origen = imagesy($img_origen);
						$ancho_limite=800;
						$ancho_new = 0;
						$alto_new = 0;
						$opcImg = 0;
						if ($ancho_origen>$ancho_limite){
							$ancho_new = $ancho_limite;
							$alto_new = ($ancho_limite * $alto_origen)/$ancho_origen;
							$opcImg = 1;
						}
						if ($ancho_origen>$alto_origen){
							$alto_new = $ancho_limite;
							$ancho_new = ($ancho_limite * $ancho_origen)/$alto_origen;
							$opcImg = 1;
						}
						if ($opcImg == 1){
							$img_destino = imagecreatetruecolor($ancho_new, $alto_new);
							imagecopyresized($img_destino, $img_origen, 0,0,0,0, $ancho_new, $alto_new, $ancho_origen, $alto_origen);
							imagejpeg($img_destino, $FotoBaseFin);
						}
						$im = file_get_contents($FotoBaseFin);
						$imdata = ltrim(rtrim(base64_encode($im)));
					}
				}
			}
			
			if (empty($codart) && !empty($imdata)){
				$XvCadena = "INSERT INTO art_foto (co_art,foto) VALUES('". ltrim(rtrim($data['cdg_prod'])) . "','" . $imdata . "')" . "\n";
				echo $XvCadena;
			}
		}
	}
}
//***********************************************************************************
//***********************************************************************************
function lista_fpag(){
	$SqlTmp = "SELECT A.NUM_ITEM, A.DES_ITEM, A.cam_item, A.SWT_ITEM 
		FROM D_TABLAS AS A
		WHERE (A.CDG_TAB = 'TDC') 
		AND A.SWT_ITEM = 1 
		GROUP BY A.NUM_ITEM, A.DES_ITEM, A.cam_item, A.SWT_ITEM 
		ORDER BY A.DES_ITEM";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM tipo_doc" . "\n";
		$XvCabecera = "INSERT INTO tipo_doc (cod_tipo, des_tipo, abr_tipo, activo) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$clides = str_replace(';','',str_replace('"','',str_replace("'","",$data['des_item'])));
			$clides = str_replace('\R', ' ', $clides);
			$clides = str_replace('\R\N', ' ', $clides);
			$clides = str_replace('\N', ' ', $clides);
			$clides = str_replace('\r', ' ', $clides);
			$clides = str_replace('\r\n', ' ', $clides);
			$clides = str_replace('\n', ' ', $clides);
			$clides = str_replace(chr(13), ' ', $clides);
			$clides = str_replace(chr(10), ' ', $clides);
				
			$XvCadena = "('".str_replace("'","",rtrim($data['num_item'])) . "','" .
				rtrim($clides) . "','" .
				rtrim($data['cam_item']) . "'," .
				$data['swt_item'] . ")";

			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++;
		}
	}
	//***********************************************************
	$SqlTmp = "SELECT D_TABLAS.NUM_ITEM, D_TABLAS.DES_ITEM, D_TABLAS.abr_item, D_TABLAS.SWT_ITEM, D_TABLAS.val_ITEM 
		FROM D_TABLAS 
		WHERE (D_TABLAS.CDG_TAB = 'CPG') 
		AND D_TABLAS.SWT_ITEM = 1 
		GROUP BY D_TABLAS.NUM_ITEM, D_TABLAS.DES_ITEM, D_TABLAS.abr_item, D_TABLAS.SWT_ITEM, D_TABLAS.val_ITEM 
		ORDER BY D_TABLAS.DES_ITEM";
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM forma_pago" . "\n";
		$XvCabecera = "INSERT INTO forma_pago (cod_fpa, des_fpa, abr_fpa, activo, dias) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$clides = str_replace(';','',str_replace('"','',str_replace("'","",$data['des_item'])));
			$clides = str_replace('\R', ' ', $clides);
			$clides = str_replace('\R\N', ' ', $clides);
			$clides = str_replace('\N', ' ', $clides);
			$clides = str_replace('\r', ' ', $clides);
			$clides = str_replace('\r\n', ' ', $clides);
			$clides = str_replace('\n', ' ', $clides);
			$clides = str_replace(chr(13), ' ', $clides);
			$clides = str_replace(chr(10), ' ', $clides);
				
			$XvCadena = "('".str_replace("'","",rtrim($data['num_item'])) . "','" .
				rtrim($clides) . "','" .
				rtrim($data['abr_item']) . "'," .
				$data['swt_item'] . "," .
				$data['val_item'] .")";
			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++;
		}
	}
}
//***********************************************************************************
function lista_lin(){
	$SqlTmp = "SELECT D_TABLAS.NUM_ITEM, D_TABLAS.DES_ITEM, D_TABLAS.SWT_ITEM
		FROM D_TABLAS 
		WHERE (D_TABLAS.CDG_TAB = 'LIN') 
		AND D_TABLAS.SWT_ITEM = 1 
		GROUP BY D_TABLAS.NUM_ITEM, D_TABLAS.DES_ITEM, D_TABLAS.SWT_ITEM 
		ORDER BY D_TABLAS.DES_ITEM";

	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;

		echo "DELETE FROM lin_art" . "\n";
		$XvCabecera = "INSERT INTO lin_art (co_lin, lin_des, activo)  VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvDesArt = rtrim(str_replace("'","",$data['des_item']));
				
			$XvCadena = "('".rtrim($data['num_item']) . "','" .
				$XvDesArt . "'," .
				$data['swt_item'] . ")";

			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=='art'){
	lista_art();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='ccosto'){
	lista_ccosto();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='activi'){
	lista_act();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='partidas'){
	lista_partidas();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='desc'){
	lista_desc();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='permi'){
	lista_permiUser();
	lista_permiUser2();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='empleados'){
	lista_emp();
	lista_ccosto();
	lista_act();
	lista_partidas();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
function limpiarcadena($pCadena){
	$vCadena = rtrim($pCadena);
	$vCadena = str_replace(';','',str_replace('"','',str_replace("'","",$vCadena)));
	$vCadena = str_replace("<", "", $vCadena);
	$vCadena = str_replace(">", "", $vCadena);
	$vCadena = str_replace('\R', ' ', $vCadena);
	$vCadena = str_replace('\R\N', ' ', $vCadena);
	$vCadena = str_replace('\N', ' ', $vCadena);
	$vCadena = str_replace('\r', ' ', $vCadena);
	$vCadena = str_replace('\r\n', ' ', $vCadena);
	$vCadena = str_replace('\n', ' ', $vCadena);
	$vCadena = str_replace(chr(13), ' ', $vCadena);
	$vCadena = str_replace(chr(10), ' ', $vCadena);

	return $vCadena;
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='clientes'){
	lista_cli();
	lista_cxc();
	lista_desc();
	lista_permiUser();
	lista_permiUser2();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='vendedor'){
	lista_ven();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='paremp'){
	lista_paremp();
	lista_mon();
	lista_user();
	lista_ven();
	lista_fpag();
	lista_desc();
	lista_permiUser();
	lista_permiUser2();
	lista_alm();
	lista_resp();
}	
	
//M_DEFRST
//cdg_tipo, des_tipo, abr_tipo, pos_tipo, swt_tipo   order by pos_tipo
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='usuario'){
	lista_user();
	lista_ven();
	lista_permiUser();
	lista_permiUser2();
	lista_desc();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='lineas'){
	lista_lin();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='moneda'){
	lista_mon();
}
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='tipodoc'){
	lista_fpag();
}	
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
if ($tabla=='fpago'){
}
/*-------------------------------------------------------*/
if ($tabla=='ultpre'){
	lista_ultPre();
}
/*-------------------------------------------------------*/
function lista_ultPre(){
	global $codcli, $codart;

	$SqlTmp = "SELECT m_doccli.ruc_cli, m_doccli.fec_docu,  d_doccli.cdg_prod, d_doccli.pre_dfac, d_doccli.pre_igv
		FROM m_doccli
		INNER JOIN d_doccli ON m_doccli.cdg_tdoc=d_doccli.cdg_tdoc AND m_doccli.num_docu=d_doccli.num_docu
		AND m_doccli.ruc_cli = '$codcli'
		AND d_doccli.cdg_prod = '$codart'
		ORDER BY m_doccli.fec_docu DESC
		LIMIT 2	";

	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
	if ($XvCantFila > 0){
		$data = pg_fetch_array($XqTabla);
		echo $data['pre_igv'];
	}else{
		echo "0";
	}		
}
/*-------------------------------------------------------*/
function lista_pre(){
	$SqlTmp = "SELECT D_TABLAS.NUM_ITEM, D_TABLAS.DES_ITEM, D_TABLAS.abr_item, D_TABLAS.SWT_ITEM 
		FROM D_TABLAS 
		WHERE (D_TABLAS.CDG_TAB = 'PRC') 
		AND D_TABLAS.SWT_ITEM = 1 
		GROUP BY D_TABLAS.NUM_ITEM, D_TABLAS.DES_ITEM, D_TABLAS.abr_item, D_TABLAS.SWT_ITEM 
		ORDER BY D_TABLAS.DES_ITEM";

	$XvConteo = 1;
	$XvGrupoF = 0;		
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		echo "DELETE FROM list_prec" . "\n";
		$XvCabecera = "INSERT INTO list_prec (cod_list,des_list,activo) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$clides = str_replace(';','',str_replace('"','',str_replace("'","",$data['des_item'])));
			$clides = str_replace('\R', ' ', $clides);
			$clides = str_replace('\R\N', ' ', $clides);
			$clides = str_replace('\N', ' ', $clides);
			$clides = str_replace('\r', ' ', $clides);
			$clides = str_replace('\r\n', ' ', $clides);
			$clides = str_replace('\n', ' ', $clides);
			$clides = str_replace(chr(13), ' ', $clides);
			$clides = str_replace(chr(10), ' ', $clides);
				
			$XvCadena = "('".str_replace("'","",rtrim($data['num_item'])) . "','" .
				rtrim($clides) . "'," .
				$data['swt_item'] . ")";

			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++;
		}
	}
	//*********************************************************************************
	$SqlTmp = "SELECT A.cdg_lprc, A.cdg_prod, 
		A.val_sol, A.pre_sol, A.min_sol, A.max_sol,
		A.val_dol, A.pre_dol, A.min_dol, A.max_dol,
		A.cdg_dct1, A.ini_dct1, A.fin_dct1, A.por_dct1,
		A.cdg_dct2, A.ini_dct2, A.fin_dct2, A.por_dct2,
		A.cdg_dct3, A.ini_dct3, A.fin_dct3, A.por_dct3 
		FROM m_precio AS A
		ORDER BY A.cdg_lprc, A.cdg_prod";

	$XvConteo = 1;
	$XvGrupoF = 0;		
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		echo "DELETE FROM art_prec" . "\n";
		$XvCabecera = "INSERT INTO art_prec ".
		"(cod_list,co_art,val_sol,pre_sol,min_sol,max_sol,val_dol,pre_dol,min_dol,max_dol,".
		"cdg_dct1, ini_dct1, fin_dct1, por_dct1,".
		"cdg_dct2, ini_dct2, fin_dct2, por_dct2,".
		"cdg_dct3, ini_dct3, fin_dct3, por_dct3) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('" . rtrim($data['cdg_lprc']) . "','" .
				rtrim($data['cdg_prod']) . "'," .
				$data['val_sol'] . "," .
				$data['pre_sol'] . "," .
				$data['min_sol'] . "," .
				$data['max_sol'] . "," .
				$data['val_dol'] . "," .
				$data['pre_dol'] . "," .
				$data['min_dol'] . "," .
				$data['max_dol'] . "," .
				"'".ltrim(rtrim($data['cdg_dct1']))."'," .
				$data['ini_dct1'] . "," .
				$data['fin_dct1'] . "," .
				$data['por_dct1'] . "," .
				"'".ltrim(rtrim($data['cdg_dct2']))."'," .
				$data['ini_dct2'] . "," .
				$data['fin_dct2'] . "," .
				$data['por_dct2'] . "," .
				"'".ltrim(rtrim($data['cdg_dct3']))."'," .
				$data['ini_dct3'] . "," .
				$data['fin_dct3'] . "," .
				$data['por_dct3'] . ")";

			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++;
		}
	}
}	
/*-------------------------------------------------------*/
/*-------------------------------------------------------*/
function lista_cli(){
	global $codven;
	
	$SqlTmp = "SELECT A.ruc_cli, A.des_cli, A.cdg_alt, A.ema_cli, A.crd_sol, A.cdg_tcli, 
		A.swt_cli, A.cdg_vend, A.cdg_lprc, A.tel_cli, A.dir_cli, A.rep_cli, A.swt_susp 
		FROM m_client AS A 
		WHERE A.swt_cli = 1 ";
			
	if ($codven != ''){
		$SqlTmp = $SqlTmp . " AND A.cdg_vend = '$codven' ";
	}
		
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvGrupoF = 0;		
		echo "DELETE FROM clientes" . "\n";
		$XvCabecera = "INSERT INTO clientes (co_cli,cli_des,rif,email,tipo,co_ven,mont_cre,activo,cdg_lprc,tel_cli,dir_cli,rep_cli,swt_susp) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$clides = limpiarcadena($data['des_cli']);
			$dircli = limpiarcadena($data['dir_cli']);
			if ( empty( $data['swt_susp'] ) )
				$SwtSusp = 0;
			else
				$SwtSusp = $data['swt_susp'];
			
			$emacli = rtrim(str_replace("'","",$data['ema_cli']));
			$emacli = str_replace("<", "", $emacli);
			$emacli = str_replace(">", "", $emacli);
			
			if ($data['crd_sol'] == null)
				$crdSol = 0.00;
			else
				$crdSol = $data['crd_sol'];
			
			$XvCadena = "('".str_replace("'","",rtrim($data['ruc_cli'])) . "','" .
				ltrim(rtrim($clides)) . "','" .
				rtrim(str_replace("'","",$data['cdg_alt'])) ."','".
				$emacli ."','".
				rtrim(str_replace("'","",$data['cdg_tcli'])) ."','".
				rtrim(str_replace("'","",$data['cdg_vend'])) ."',".
				$crdSol . "," .
				$data['swt_cli'] . ",'" .
				rtrim($data['cdg_lprc']) . "','".
				rtrim($data['tel_cli']) . "','".
				$dircli . "','". 
				rtrim($data['rep_cli']) . "'," .
				$SwtSusp . ")";		

			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++;
		}
	}
}
/*-------------------------------------------------------*/
function lista_cxc(){
	global $codven;
	//*********************************** Cuentas por Cobrar ***************************************************
	$SqlTmp = "SELECT m_ctecli.CDG_TDOC, m_ctecli.NUM_DOCU, m_ctecli.RUC_CLI, tipoDocum.tip_item,
		m_ctecli.CDG_MON, m_ctecli.FEC_DOCU, m_ctecli.VCT_DOCU, m_ctecli.IMP_DOCU, m_ctecli.PAG_DOCU, 
		m_ctecli.CDG_LOC, m_ctecli.TOT_RET, B.SaldoTotal, d_tablas.abr_item AS moneda, tipoDocum.abr_item AS tipodocu,
		T_DOCCLI.NUM_SER, (M_CTECLI.IMP_DOCU - M_CTECLI.PAG_DOCU) AS Saldo, m_client.cdg_vend  
		FROM M_CTECLI 
		INNER JOIN m_client ON m_client.ruc_cli = m_ctecli.ruc_cli 
		INNER JOIN T_DOCCLI ON M_CTECLI.CDG_TDOC = T_DOCCLI.CDG_TDOC 
		INNER JOIN d_tablas ON m_ctecli.cdg_mon = d_tablas.num_item AND d_tablas.cdg_tab = 'MON'
		INNER JOIN d_tablas AS tipoDocum ON m_ctecli.cdg_tdoc = tipoDocum.num_item AND tipoDocum.cdg_tab = 'TDC'
		INNER JOIN (SELECT RUC_CLI, SUM(IMP_DOCU - PAG_DOCU) AS SaldoTotal
						FROM M_CTECLI AS X
                        WHERE (IMP_DOCU - PAG_DOCU > 0) 
						AND (SWT_DOCU NOT IN ('T', 'A'))
                        GROUP BY RUC_CLI) AS B ON M_CTECLI.RUC_CLI = B.RUC_CLI
		WHERE (M_CTECLI.IMP_DOCU - M_CTECLI.PAG_DOCU > 0) 
		AND (M_CTECLI.SWT_DOCU NOT IN ('T', 'A')) ";
		
	if ($codven != ''){
		$SqlTmp = $SqlTmp . " AND m_client.cdg_vend = '$codven' ";
	}
	$SqlTmp = $SqlTmp . " ORDER BY M_CTECLI.RUC_CLI, M_CTECLI.FEC_DOCU ";
		
		
	$XvConteo = 1;
	$XvGrupoF = 0;		
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		echo "DELETE FROM docum_cc" . "\n";
		$XvCabecera = "INSERT INTO docum_cc (tipo_doc,nro_doc,co_cli,cdg_mon,tipodocu,tip_item,fec_emis,fec_venc,co_ven,neto,saldo,saldoTotal) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('" . rtrim($data['num_ser']) . "','" .
				rtrim($data['num_docu']) . "','" .
				$data['ruc_cli']  . "','" .
				ltrim(rtrim($data['moneda']))  . "','" .
				ltrim(rtrim($data['tipodocu']))  . "','" .
				ltrim(rtrim($data['tip_item']))  . "','" .
				$data['fec_docu'] . "'," .
				"'" .$data['vct_docu'] . "'," .
				"'" . $data['cdg_vend'] . "'," .
				$data['imp_docu'] . "," .
				$data['saldo'] . "," .
				$data['saldototal'] . ")";

			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=='cxc'){
	lista_cli();
	//*********************************** Cuentas por Cobrar ***************************************************
	$SqlTmp = "SELECT M_CTECLI.CDG_TDOC, M_CTECLI.NUM_DOCU, M_CTECLI.RUC_CLI, tipoDocum.tip_item,
		M_CTECLI.CDG_MON, M_CTECLI.FEC_DOCU, M_CTECLI.VCT_DOCU, M_CTECLI.IMP_DOCU, M_CTECLI.PAG_DOCU, 
		M_CTECLI.CDG_LOC, M_CTECLI.TOT_RET, B.SaldoTotal, d_tablas.abr_item AS moneda, tipoDocum.abr_item AS tipodocu,
		T_DOCCLI.NUM_SER, (M_CTECLI.IMP_DOCU - M_CTECLI.PAG_DOCU) AS Saldo  
		FROM M_CTECLI 
		INNER JOIN T_DOCCLI ON M_CTECLI.CDG_TDOC = T_DOCCLI.CDG_TDOC 
		INNER JOIN d_tablas ON m_ctecli.cdg_mon = d_tablas.num_item AND d_tablas.cdg_tab = 'MON'
		INNER JOIN d_tablas AS tipoDocum ON m_ctecli.cdg_tdoc = tipoDocum.num_item AND tipoDocum.cdg_tab = 'TDC'
		INNER JOIN (SELECT RUC_CLI, SUM(IMP_DOCU - PAG_DOCU) AS SaldoTotal
						FROM M_CTECLI AS X
						WHERE (IMP_DOCU - PAG_DOCU > 0) 
						AND (SWT_DOCU NOT IN ('T', 'A'))
						GROUP BY RUC_CLI) AS B ON M_CTECLI.RUC_CLI = B.RUC_CLI
		WHERE (M_CTECLI.IMP_DOCU - M_CTECLI.PAG_DOCU > 0) 
		AND (M_CTECLI.SWT_DOCU NOT IN ('T', 'A'))
		ORDER BY M_CTECLI.RUC_CLI, M_CTECLI.FEC_DOCU";

	$XvConteo = 1;
	$XvGrupoF = 0;		
	$XqTabla = pg_query( $SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		echo "DELETE FROM docum_cc" . "\n";
		$XvCabecera = "INSERT INTO docum_cc (tipo_doc,nro_doc,co_cli,cdg_mon,tipodocu,tip_item,fec_emis,fec_venc,co_ven,neto,saldo,saldoTotal) VALUES";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "('" . rtrim($data['num_ser']) . "','" .
				rtrim($data['num_docu']) . "','" .
				$data['ruc_cli']  . "','" .
				ltrim(rtrim($data['moneda']))  . "','" .
				ltrim(rtrim($data['tipodocu']))  . "','" .
				ltrim(rtrim($data['tip_item']))  . "','" .
				$data['fec_docu'] . "','" .
				$data['vct_docu'] . "',''," .
				$data['imp_docu'] . "," .
				$data['saldo'] . "," .
				$data['saldototal'] . ")";

			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=='pedidos'){
	global $codven;
	lista_lin();
	lista_art();
	lista_cli();
	//************************************ Pedidos ******************************************
	$SqlTmp = "SELECT A.num_ped, A.ruc_cli, A.cdg_vend, A.cdg_cpag, A.cdg_mon, A.fec_ped, A.imp_ttot, A.imp_stot, A.imp_tigv 
		FROM m_pedido AS A
		WHERE A.cdg_vend = '$codven' 
		AND A.swt_ped = ''
		ORDER BY A.num_ped";

	$XvGrupoF = 0;		
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		echo "DELETE FROM reng_ped WHERE id_ped IN (SELECT id_ped FROM pedidos WHERE nro_fac=0 AND ped_serv = 1) " . "\n";
		$XvCabecera = "INSERT INTO pedidos (ped_num, co_cli, co_ven, cdg_cpag, cdg_mon, fec_emis, tot_neto, tot_bruto, iva, tip_doc, ped_serv, destino) ";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "SELECT '". rtrim($data['num_ped']) . "','" .
				rtrim($data['ruc_cli']) . "','" .
				rtrim($data['cdg_vend']) . "','" .
				rtrim($data['cdg_cpag']) . "','" .
				rtrim($data['cdg_mon']) . "','" .
				rtrim($data['fec_ped']) . "'," .
				$data['imp_ttot'] . "," .
				$data['imp_stot'] . "," .
				$data['imp_tigv'] . "," .
				"'PED', 1, 'PED' " .
				"WHERE NOT EXISTS(SELECT ped_num FROM pedidos WHERE ped_num='". rtrim($data['num_ped']) . "')";

			if ($XvGrupoF >= 499 || $XvConteo>=$XvCantFila){
				$XvCadena = $XvCadena . "\n";
				$XvGrupoF = -1;
				echo $XvCadena;

				if (($XvConteo+2) < $XvCantFila){
					echo $XvCabecera;
				}
			}else{
				$XvCadena = $XvCadena . " UNION ";
				echo $XvCadena;
			}
			$XvConteo++;
			$XvGrupoF++;
		}
	}
	//**************** Renglones Pedidos ***********************
	$SqlTmp = "SELECT A.num_ped, A.cdg_prod, A.can_pprd, A.pre_pprd, A.imp_tprd, A.pre_igv, A.imp_igv 
		FROM d_pedido AS A 
		INNER JOIN m_pedido AS B ON A.num_ped = B.num_ped 
		WHERE B.cdg_vend = '$codven' 
		AND B.swt_ped = ''
		ORDER BY A.num_ped";

	$XvGrupoF = 0;		
	$XqTabla = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
	$XvCantFila = pg_num_rows($XqTabla);
		
	if ($XvCantFila > 0){
		$XvConteo = 1;
		$XvCabecera = "INSERT INTO reng_ped (id_ped, co_art, total_art, prec_vta, reng_neto, prec_vta_igv, reng_neto_igv) ";
		echo $XvCabecera;
		while ($data = pg_fetch_array($XqTabla)){
			$XvCadena = "SELECT A.id_ped,'" . rtrim($data['cdg_prod']) . "'," .
				rtrim($data['can_pprd']) . "," .
				rtrim($data['pre_pprd']) . "," .
				rtrim($data['imp_tprd']) . ",".
				rtrim($data['pre_igv']) . ",".
				rtrim($data['imp_igv']) . " ".
				"FROM pedidos AS A WHERE A.ped_num='".rtrim($data['num_ped'])."' AND A.nro_fac=0 AND A.ped_serv=1 ";

			if ($XvGrupoF >= 499 || $XvConteo>=$XvCantFila){
				$XvCadena = $XvCadena . "\n";
				$XvGrupoF = -1;
				echo $XvCadena;

				if (($XvConteo+2) < $XvCantFila){
					echo $XvCabecera;
				}
			}else{
				$XvCadena = $XvCadena . " UNION ";
				echo $XvCadena;
			}
			$XvConteo++;
			$XvGrupoF++;
		}
	}
}
pg_close($con);

?>