<?php 
require_once ("../app/formatos/formato.php");
$_POST['cli_nom'] = str_ireplace('&','y',$_POST['cli_nom']);
$_POST['emp_razsoc'] = str_ireplace('&','y',$_POST['emp_razsoc']);
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:qdt="urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2" xmlns:udt="urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ext:UBLExtensions>
    <ext:UBLExtension>
        <ext:ExtensionContent>
        </ext:ExtensionContent>
        </ext:UBLExtension>
    </ext:UBLExtensions>
    <cbc:UBLVersionID>2.1</cbc:UBLVersionID>
    <cbc:CustomizationID>2.0</cbc:CustomizationID>
	
<cbc:ProfileID schemeName="SUNAT:Identificador de Tipo de Operacion" schemeAgencyName="PE:SUNAT" schemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo17">0104</cbc:ProfileID>
<cbc:ID>'.$_POST['ven_numdoc'].'</cbc:ID>
 
<cbc:IssueDate>'.$_POST['ven_fec'].'</cbc:IssueDate>
  <cbc:InvoiceTypeCode listID="0101" listAgencyName="PE:SUNAT" listName="Tipo de Documento" listURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01">'.$_POST['tip_com'].'</cbc:InvoiceTypeCode>
  <cbc:Note languageLocaleID="1000">'.$_POST['ven_lettot'].'</cbc:Note>   
  <cbc:DocumentCurrencyCode listID="ISO 4217 Alpha" listName="Currency" listAgencyName="United Nations Economic Commission for Europe">'.$_POST['mon_let'].'</cbc:DocumentCurrencyCode>
<cbc:LineCountNumeric>1</cbc:LineCountNumeric>

<cac:Signature>
    <cbc:ID>'.$_POST['emp_ruc'].'</cbc:ID>
    <cac:SignatoryParty>
      <cac:PartyIdentification>
        <cbc:ID>'.$_POST['emp_ruc'].'</cbc:ID>
      </cac:PartyIdentification>
      <cac:PartyName>
        <cbc:Name>'.$_POST['emp_razsoc'].'</cbc:Name>
      </cac:PartyName>
    </cac:SignatoryParty>
    <cac:DigitalSignatureAttachment>
      <cac:ExternalReference>
        <cbc:URI>#SignatureKG</cbc:URI>
      </cac:ExternalReference>
    </cac:DigitalSignatureAttachment>
</cac:Signature>
  
<cac:AccountingSupplierParty>
        <cac:Party>
            <cac:PartyIdentification>
                <cbc:ID schemeID="6" schemeName="Documento de Identidad" schemeAgencyName="PE:SUNAT" schemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06">'.$_POST['emp_ruc'].'</cbc:ID>
            </cac:PartyIdentification>
            <cac:PartyName>
                <cbc:Name>'.$_POST['emp_rep'].'</cbc:Name>
            </cac:PartyName>
            <cac:PartyLegalEntity>
                <cbc:RegistrationName>'.$_POST['emp_razsoc'].'</cbc:RegistrationName>
                <cac:RegistrationAddress>
                    <cbc:AddressTypeCode>'.$_POST['punven_cod'].'</cbc:AddressTypeCode>
                </cac:RegistrationAddress>
            </cac:PartyLegalEntity>
        </cac:Party>
</cac:AccountingSupplierParty>
	
<cac:AccountingCustomerParty>
        <cac:Party>
            <cac:PartyIdentification>
                <cbc:ID schemeID="'.$_POST['tipdoc'].'" schemeName="Documento de Identidad" schemeAgencyName="PE:SUNAT" schemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06">'.$_POST['cli_numdoc'].'</cbc:ID>
            </cac:PartyIdentification>
            <cac:PartyLegalEntity>
                <cbc:RegistrationName>'.$_POST['cli_nom'].'</cbc:RegistrationName>
            </cac:PartyLegalEntity>
        </cac:Party>
