<?php session_start();
if(empty($_SESSION['user_vcrx_id'])){die('<resultado><error>No sesion expiro</error></resultado>');}
require('../cfg/res.php');

$clie1_sql='insert into clie1 (empr,docu,ptoe,enti,adrs)
select empr,docu,ptoe,enti,adrs from tvir1 where enti="'.$_SESSION['user_vcrx_id'].'" and docu="OP20"';
if(!mysql_query($clie1_sql,$link_vcrx)){die('<resultado><error>Ocurrio un error al registrar</error></resultado>');}

//echo $clie1_sql;

$num_sql='SELECT * FROM	numdocu WHERE	docu="OP20" AND ptoe="001001"';

//echo $num_sql;

$num_res=mysql_query($num_sql,$link_vcrx);
$num_numero=0;
if(mysql_num_rows($num_res)!=0){$num_numero=mysql_result($num_res,0,'numero');}



$num_numero++;
$num_numero=str_pad($num_numero,9,"0",STR_PAD_LEFT);
$idnum1_sql='select max(idnum1) as maximo from clie1  where  docu="OP20" AND ptoe="001001" and enti="'.$_SESSION['user_vcrx_id'].'"';
$idnum1_res=mysql_query($idnum1_sql,$link_vcrx);
$idnum1_clie=mysql_result($idnum1_res,0,'maximo');


$clie1_sql='update clie1 set 
numero="'.$num_numero.'",
fecha=NOW(),
plazo=3,
concepto="TIENDA VIRTUAL",
iuser="'.$_SESSION['user_vcrx_id'].'",
idate=NOW()
where 
docu="OP20" AND ptoe="001001" and idnum1="'.$idnum1_clie.'" and enti="'.$_SESSION['user_vcrx_id'].'"';
//echo $clie1_sql;

if(!mysql_query($clie1_sql,$link_vcrx)){die('<resultado><error>Ocurrio un error al registrar.</error></resultado>');}


$idnum1_sql='select max(idnum1) as maximo from tvir1  where   enti="'.$_SESSION['user_vcrx_id'].'" and  docu="OP20" and ptoe="001001"';
//echo $idnum1_sql;
$idnum1_res=mysql_query($idnum1_sql,$link_vcrx);
$idnum1_tvir=mysql_result($idnum1_res,0,'maximo');



$tvir2_sql='select *from tvir2 where idnum2="'.$idnum1_tvir.'"';
//echo $tvir2_sql;

$tvir2_res=mysql_query($tvir2_sql,$link_vcrx);

$iddet=0;
while($tvir2_r=mysql_fetch_assoc($tvir2_res))
{

	$iddet++;
	$item=$tvir2_r['item'];
	$cant=$tvir2_r['cant'];
	$puni=$tvir2_r['puni'];
	$dcto=$tvir2_r['dcto'];
	$ice=$tvir2_r['ice'];
	$iva=$tvir2_r['iva'];
	$irbp=$tvir2_r['irbp'];
	$ptoem=$tvir2_r['ptoem'];
	
	$clie2_sql='insert into clie2 
	(
	idnum2,
	iddet,
	item,
	cant,
	puni,
	dcto,
	ice,
	iva,
	irbp,
	ptoem)
	values(
	"'.$idnum1_clie.'",
	"'.$iddet.'",
	"'.$item.'",
	"'.$cant.'",
	"'.$puni.'",
	"'.$dcto.'",
	"'.$ice.'",
	"'.$iva.'",
	"'.$irbp.'",
	"'.$ptoem.'"
	)
	';
	//echo $clie2_sql;
	if(!mysql_query($clie2_sql,$link_vcrx)){die('<resultado><error>Ocurrio un error al registrar detalle.</error></resultado>');}

}
$tvir2_sql='delete from tvir2 where idnum2="'.$idnum1_tvir.'"';
mysql_query($tvir2_sql,$link_vcrx);
$tvir1_sql='update tvir1 set adrs= NULL where enti="'.$_SESSION['user_vcrx_id'].'"';
mysql_query($tvir1_sql,$link_vcrx);
echo '<resultado><error>Finalizo con exito</error></resultado>';
?>