<?php


  function index($request){

          $pf = 'nd';
          $consecutive++;
          
          $user = $note->user;

          $companyNIT = '900711566';
          $companyNITDV = '0';
          $SoftwareID = 'feeb4367-44vb-400f-9dbb-0ee742608c3c';
          $ClTec = 'fc8eac422eba16e22ftt8c6f94b3f40a6e38162c';
          $pin = '48151';
          $AuthorizationProviderID = '809197268';

          // 32 Nota Débito sin referencia a facturas*.
          $CustomizationID = '32';
          $ProfileExecutionID = '2';
          $ID = $pf.$consecutive;

          $SoftwareSecurityCode = hash('sha384',$SoftwareID.$pin.$ID);
          $IssueDate  = $note->created_at->format('Y-m-d');
          $IssueTime = $note->created_at->format('h:s:i')."-05:00";
          $IndustryClasificationCode = '4761'; 
          $CompanyName = 'GRUPO FAILIA SAS';
          $CompanyAddress = 'CR 72 N 37 59';
          $CompanyCity = 'Bogotá, D.C.';
          $CompanyDepto = 'Bogotá, D.C.';
          $CompanyDeptoCode = '11';
          $companyEmail = 'gfinanciera@GRUPO.com';
          $TaxLevelCode = 'O-23';
          $TLClistName = '48';
          $cityCode = '11001';
          $TaxSchemeId = '01';
          $TaxSchemeName = 'IVA';

          $CustomerName = htmlspecialchars($user->name);
          $CustomerCityCode = '05042';
          $CustomerCity = htmlspecialchars($user->city);
          $CustomerDepto = htmlspecialchars($user->depto);
          $CustomerDeptoCode = '05';
          $CustomerAddress = htmlspecialchars($user->address);
          $CustomerNit = $user->personal_id;
          $CustomerEmail = $user->email;
          $CustomerIdCode = $user->type_of_id;
          $AdditionalAccountID = '2';
          
          $CustomerDV = null;
          if ($CustomerIdCode == '31') {
              $CustomerDV = $this->getDV($CustomerNit);
              $AdditionalAccountID = '1';
          };
        
          $TaxableAmount = '10000.00';
          $TaxAmount = '1900.00';
          $Percent = '19';

          $LineExtensionAmount = '10000.00';
          $TaxExclusiveAmount = '10000.00';
          $TaxInclusiveAmount = '11900.00';
          $ChargeTotalAmount = '0.00';
          $PayableAmount = '11900.00';

          $LineCountNumeric = 1;
          
          $codImp1 = '01';
          $ValImp1 =  $TaxAmount;

          $codImp2 = '04';
          $ValImp2 =  '0.00';

          $codImp3 = '03';
          $ValImp3 =  '0.00';

          $cufe = $ID.$IssueDate.$IssueTime.$LineExtensionAmount.$codImp1.$ValImp1.$codImp2.$ValImp2.$codImp3.$ValImp3.$PayableAmount.$companyNIT.$CustomerNit.$pin.$ProfileExecutionID;

          $UUID = hash('sha384',$cufe);

          $QRCode = "NroFactura=$ID NitFacturador=$companyNIT NitAdquiriente=$CustomerNit FechaFactura=$IssueDate ValorTotalFactura=$PayableAmount CUFE=$UUID URL=https://catalogo-vpfe-hab.dian.gov.co/document/searchqr?documentkey=$UUID";


          $xmlHead = $this->formHeadXMl();


          $xmlExtensions = $this->formExtensionXMl($companyNIT,$SoftwareID,$AuthorizationProviderID,$QRCode,$companyNITDV,$SoftwareSecurityCode);

          $xmlVersion = $this->formVersionXMl($CustomizationID,$ProfileExecutionID,$ID,$UUID,$IssueDate,$IssueTime,$LineCountNumeric);

          $xmlCompany = $this->formCompanyXMl($CompanyName,$CompanyCity,$CompanyDepto,$CompanyDeptoCode,$CompanyAddress,$companyNIT,$TaxLevelCode,$cityCode,$TaxSchemeId,$TaxSchemeName,$companyNITDV,$TLClistName,$companyEmail);

          $xmlCustomer = $this->formCustomerXMl($AdditionalAccountID,$CustomerName,$CustomerCityCode,$CustomerCity,$CustomerDepto,$CustomerDeptoCode,$CustomerAddress,$CustomerNit,$CustomerIdCode,$CustomerDV,$CustomerEmail);

          $xmlTotal = $this->formTotalsXMl($TaxableAmount,$Percent,$TaxAmount,$LineExtensionAmount,$TaxExclusiveAmount,$TaxInclusiveAmount,$PayableAmount);

          $xmlLines = $this->formLinesXMl();
          $xml = $xmlHead.$xmlExtensions.$xmlVersion.$xmlCompany.$xmlCustomer.$xmlTotal.$xmlLines;
          $firmado = new FirmadorV2();
          
          $certificadop12 = '../../PATH/cert.p12';
          $clavecertificado = '12345';
          
          
          $signed = $firmado->firmar($certificadop12, $clavecertificado, $xml, $UUID, $pf);

          $nit = '0'.$companyNIT;
          $ppp = '000';
          $aa = '20';
          $a = str_pad($consecutive, 8, '0', STR_PAD_LEFT);
          $xml_name = $pf.$nit.$ppp.$aa.$a.'.xml';
          $z = 'z';
          $fileName = $z.$nit.$ppp.$aa.$a.'.zip';
          $zip_name = '../../laravel/storage/xmls/debit_notes/'.$fileName;
          $zip = new ZipArchive;
          $zip->open($zip_name, ZipArchive::CREATE); 
          $zip->addFromString($xml_name, $signed);
          $zip->close();
          
          $document = file_get_contents($zip_name);
          $contentFile =  base64_encode($document);
          $created = gmdate("Y-m-d\TH:i:s\Z" );
          $expires = gmdate("Y-m-d\TH:i:s\Z", time() + 3600 );
          $testSetId = '9a13f4ed-f52a-4e30-8f1d-f6e183bc82f4';

          $soap = $this->formSoap($created,$expires,$xml_name,$contentFile,$testSetId);

          $options = [
              'body'    => $soap,
              'headers' => [
                  "Content-Type" => "application/soap+xml",
                  "accept" => "*/*",
                  "accept-encoding" => "gzip, deflate",
                  'action' => "http://wcf.dian.colombia/IWcfDianCustomerServices/SendTestSetAsync"
              ]
          ];

          $endpoint = "https://vpfe-hab.dian.gov.co/WcfDianCustomerServices.svc";
          $client = new Client();

          $res = $client->request(
              'POST',
              $endpoint,
              $options
          );

          $response = $res->getBody()->getContents();
  }

  function formLinesXMl(){


      $LineID = 1;
      $LineQty = 1;
      $LineBaseAmount = '10000.00';
      $LineTotal =' 10000.00';
      $LineTax = '1900.00';
      $LineTaxPercentage = 19;
      $LineItemName =  'recargo por cobrar';
      $TaxableAmount = $LineTotal;
      
      
      return "<cac:DebitNoteLine>
          <cbc:ID>$LineID</cbc:ID> 
          <cbc:DebitedQuantity unitCode='EA'>$LineQty</cbc:DebitedQuantity> 
          <cbc:LineExtensionAmount currencyID='COP'>$LineTotal</cbc:LineExtensionAmount> 
          <cac:TaxTotal> 
            <cbc:TaxAmount currencyID='COP'>$LineTax</cbc:TaxAmount> 
            <cac:TaxSubtotal> 
              <cbc:TaxableAmount currencyID='COP'>$TaxableAmount</cbc:TaxableAmount> 
              <cbc:TaxAmount currencyID='COP'>$LineTax</cbc:TaxAmount> 
              <cac:TaxCategory> 
                <cbc:Percent>$LineTaxPercentage</cbc:Percent> 
                <cac:TaxScheme> 
                  <cbc:ID>01</cbc:ID> 
                  <cbc:Name>IVA</cbc:Name> 
                </cac:TaxScheme> 
              </cac:TaxCategory> 
            </cac:TaxSubtotal> 
          </cac:TaxTotal> 
          <cac:Item> 
            <cbc:Description>$LineItemName</cbc:Description> 
          </cac:Item> 
          <cac:Price> 
            <cbc:PriceAmount currencyID='COP'>$LineTotal</cbc:PriceAmount> 
            <cbc:BaseQuantity unitCode='EA'>$LineQty</cbc:BaseQuantity> 
          </cac:Price> 
        </cac:DebitNoteLine></DebitNote>";

  }

  function formTotalsXMl($TaxableAmount,$Percent,$TaxAmount,$LineExtensionAmount,$TaxExclusiveAmount,$TaxInclusiveAmount,$PayableAmount){

    
    $string =
        "<cac:TaxTotal> 
          <cbc:TaxAmount currencyID='COP'>$TaxAmount</cbc:TaxAmount> 
          <cac:TaxSubtotal> 
            <cbc:TaxableAmount currencyID='COP'>$TaxableAmount</cbc:TaxableAmount> 
            <cbc:TaxAmount currencyID='COP'>$TaxAmount</cbc:TaxAmount> 
            <cac:TaxCategory> 
              <cbc:Percent>$Percent</cbc:Percent> 
              <cac:TaxScheme> 
                <cbc:ID>01</cbc:ID> 
                <cbc:Name>IVA</cbc:Name> 
              </cac:TaxScheme> 
            </cac:TaxCategory> 
          </cac:TaxSubtotal> 
        </cac:TaxTotal> 
        <cac:RequestedMonetaryTotal>
          <cbc:LineExtensionAmount currencyID='COP'>$LineExtensionAmount</cbc:LineExtensionAmount> 
          <cbc:TaxExclusiveAmount currencyID='COP'>$TaxExclusiveAmount</cbc:TaxExclusiveAmount> 
          <cbc:TaxInclusiveAmount currencyID='COP'>$TaxInclusiveAmount</cbc:TaxInclusiveAmount> 
          <cbc:PayableAmount currencyID='COP'>$PayableAmount</cbc:PayableAmount> 
        </cac:RequestedMonetaryTotal>";

    return $string;
  }

  function formCustomerXMl($AdditionalAccountID,$CustomerName,$CustomerCityCode,$CustomerCity,$CustomerDepto,$CustomerDeptoCode,$CustomerAddress,$CustomerNit,$customerIdCode,$CustomerDV,$CustomerEmail){
      return   
      "<cac:AccountingCustomerParty>
        <cbc:AdditionalAccountID>$AdditionalAccountID</cbc:AdditionalAccountID>
            <cac:Party> 
                <cac:PartyName> 
                    <cbc:Name>$CustomerName</cbc:Name>
                </cac:PartyName> 
                <cac:PhysicalLocation> 
                    <cac:Address> 
                        <cbc:ID>$CustomerCityCode</cbc:ID> 
                        <cbc:CityName>$CustomerCity</cbc:CityName> 
                        <cbc:CountrySubentity>$CustomerDepto</cbc:CountrySubentity> 
                        <cbc:CountrySubentityCode>$CustomerDeptoCode</cbc:CountrySubentityCode> 
                        <cac:AddressLine> 
                            <cbc:Line>$CustomerAddress</cbc:Line> 
                        </cac:AddressLine> 
                        <cac:Country> 
                            <cbc:IdentificationCode>CO</cbc:IdentificationCode> 
                            <cbc:Name languageID='es'>Colombia</cbc:Name> 
                        </cac:Country> 
                    </cac:Address> 
                </cac:PhysicalLocation> 
                <cac:PartyTaxScheme> 
                    <cbc:RegistrationName>$CustomerName</cbc:RegistrationName> 
                    <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeName='$customerIdCode' schemeID='$CustomerDV'>$CustomerNit</cbc:CompanyID> 
                    <cac:TaxScheme> 
                        <cbc:ID>ZY</cbc:ID> 
                        <cbc:Name>No Causa</cbc:Name> 
                    </cac:TaxScheme> 
                </cac:PartyTaxScheme> 
                <cac:PartyLegalEntity> 
                    <cbc:RegistrationName>$CustomerName</cbc:RegistrationName> 
                    <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$CustomerDV' schemeName='$customerIdCode'>$CustomerNit</cbc:CompanyID>
                </cac:PartyLegalEntity> 
                <cac:Contact>
                    <cbc:ElectronicMail>
                        $CustomerEmail
                    </cbc:ElectronicMail>
                </cac:Contact>
            </cac:Party> 
        </cac:AccountingCustomerParty>";

  }
  function formCompanyXMl($CompanyName,$CompanyCity,$CompanyDepto,$CompanyDeptoCode,$CompanyAddress,$companyNIT,$TaxLevelCode,$cityCode,$TaxSchemeId,$TaxSchemeName,$companyNITDV,$TLClistName,$companyEmail){

     $string = 
     "<cac:AccountingSupplierParty> 
        <cbc:AdditionalAccountID>1</cbc:AdditionalAccountID> 
        <cac:Party> 
            <cac:PartyName> 
                <cbc:Name>$CompanyName</cbc:Name> 
            </cac:PartyName>
            <cac:PhysicalLocation>
                <cac:Address>
                    <cbc:ID>$cityCode</cbc:ID>
                    <cbc:CityName>$CompanyCity</cbc:CityName>
                    <cbc:CountrySubentity>$CompanyDepto</cbc:CountrySubentity>
                    <cbc:CountrySubentityCode>$CompanyDeptoCode</cbc:CountrySubentityCode>
                    <cac:AddressLine>
                        <cbc:Line>$CompanyAddress</cbc:Line>
                    </cac:AddressLine>
                    <cac:Country>
                        <cbc:IdentificationCode>CO</cbc:IdentificationCode>
                        <cbc:Name languageID='es'>Colombia</cbc:Name>
                    </cac:Country>
                </cac:Address>
            </cac:PhysicalLocation> 
            <cac:PartyTaxScheme> 
                <cbc:RegistrationName>$CompanyName</cbc:RegistrationName> 
                <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$companyNITDV' schemeName='31'>$companyNIT</cbc:CompanyID> 
                <cbc:TaxLevelCode listName='$TLClistName'>$TaxLevelCode</cbc:TaxLevelCode> 
                <cac:RegistrationAddress> 
                    <cbc:ID>$cityCode</cbc:ID> 
                    <cbc:CityName>$CompanyCity</cbc:CityName> 
                    <cbc:CountrySubentity>$CompanyDepto</cbc:CountrySubentity> 
                    <cbc:CountrySubentityCode>$CompanyDeptoCode</cbc:CountrySubentityCode> 
                    <cac:AddressLine> 
                        <cbc:Line>$CompanyAddress</cbc:Line> 
                    </cac:AddressLine> 
                    <cac:Country> 
                        <cbc:IdentificationCode>CO</cbc:IdentificationCode> 
                        <cbc:Name languageID='es'>Colombia</cbc:Name> 
                    </cac:Country> 
                </cac:RegistrationAddress> 
                <cac:TaxScheme> 
                    <cbc:ID>$TaxSchemeId</cbc:ID> 
                    <cbc:Name>$TaxSchemeName</cbc:Name> 
                </cac:TaxScheme> 
            </cac:PartyTaxScheme> 
            <cac:PartyLegalEntity> 
                <cbc:RegistrationName>$CompanyName</cbc:RegistrationName> 
                <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$companyNITDV' schemeName='31'>$companyNIT</cbc:CompanyID> 
            </cac:PartyLegalEntity> 
            <cac:Contact>
                <cbc:ElectronicMail>$companyEmail</cbc:ElectronicMail>
            </cac:Contact>
        </cac:Party> 
    </cac:AccountingSupplierParty>";
     return $string;
  }

  function formVersionXMl($CustomizationID,$ProfileExecutionID,$ID,$UUID,$IssueDate,$IssueTime,$LineCountNumeric){

     return 
    "<cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID>
    <cbc:CustomizationID>$CustomizationID</cbc:CustomizationID> 
    <cbc:ProfileID>DIAN 2.1</cbc:ProfileID> 
    <cbc:ProfileExecutionID>$ProfileExecutionID</cbc:ProfileExecutionID> 
    <cbc:ID>$ID</cbc:ID> 
    <cbc:UUID schemeID='$ProfileExecutionID' schemeName='CUDE-SHA384'>$UUID</cbc:UUID> 
    <cbc:IssueDate>$IssueDate</cbc:IssueDate> 
    <cbc:IssueTime>$IssueTime</cbc:IssueTime>  
    <cbc:DocumentCurrencyCode listAgencyID='6' listAgencyName='United Nations Economic Commission for Europe' listID='ISO 4217 Alpha'>COP</cbc:DocumentCurrencyCode>
    <cbc:LineCountNumeric>$LineCountNumeric</cbc:LineCountNumeric>";
  }

  function formExtensionXMl($companyNIT,$SoftwareID,$AuthorizationProviderID,$QRCode,$companyNITDV,$SoftwareSecurityCode){
    return 
    "<ext:UBLExtensions> 
        <ext:UBLExtension> 
            <ext:ExtensionContent> 
                <sts:DianExtensions> 
                    <sts:InvoiceSource> 
                        <cbc:IdentificationCode listAgencyID='6' listAgencyName='United Nations Economic Commission for Europe' listSchemeURI='urn:oasis:names:specification:ubl:codelist:gc:CountryIdentificationCode-2.1'>CO</cbc:IdentificationCode> 
                    </sts:InvoiceSource> 
                    <sts:SoftwareProvider> 
                        <sts:ProviderID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$companyNITDV' schemeName='31'>$companyNIT</sts:ProviderID> 
                        <sts:SoftwareID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$SoftwareID</sts:SoftwareID> 
                    </sts:SoftwareProvider> 
                    <sts:SoftwareSecurityCode schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$SoftwareSecurityCode</sts:SoftwareSecurityCode> 
                    <sts:AuthorizationProvider> 
                        <sts:AuthorizationProviderID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='4' schemeName='31'>$AuthorizationProviderID</sts:AuthorizationProviderID> 
                        </sts:AuthorizationProvider> 
                        <sts:QRCode> $QRCode </sts:QRCode> 
                </sts:DianExtensions> 
            </ext:ExtensionContent> 
        </ext:UBLExtension> 
        <ext:UBLExtension><ext:ExtensionContent></ext:ExtensionContent></ext:UBLExtension></ext:UBLExtensions>";
  }

  function formHeadXMl(){
    $string = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><DebitNote xmlns='urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2' xmlns:cac='urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' xmlns:cbc='urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' xmlns:ext='urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' xmlns:sts='http://www.dian.gov.co/contratos/facturaelectronica/v1/Structures' xmlns:xades='http://uri.etsi.org/01903/v1.3.2#' xmlns:xades141='http://uri.etsi.org/01903/v1.4.1#' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-DebitNote-2.1.xsd'>";
    return $string;
  }

} 