</cac:AccountingCustomerParty>
   
	';
	
	if($_POST['Numcuotas']==1){
	if($_POST['venpag_est']==1){
		if($_POST['venpag_for']=='Contado'){
				$xml .=' <cac:PaymentTerms>
				<cbc:ID>'.$_POST['venpag_id'].'</cbc:ID>
				<cbc:PaymentMeansID>'.$_POST['venpag_for'].'</cbc:PaymentMeansID>
				</cac:PaymentTerms>';
		}
		
		if($_POST['venpag_for']=='Credito'){
				$xml .='<cac:PaymentTerms>
					<cbc:ID>'.$_POST['venpag_id'].'</cbc:ID>
					<cbc:PaymentMeansID>'.$_POST['venpag_for'].'</cbc:PaymentMeansID>
					<cbc:Amount currencyID="'.$_POST['mon_let'].'">'.$_POST['venpag_tot'].'</cbc:Amount>
					</cac:PaymentTerms>';
					
					
				foreach($_POST['venpag_forc'] as $indice=>$can)
		{
		
			$xml .='			
				<cac:PaymentTerms>
				<cbc:ID>'.$_POST['venpag_idc'][$indice].'</cbc:ID>
				<cbc:PaymentMeansID>'.$_POST['venpag_forc'][$indice].'</cbc:PaymentMeansID>
				<cbc:Amount currencyID="'.$_POST['mon_let'].'">'.$_POST['venpag_totc'][$indice].'</cbc:Amount>
				<cbc:PaymentDueDate>'.$_POST['venpag_fecvenc'][$indice].'</cbc:PaymentDueDate>
				</cac:PaymentTerms>
			';
		
		}
					
					
		}
		
	}
	}else{
		$xml .='<cac:PaymentTerms>
					<cbc:ID>'.$_POST['venpag_id'].'</cbc:ID>
					<cbc:PaymentMeansID>'.$_POST['venpag_for'].'</cbc:PaymentMeansID>
					<cbc:Amount currencyID="'.$_POST['mon_let'].'">'.$_POST['venpag_tot'].'</cbc:Amount>
					</cac:PaymentTerms>';
		
		foreach($_POST['venpag_forc'] as $indice=>$can)
		{
		
			$xml .='			
				<cac:PaymentTerms>
				<cbc:ID>'.$_POST['venpag_idc'][$indice].'</cbc:ID>
				<cbc:PaymentMeansID>'.$_POST['venpag_forc'][$indice].'</cbc:PaymentMeansID>
				<cbc:Amount currencyID="'.$_POST['mon_let'].'">'.$_POST['venpag_totc'][$indice].'</cbc:Amount>
				<cbc:PaymentDueDate>'.$_POST['venpag_fecvenc'][$indice].'</cbc:PaymentDueDate>
				</cac:PaymentTerms>
			';
		
		}
		
	}
	
	
$xml .='	
   
   
<cac:TaxTotal>
        <cbc:TaxAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($_POST['ven_igv'])).'</cbc:TaxAmount>
        <cac:TaxSubtotal>
            <cbc:TaxableAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($_POST['ven_valven'])).'</cbc:TaxableAmount>
            <cbc:TaxAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($_POST['ven_igv'])).'</cbc:TaxAmount>
            <cac:TaxCategory>
                <cbc:ID schemeID="UN/ECE 5305" schemeName="Tax Category Identifier" schemeAgencyName="PE:SUNAT">S</cbc:ID>
                <cac:TaxScheme>
                    <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">1000</cbc:ID>
                    <cbc:Name>IGV</cbc:Name>
                    <cbc:TaxTypeCode>VAT</cbc:TaxTypeCode>
                </cac:TaxScheme>
            </cac:TaxCategory>
        </cac:TaxSubtotal>
</cac:TaxTotal>
    
<cac:LegalMonetaryTotal>
         <cbc:LineExtensionAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($_POST['ven_valven'])).'</cbc:LineExtensionAmount>
		<cbc:TaxInclusiveAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($_POST['ven_tot'])).'</cbc:TaxInclusiveAmount>
		<cbc:PayableAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($_POST['ven_tot'])).'</cbc:PayableAmount>
