<?php
	//set_time_limit(300);
	$json = file_get_contents('php://input');
	$dataJSON=json_decode($json, true); 
	if(is_array($dataJSON)){
		$XvResultado = '{"pedido": [{';
		include_once('conex.php');

		// Tipos de Pedidos
		// -------------------------------------------
		// m_pedidos
		// SWT_PTV = P  (Venta Mostrador)
		// SWT_PTV = Vacio (Venta Despacho)
		// -------------------------------------------
		// d_pedidos
		// 0 = Ventas Mostrador
		// 1 = Venta Despacho
		// -------------------------------------------
		$TipoPedido=1;
		// -------------------------------------------

		$SqlTmp = "SELECT por_tigv, mon_ped FROM t_params WHERE cdg_par = '000'";
		$XqParEmp = pg_query($SqlTmp)  or die(pg_last_error());
		$data = pg_fetch_array($XqParEmp);
		$cdg_mon = $data['mon_ped'];
		$por_tigv = $data['por_tigv'];

		for($i=0; $i<count($dataJSON);$i++){ 
			$co_cli 		= $dataJSON[$i]["co_cli"];
			$co_ven 		= $dataJSON[$i]["co_ven"];
			$fec_emis 		= $dataJSON[$i]["fec_emis"];
			$id_ped 		= $dataJSON[$i]["id_ped"];
			$cdg_cpag		= $dataJSON[$i]["cdg_cpag"];
			$tip_doc		= substr($dataJSON[$i]["tip_doc"], 0 , 1);
			$cod_usr		= $dataJSON[$i]["cod_usr"];
			$tot_bruto 		= $dataJSON[$i]["tot_bruto"];
			$iva 			= $dataJSON[$i]["iva"];
			$tot_neto 		= $dataJSON[$i]["tot_neto"];
			$comentarios	= $dataJSON[$i]["comentarios"];
			$renglonJSON	= $dataJSON[$i]["renglon"];
			$PedNumOrige	= $dataJSON[$i]["ped_num"];
			$cdg_tdoc		= $dataJSON[$i]["cdg_tdoc"];
			$suc_usr		= $dataJSON[$i]["suc_usr"];
			$por_tdct		= $dataJSON[$i]["por_tdct"];
			
			$imp_tdct		= round(($tot_bruto * $por_tdct)/100,2);
			$num_ser = "PED";
			$swt_cot = 0;
			if ($tip_doc == "C"){
				$swt_cot = 1;
				$num_ser = "COT";
			}
			
			$fec_emis = date("Ymd");

			$SqlTmp = "SELECT CDG_AREA FROM t_defvta WHERE CDG_LOC='$suc_usr' AND SWT_AREA='X' AND DEF_AREA='X'";
			$XqParEmp = pg_query($SqlTmp)  or die(pg_last_error());
			$dataAlma = pg_fetch_array($XqParEmp);
			$cdg_area = $dataAlma['cdg_area'];
			
			$SqlTmp = "SELECT A.NUM_ITEM, A.DES_ITEM, A.abr_item, A.SWT_ITEM, A.val_ITEM 
				FROM D_TABLAS AS A
				WHERE (A.CDG_TAB = 'CPG') 
				AND (A.NUM_ITEM = '".$cdg_cpag."') ";
			$XqFPago = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
			$datafPago = pg_fetch_array($XqFPago);
			$dv = intval($datafPago['val_item']);
			$fec_vence = date("Ymd", strtotime($fec_emis."+ $dv days"));
			
			$fact_num = "";
			$swt_ped = "";
			if ($tip_doc=="F" || $tip_doc=="B"){
				$swt_ped = "T";
			}

			$SqlTmp = "SELECT des_cli, cdg_alt, dir_cli FROM m_client WHERE ruc_cli='$co_cli' ";
			$XqCli = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
			$dataCli = pg_fetch_array($XqCli);
			$des_cli = $dataCli['des_cli'];
			$cdg_alt = $dataCli['cdg_alt'];
			$dir_cli = $dataCli['dir_cli'];
			if (empty($PedNumOrige)){
				//************************************************************************
				//************************* Correlativo Pedido ***************************
				//************************************************************************
				$llave = 0;
				$cotc_num = 0;
				while ($llave < 1){
					$SqlTmp = "SELECT cor_loc FROM t_correl WHERE cdg_cor ='003' AND cdg_loc='$suc_usr' ";
					$XqParEmp2 = pg_query($SqlTmp) or die('La consulta fallo: ' . pg_last_error());
					$data2 = pg_fetch_array($XqParEmp2);
					$cotc_num = $data2['cor_loc'];
					
					$SqlTmp = "SELECT num_ped FROM m_pedido WHERE num_ped = '$cotc_num' ";
					$XqPedidos = pg_query($SqlTmp)  or die('La consulta fallo: ' . pg_last_error());
					$CantReg = pg_num_rows($XqPedidos);
					if ($CantReg > 0){
						$CorrInt = (int)$cotc_num;
						$CorrInt++;
						$cotc_num = substr("0000000000".ltrim(rtrim((String)$CorrInt)), -8);
						$SqlTmp = "UPDATE t_correl SET cor_loc = '$cotc_num' WHERE cdg_cor ='003' AND cdg_loc='$suc_usr' ";
						$XqUpdatePed = pg_query($con, $SqlTmp)  or die(pg_last_error());
					}else{
						$llave = 1;
					}
				}
				//************************************************************************
				if($TipoPedido==0){
					$XvSWTPTV = 'P';
				}
				if($TipoPedido==1){
					$XvSWTPTV = '';
				}

				$SqlTmp = "INSERT INTO m_pedido 
					( NUM_PED, CDG_VEND, CDG_CPAG, CDG_MON, 
					FEC_PED, NUM_OCOM, IMP_STOT, IMP_TIGV, 
					IMP_TDCT, IMP_TTOT, POR_TDCT, POR_TIGV, 
					OBS_PED, SWT_PED, RUC_CLI, SWT_COT, 
					FEC_ANUL, SWT_PTV, ORI_AREA, CDG_AREA, 
					NUM_COT, CDG_USR, CDG_PRIO, IMP_AJU, 
					CDG_LOC, SWT_DIST, REF_PED, SWT_PROD, 
					IMP_TISC, NUM_NSAL, FEC_ENT, NUM_MESA, 
					NUM_PERS, HRA_PED, PND_APR, FEC_APR, 
					USR_APR, HRA_APR, VAL_DPVT, POR_DPVT, 
					DCT_APR, CTA_IVA, CTA_ICA, CTA_FTE, 
					POR_IVA, POR_ICA, POR_FTE, VAL_RET, 
					VAL_IVA, VAL_ICA, VAL_FTE, FEC_ING, 
					FEC_SAL, HRA_ING, HRA_SAL, TDC_CLI, 
					DOI_CLI, CDG_NAC, CNT_PED, VAL_CARG, 
					POR_CARG) VALUES 
					('$cotc_num', '$co_ven', '$cdg_cpag', '$cdg_mon', 
					'$fec_emis', '', $tot_bruto, $iva,
					$imp_tdct, $tot_neto, $por_tdct, $por_tigv, 
					'PEDIDO MOVIL', '$swt_ped', '$co_cli', $swt_cot, 
					NULL, '$XvSWTPTV', '$cdg_area', '000', 
					'', '$cod_usr', '000', 0.00,
					'$suc_usr', 0, '$des_cli', '', 
					0.00, '', NULL, '', 
					0, '','',NULL,
					'', '', 0.00, 0.00,
					'', '', '', '',
					0.00, 0.00, 0.00, 0.00,
					0.00, 0.00, 0.00, NULL,
					NULL, '', '', '',
					'', '', '', 0.00,
					0.00) ";
			}else{
				$cotc_num = $PedNumOrige;
				$SqlTmp = "UPDATE m_pedido SET swt_ped = 'T' WHERE num_ped = '$cotc_num'";
			}
			$XqInsertPed = pg_query($SqlTmp)  or die("Error - INSERT/UPDATE (m_pedido). " . pg_last_error());
			
			if ($tip_doc=="F" || $tip_doc=="B"){
				//************************************************************************
				//************************* Correlativo Guia *****************************
				//************************************************************************
				$llave = 0;
				$num_guia = "";
				while ($llave < 1){			
					$SqlTmp = "SELECT num_guia FROM t_guia WHERE cdg_tpg='002' AND cdg_loc='$suc_usr' ";
					$XqTguia = pg_query($SqlTmp)  or die(pg_last_error());
					$dataGuia = pg_fetch_array($XqTguia);
					$num_guia = $dataGuia['num_guia'];

					$SqlTmp = "SELECT * FROM m_guia WHERE cdg_tpg='002' AND num_guia='$num_guia' ";
					$XqPedidos = pg_query($SqlTmp)  or die('SELECT (m_guia) fallo: ' . pg_last_error());
					$CantReg = pg_num_rows($XqPedidos);
					if ($CantReg > 0){
						$CorrInt = (int)$num_guia;
						$CorrInt++;
						$num_guia = substr("000000000000000".ltrim(rtrim((String)$CorrInt)), -10);
						$SqlTmp = "UPDATE t_guia SET num_guia = '$num_guia' WHERE cdg_tpg='002' AND cdg_loc='$suc_usr' ";
						$XqUpdatePed = pg_query($con, $SqlTmp)  or die(pg_last_error());
					}else{
						$llave = 1;
					}
				}			
				//************************************************************************
				//************************* Correlativo Factura **************************
				//************************************************************************
				$llave = 0;
				$fact_num = "";
				while ($llave < 1){
					$SqlTmp = "SELECT num_docu, num_ser FROM t_doccli WHERE cdg_tdoc='$cdg_tdoc' ";
					$XqParEmp2 = pg_query($SqlTmp) or die('SELECT (t_doccli) fallo: ' . pg_last_error());
					$data2 = pg_fetch_array($XqParEmp2);
					$fact_num = $data2['num_docu'];
					$num_ser = $data2['num_ser'];
					
					$SqlTmp = "SELECT * FROM m_doccli WHERE cdg_tdoc='$cdg_tdoc' AND num_docu='$fact_num' ";
					$XqPedidos = pg_query($SqlTmp)  or die('La consulta fallo: ' . pg_last_error());
					$CantReg = pg_num_rows($XqPedidos);
					if ($CantReg > 0){
						$CorrInt = (int)$fact_num;
						$CorrInt++;
						$fact_num = substr("0000000000".ltrim(rtrim((String)$CorrInt)), -10);
						$SqlTmp = "UPDATE t_doccli SET num_docu = '$fact_num' WHERE cdg_tdoc='$cdg_tdoc' ";
						$XqUpdatePed = pg_query($con, $SqlTmp)  or die(pg_last_error());
					}else{
						$llave = 1;
					}
				}
				//************************************************************************
				$SqlTmp = "SELECT MAX(cor_docu) AS cor_docu FROM m_doccli";
				$XqCorDocu = pg_query($SqlTmp)  or die(pg_last_error());
				$dataCorDocu = pg_fetch_array($XqCorDocu);
				$cor_docu = $dataCorDocu['cor_docu'];

				$SqlTmp = "INSERT INTO m_doccli (
					CDG_TDOC, NUM_DOCU, RUC_CLI, DES_CLI,
					CDG_CPAG, CDG_MON, NUM_GUIA, CDG_TPG,
					CDG_TMOV, NUM_PED, FEC_DOCU, FEC_VCTO,
					FEC_CANC, VAL_FSUB, VAL_FDES, VAL_FFLE,
					VAL_FIGV, VAL_FINT, VAL_FTOT, VAL_FPAG,
					OBS_FCLI, SWT_EST, SWT_PED, POR_TIGV,
					POR_TDCT, POR_COMI, SWT_PR, TOT_COB,
					NUM_ORIG, NUM_VOUC, SWT_SAL, FEC_ANUL,
					DIRECCION, SWT_OTRO, REF_OTRO, CDG_OTRO,
					NUM_OTRO, FEC_OTRO, SWT_APLI, CMB_DOCU,
					VAL_EXON, FEC_APLI, CDG_USR, COR_DOCU,
					PED_ANTI, SWT_ANTI, VAL_ANTI, VAL_AJU,
					VND_DOCU, VAL_SERV, VAL_COMV, CDG_LOC,
					FEC_REC, SWT_DET, CDG_ALT, VAL_FISC,
					SWT_DESP, SWT_TEC, CDG_CCT, VAL_PERC,
					SWT_PERC, DSP_POZA, SWT_POZA, CDG_CAJA,
					VAL_FTE, VAL_ICA, VAL_IVA, VAL_RET,
					POR_FTE, POR_ICA, POR_IVA, NUM_SERV,
					CTA_FTE, CTA_ICA, CTA_IVA, HRA_DOCU,
					SWT_VINC, IMP_FISC, SUB_FISC, PGO_FISC,
					GAV_FISC, VAL_DPVT, POR_DPVT, COM_JEFE,
					ADJ_DOCU, CDG_BONO, NUM_BONO, DOC_BONO,
					AFE_PERC, SWT_PDF, SWT_ENV, SWT_BAJ,
					VAL_AFEC, VAL_INAF, VAL_CARG, POR_CARG,
					CDG_DET, POR_DET) 
					VALUES (
					'$cdg_tdoc', '$fact_num', '$co_cli', '$des_cli',
					'$cdg_cpag', '$cdg_mon', '$num_guia', '002',
					'000', '$cotc_num', '$fec_emis','$fec_vence',
					NULL, $tot_bruto, 0, 0,
					$iva, 0, $tot_neto, 0,
					'', 'T', '', $por_tigv,
					0, 0, 'R', 0,
					'', '', 'S', NULL,
					'$dir_cli', 0, '', '',
					'', NULL, '', 0,
					0, NULL, '$cod_usr', NULL,
					'', 0, 0, 0,
					'000', 0, 0, '$suc_usr',
					'$fec_emis', '', '$cdg_alt', 0,
					0, '', '0000000000', 0,
					'', '', '', '',
					0, 0, 0, 0,
					0, 0, 0, '',
					'', '', '', '16:13',
					'', '', '', '',
					'', 0, 0, 0,
					'', '', '', '',
					0, '', 0, 0,
					0, 0, 0, 0,
					'', 0)";
				$XqCorDocu = pg_query($SqlTmp)  or die(pg_last_error());
				//************************************************************************
				$SqlTmp = "INSERT INTO M_CTECLI (
					CDG_TDOC, NUM_DOCU, RUC_CLI, CDG_MON, 
					FEC_DOCU, VCT_DOCU, IMP_DOCU, PAG_DOCU, 
					SWT_DOCU, FEC_APLI, CDG_LOC, FEC_REC, 
					SWT_REC, CDG_COB, TOT_PERC, COB_PERC, 
					CDG_FLUJ, FEC_FLUJ, TOT_RET, CDG_ANUL)
					VALUES (
					'$cdg_tdoc', '$fact_num', '$co_cli', '$cdg_mon',
					'$fec_emis', '$fec_vence', $tot_neto, 0,
					'', NULL, '$suc_usr', '$fec_emis', 
					'', '', 0 , 0, 
					NULL, '$fec_emis', 0, NULL)";
				$XqInsertGuia = pg_query($SqlTmp)  or die(pg_last_error());
				//************************************************************************
				$SqlTmp = "INSERT INTO m_guia (
					CDG_TPG, NUM_GUIA, NUM_OCOM, NUM_GREM,
					CDG_AREA, FEC_GUIA, FEC_GREM, CDG_EST,
					ORI_AREA, SWT_EST, CDG_CHOF, NUM_PED,
					CAR_PLAC, CAR_TUR, CDG_TMOV, NUM_DOCU,
					CDG_MON, CDG_TDOC, SWT_ING, OBS_GUIA,
					RUC_CLI, FEC_ANUL, CAN_PESO, CAN_BULT, 
					DESTINO, PARTIDA, CDG_USR, CLIENTE,
					DIRECCION, CLI_PRV, NUM_INSC, CDG_ETRN,
					CDG_VEH, FEC_TRAS, BREVETE, TIP_CMB,
					CDG_LOC, NUM_REQ, LOC_REQ, CDG_RESP,
					SWT_DIST, CIE_DIST, INF_DIST, NUM_ORIG,
					NUM_VOUC, SUC_CLI, NUM_OTRB, NUM_TRAN,
					NUM_SERV, NUM_REC, NUM_COT, CDG_CCT,
					CDG_PART, SWT_VINC, TDC_DOCP, NUM_DOCP,
					PRV_DOCP, TAL_COT, EMP_RESP, DES_RESP) 
					VALUES (
					'002', '$num_guia', '','',
					'000', '$fec_emis', NULL,'',
					'$cdg_area', '', NULL, '$cotc_num',
					'', '', '000', '$fact_num',
					'$cdg_mon', '$cdg_tdoc', 2, '',
					'$co_cli', NULL, '', '',
					'', '', '$cod_usr', '',
					'', '', '', '000',
					'000', NULL, '', 0.000,
					'$suc_usr', '', '', '000',
					0, NULL, '', '',
					'', '', '', '',
					'', '', '', '0000000000',
					'', '', '', '',
					'', '', '', '') ";
				$XqInsertGuia = pg_query($SqlTmp)  or die(pg_last_error());
				//************************************************************************
			}
			//************************************************************************
			
			//************************************************************************
			//********************* INSERT Renglones *********************************
			//************************************************************************
			$RengNum = 1;
			for($iD=0; $iD<count($renglonJSON);$iD++){ 
				$coart 		= $renglonJSON[$iD]["co_art"];
				$totalart 	= $renglonJSON[$iD]["total_art"];
				$precio		= $renglonJSON[$iD]["prec_vta"];
				$reng_neto 	= $renglonJSON[$iD]["reng_neto"];
				$DctPprdTmp	= $renglonJSON[$iD]["dct_pprd"];
				$DctFicTmp	= $renglonJSON[$iD]["dct_fic"];
				
				$precioDesc = $precio - (($precio * $DctPprdTmp)/100);
				$precioDesc = $precioDesc - (($precioDesc * $DctFicTmp)/100);
				
				$SqlTmp = "SELECT cdg_umed, swt_igv FROM m_produc WHERE cdg_prod = '$coart' ";
				$XqArtTmp = pg_query($SqlTmp) or die("Error SELECT m_produc. " . pg_last_error());
				$DataArt = pg_fetch_array($XqArtTmp);
				$uni_venta = $DataArt['cdg_umed'];
				$swt_igv = $DataArt['swt_igv'];
				$PrecioConIva = 0;
				$imp_iva = 0;
				if ($swt_igv == 1){
					$imp_iva = round(($precioDesc * $por_tigv)/100,2);
					$PrecioConIva = round($precioDesc + $imp_iva,2);
					
					$imp_ivaFull = round(($precio * $por_tigv)/100,2);
					$PrecioConIvaFull = round($precio + $imp_ivaFull,2);
					
					$swt_igvC = "X";
				}else{
					$PrecioConIva = $precioDesc;
					$swt_igvC = "";
				}
				$imp_igv = $PrecioConIva * $totalart;
				$imp_iva2 = $imp_iva * $totalart;
				$num_item = substr("0000" . rtrim(ltrim((String)$RengNum)), -5);
				if (empty($PedNumOrige)){
					if ($TipoPedido==0){
						$XvCANDPRD = $totalart;
						$XvCANFPRD = $totalart;
					}

					if ($TipoPedido==1){
						$XvCANDPRD = 0;
						$XvCANFPRD = 0;
					}
					$SqlTmp = "INSERT INTO d_pedido ( 
						NUM_PED, CDG_PROD, CDG_FPRD, CAN_PPRD,
						PRE_PPRD, DCT_PPRD, DCT_FIC, IGV_PPRD,
						IMP_TPRD, CAN_DPRD, CAN_FPRD, OBS_PPRD,
						CDG_LPRC, PRE_IGV, IMP_IGV, CDG_PROM, 
						FAC_UVTA, CDG_UVTA, COM_PPRD, CAN_PROD,
						CAN_OTRB, CAN_UVTA, PRE_UVTA, VAL_UVTA,
						TOT_UVTA, POR_TISC, SWT_IGV, COM_IMPO,
						SAC_PPRD, SWT_CMP, POR_IGV, IMP_IVA,
						NUM_ITEM, IMP_PROD, SWT_IMPR, PCT_CARG, IMP_CARG, 
						ori_ped) 
						VALUES(
						'$cotc_num', '$coart', '000', $totalart, 
						$precio, $DctPprdTmp, $DctFicTmp, 0,
						$reng_neto, $XvCANDPRD, $XvCANFPRD, '',
						'000', $PrecioConIvaFull, $imp_igv, '',
						1, '$uni_venta', 0, 0,
						0, $totalart, $PrecioConIvaFull, $precio,
						$reng_neto, 0, '$swt_igvC', 0,
						'', '', $por_tigv, $imp_iva2,
						'$num_item', '', '', 0,0,
						'')";
					$XqInsertRengPed = pg_query($SqlTmp)  or die('Error INSERT d_pedido. '.pg_last_error());
					$RengNum ++;
				}
				
				if ($tip_doc=="F" || $tip_doc=="B"){
					/********************** Item del Documento *********************************/
					$SqlTmp = "INSERT INTO d_doccli (
						CDG_TDOC, NUM_DOCU, NUM_PED,
						CDG_PROD, CAN_DFAC, PRE_DFAC, DCT_DFAC,
						IMP_DFAC, CDG_FPRD, DCT_FIC, SWT_PED,
						SWT_PR, POR_COMI, OBS_DFAC, SWT_IGV,
						PRE_IGV, IMP_IGV, CDG_PROM, FAC_UVTA,
						CDG_UVTA, COM_DFAC, IMP_NOTC, CAN_UVTA,
						PRE_UVTA, VAL_UVTA, TOT_UVTA, POR_TISC,
						IMP_PERC, POR_PERC, SWT_ENT, CAN_POZA,
						POR_IGV, IMP_IVA, NUM_ITEM, IMP_TOT) 
						VALUES (
						'$cdg_tdoc', '$fact_num', '$cotc_num',
						'$coart', $totalart, $precio, 0,
						$reng_neto, '000', 0, '',
						'R', 0, '', '$swt_igvC',
						$PrecioConIva, $PrecioConIva*$totalart, '', 1,
						'$uni_venta', 0, 0, $totalart,
						$PrecioConIva, $precio, $reng_neto, 0,
						0,0,1,0,
						$por_tigv, $imp_iva, '$num_item', $PrecioConIva*$totalart)";
					$XqInsertDGuia = pg_query($SqlTmp)  or die('Error INSERT d_doccli. '.pg_last_error());
					
					$SqlTmp = "INSERT INTO d_guia (
						CDG_TPG, NUM_GUIA, CDG_PROD, CDG_UMED,
						CDG_EQV, FAC_EQV, CAN_PGUI, PRE_GUIA,
						CAN_DGUI, CAN_FGUI, FEC_GEN, CTO_PROM,
						OBS_DGUI, CMB_DGUI, CAN_COMO, UND_COMO,
						CTO_NAC, CTO_EXT, MAT_PRIM, MAN_OBRA,
						GTO_FABR, CTA_DEB, CTA_HAB, NUM_ITEM) 
						VALUES (
						'002', '$num_guia', '$coart','$uni_venta',
						'$uni_venta', 1, $totalart, $precio,
						$totalart, $totalart, '$fec_emis', 0.00,
						'', 0, 0, '',
						0, 0, 0, 0,
						0, '0000000000', '0000000000', '$num_item')";
					$XqInsertDGuia = pg_query($SqlTmp)  or die('Error INSERT d_guia. '.pg_last_error());
				}
				
			}
			
			$XvResultado = $XvResultado . '"docum":'.$id_ped.',"profit":"'.$cotc_num.'","fecha":"xxxx","tipo":"'.$num_ser.'","factura":"'.$fact_num.'"},{';
		}
		$XvResultado = substr($XvResultado, 0, strlen($XvResultado)-2) . "]}";
		echo $XvResultado;
	}else{
		echo "xxxxxxx";
	}
?>