<?php
function XML_OK($XML){
	return true;
	/*
	$dom = new DOMDocument();
	$dom->load($XML);	
	if($dom->schemaValidate("UBL-Invoice-2.1.xsd")){
		return true;
	}else{
		return false;//++
	}
	*/
}
//+++++++++++++
function XML_PROCESAR($XML,$HW,$USU,$XML_NOM_ORI,$XML_NOM_TMP,$MODO=0){
	
	$SYS_FEC=date("Y-m-d");
	$SYS_HOR=GetHoraAP();
	$SYS_TIM=time();
	//
	$xml=simplexml_load_file($XML);
	if($xml===false){
		/*
		foreach (libxml_get_errors() as $error) {
			echo $error->message . "<br>";
		}
		*/
		return "ERROR";
	} 
	$ns = $xml->getNamespaces(true);
	$cbc = $ns['cbc'];
	$cac = $ns['cac'];
	//
	$cabecera = [
		'serie_numero' => (string)$xml->children($cbc)->ID,
		'fecha'        => (string)$xml->children($cbc)->IssueDate,
		'hora'         => (string)$xml->children($cbc)->IssueTime,
		'moneda'       => (string)$xml->children($cbc)->DocumentCurrencyCode
	];
	//EMISOR
	$emisorNode = $xml->children($cac)->AccountingSupplierParty->children($cac)->Party;
	$emisor = [
		'ruc'  => (string)$xml->children($cac)
							->AccountingSupplierParty
							->children($cac)
							->Party
							->children($cac)
							->PartyIdentification
							->children($cbc)
							->ID,
	
		'nombre' => (string)$emisorNode
							->children($cac)
							->PartyLegalEntity
							->children($cbc)
							->RegistrationName
		
	];
	//CLIENTE
	$clienteNode = $xml->children($cac)->AccountingCustomerParty->children($cac)->Party;
	$cliente = [
		'documento' => (string)$clienteNode
								->children($cac)
								->PartyIdentification
								->children($cbc)
								->ID,
	
		'nombre' => (string)$clienteNode
							->children($cac)
							->PartyLegalEntity
							->children($cbc)
							->RegistrationName
	];
	//TOTALES
	$totalesNode = $xml->children($cac)->LegalMonetaryTotal;	
	$totales = [
		'subtotal' => (string)$totalesNode->children($cbc)->LineExtensionAmount,
		'total'    => (string)$totalesNode->children($cbc)->PayableAmount
	];
	$igv = 0;
	foreach ($xml->children($cac)->TaxTotal as $tax) {
		$igv += (float)$tax->children($cbc)->TaxAmount;
	}
	$totales['igv'] = $igv;
	$formaPago = 'CONTADO';
	foreach ($xml->children($cac)->PaymentTerms as $pt) {
    	if (trim(strtolower((string)$pt->children($cbc)->PaymentMeansID)) === 'credito') {
        	$formaPago = 'CREDITO';
	    }
	}
	//++++++++++++++++++++++++++++++++++++++++++++++++++++
	$DAT=explode("-",$cabecera['serie_numero']);
	$FAC_SER=$DAT[0];
	$FAC_NUM=$DAT[1];
	$FAC_FEC=$cabecera['fecha'];
	$FAC_HOR=$cabecera['hora'];
	$FAC_MND=$cabecera['moneda'];
	//++
	XML_MND_ADD($FAC_MND);
	//++
	$EMI_RUC=$emisor['ruc'];
	$EMI_NOM=$emisor['nombre'];
	//
		XML_EMP_ADD($EMI_RUC,$EMI_NOM);
	//
	$CLI_RUC=$cliente['documento'];
	$CLI_NOM=$cliente['nombre'];
	//
		XML_EMP_ADD($CLI_RUC,$CLI_NOM);
	//
	$FAC_STO=$totales['subtotal'];
	$FAC_IGV=$totales['igv'];
	$FAC_TOT=$totales['total'];
	//
	$TABLA_CAB="ges_xml";
	$TABLA_DET="ges_xml_det";
	$TABLA_CUO="ges_xml_cuo";
	if($MODO==0){
		ejt("DELETE FROM ges_xml_tmp WHERE hw='$HW' AND usu=$USU");
		ejt("DELETE FROM ges_xml_tmp_det WHERE hw='$HW' AND usu=$USU");
		ejt("DELETE FROM ges_xml_tmp_cuo WHERE hw='$HW' AND usu=$USU");
		$TABLA_CAB="ges_xml_tmp";
		$TABLA_DET="ges_xml_tmp_det";
		$TABLA_CUO="ges_xml_tmp_cuo";
	}
	//
	$EXI=gn("count(*)","ges_xml","xml_emi_ruc='$EMI_RUC' AND xml_ser='$FAC_SER' AND xml_num='$FAC_NUM' ");
	if($EXI>0){
		return "RE";
	}
	//
	$TCAM=1;
	$EMI_ES_AGENTE=gs("emp_age","ges_xml_empresas","emp_ruc='$CLI_RUC'");
	if(strlen($EMI_ES_AGENTE)==0)$EMI_ES_AGENTE="NO";
	if($EMI_ES_AGENTE=="SI"){
		if($FAC_MND=="PEN"){
			if($FAC_TOT>=700){
				$EMI_ES_AGENTE="SI";
			}else{
				$EMI_ES_AGENTE="NO";
			}
		}else{
			$EMI_ES_AGENTE="NO";
		}
	}
	//
	$s="INSERT INTO ".$TABLA_CAB."
		(hw,usu,fec,hor,tim,xml_nom,xml_ser,
		 xml_num,xml_fec,xml_hor,xml_mnd,
		 xml_emi_ruc,xml_emi_nom,xml_cli_ruc,xml_cli_nom,xml_sub,xml_igv,xml_tot,
		 xml_fdp,xml_nom_tmp,xml_ori,xml_ret,xml_tc) 
		VALUES 
		('$HW',$USU,'$SYS_FEC','$SYS_HOR',$SYS_TIM,'$XML_NOM_ORI','$FAC_SER',
		 '$FAC_NUM','$FAC_FEC','$FAC_HOR','$FAC_MND',
		 '$EMI_RUC','$EMI_NOM','$CLI_RUC','$CLI_NOM',$FAC_STO,$FAC_IGV,$FAC_TOT,
		 '$formaPago','$XML_NOM_TMP','XML','$EMI_ES_AGENTE',$TCAM)";
	//echo $s."<br>";
	$KEY=ejt7($s);
	//
	if($KEY>0){
		$items = [];
		foreach ($xml->children($cac)->InvoiceLine as $line) {	
			$CAN=(string)$line->children($cbc)->InvoicedQuantity;
			$PRE=(string)$line->children($cac)
										   ->Price
										   ->children($cbc)
										   ->PriceAmount;
			$DES=(string)$line->children($cac)
											 ->Item
											 ->children($cbc)
											 ->Description;
			$TOT=(string)$line->children($cbc)->LineExtensionAmount;
			//
			$CAN=vbval($CAN);
			$PRE=vbval($PRE);
			$TOT=vbval($TOT);
			//
			$s="INSERT INTO ".$TABLA_DET."
				(hw,usu,id_xml,det_can,det_pre,det_des,det_tot) 
				VALUES 
				('$HW',$USU,$KEY,$CAN,$PRE,'$DES',$TOT)";
			ejt($s);
		}
		//+++++++++++++++++++++++++++++++++++++++++++++++
		$cuotas = [];
		foreach ($xml->children($cac)->PaymentTerms as $pt) {		
			$id  = strtoupper((string)$pt->children($cbc)->ID);
			$pm  = strtoupper((string)$pt->children($cbc)->PaymentMeansID);		
			// detectar cuota en cualquiera de los dos campos
			if (strpos($id, 'CUOTA') !== false || strpos($pm, 'CUOTA') !== false) {	
				/*	
				$cuotas[] = [
					'cuota' => strpos($id, 'Cuota') !== false ? $id : $pm,
					'monto' => (string)$pt->children($cbc)->Amount,
					'fecha' => (string)$pt->children($cbc)->PaymentDueDate
				];
				*/
				$CUO=strpos($id, 'Cuota') !== false ? $id : $pm;
				$TOT=vbval((string)$pt->children($cbc)->Amount);
				$FEC=(string)$pt->children($cbc)->PaymentDueDate;
				//
				if($EMI_ES_AGENTE=="SI"){
					$CUO_TOT_RET=round($TOT * 0.03,2);
					$CUO_TOT_PAG=round($TOT - $CUO_TOT_RET,2);		
				}else{
					$CUO_TOT_PAG=$TOT;
					$CUO_TOT_RET=0;
				}
				//
				$s="INSERT INTO ".$TABLA_CUO."
					(hw,usu,id_xml,cuo_nro,cuo_tot,cuo_fec,cuo_fep , cuo_tot_pag , cuo_tot_ret ) 
					VALUES 
					('$HW',$USU,$KEY,'$CUO',$TOT,'$FEC','1900-01-01' , $CUO_TOT_PAG , $CUO_TOT_RET )";
				ejt($s);
			}
		}
	}
	return "OK";
}