</cac:LegalMonetaryTotal>
	
	';
		
$i=1;
foreach($_POST['vendet_can'] as $indice=>$can)
{
		
$item_proid=$_POST['pro_id'][$indice];
$item_nom=  str_ireplace('&','y',$_POST['vendet_art'][$indice]);   
$item_uniabr = $_POST['vendet_uni'][$indice];

$item_valuni=moneda_mysql($_POST['vendet_valuni'][$indice]);
$item_preuni=moneda_mysql($_POST['vendet_preuni'][$indice]);
$item_igv = $item_valuni * 0.18;

$item_valtot=$item_valuni * $can;
$item_igvtot=$item_igv * $can;

$xml .='
<cac:InvoiceLine>
        <cbc:ID>'.$i.'</cbc:ID>
        <cbc:InvoicedQuantity unitCode="'.$item_uniabr.'" unitCodeListID="UN/ECE rec 20" unitCodeListAgencyName="United Nations Economic Commission for Europe">'.$can.'</cbc:InvoicedQuantity>
        
		<cbc:LineExtensionAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($item_valtot)).'</cbc:LineExtensionAmount>
        
		<cac:PricingReference>
            <cac:AlternativeConditionPrice>
                <cbc:PriceAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money4($item_preuni)).'</cbc:PriceAmount>
                <cbc:PriceTypeCode listName="Tipo de Precio" listAgencyName="PE:SUNAT" listURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16">01</cbc:PriceTypeCode>
            </cac:AlternativeConditionPrice>
        </cac:PricingReference>
        
		<cac:TaxTotal>
            <cbc:TaxAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($item_igvtot)).'</cbc:TaxAmount>
            <cac:TaxSubtotal>
                <cbc:TaxableAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($item_valtot)).'</cbc:TaxableAmount>
                <cbc:TaxAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money($item_igvtot)).'</cbc:TaxAmount>
                <cac:TaxCategory>
                    <cbc:Percent>18.00</cbc:Percent>
                    <cbc:TaxExemptionReasonCode listAgencyName="PE:SUNAT" listName="Afectacion del IGV" listURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07">10</cbc:TaxExemptionReasonCode>
                    <cac:TaxScheme>
                        <cbc:ID schemeID="UN/ECE 5153" schemeName="Codigo de tributos" schemeAgencyName="PE:SUNAT">1000</cbc:ID>
                        <cbc:Name>IGV</cbc:Name>
                        <cbc:TaxTypeCode>VAT</cbc:TaxTypeCode>
                    </cac:TaxScheme>
                </cac:TaxCategory>
            </cac:TaxSubtotal>
        </cac:TaxTotal>
		
        <cac:Item>
            <cbc:Description>'.$item_nom.'</cbc:Description>
            <cac:SellersItemIdentification>
                <cbc:ID>'.$item_proid.'</cbc:ID>
            </cac:SellersItemIdentification>
          
        </cac:Item>
        <cac:Price>
            <cbc:PriceAmount currencyID="'.$_POST['mon_let'].'">'.moneda_mysql(formato_money4($item_valuni)).'</cbc:PriceAmount>
        </cac:Price>
</cac:InvoiceLine>';	
$i++;
}
$xml .='</Invoice>';
	
	
$fac = new DOMDocument;
$fac->standalone         = false;
$fac -> preserveWhiteSpace = true;
$fac->loadXML($xml);
//Save XML as a file
$nom_xml = $_POST['emp_ruc'].'-'.$_POST['tip_com'].'-'.$_POST['ven_numdoc'].'.xml';
$archivo = '../docsinfirma/'.$nom_xml;
$fac->save($archivo);
$data["url"] = "../../docgeneracion/firmar.php";
$data["arc"] = $archivo;
$data["tipcom"] = $_POST['tip_com'];
$data["ruc"] = $_POST['emp_ruc'];
echo json_encode($data);
	
?>