<?php
defined('BASEPATH') or exit('No direct script access allowed');

class ParserFile
{

    protected $rutaDiaria = "";
    protected $rutaMensual = FCPATH . "DOWNLOADS/MONTH/format";

    //TODO: Añadir los nodos que falten mirando la libreria de java
    //TODO Nuevo Nodo: Proveedor de pliegos->TenderingTerms->DocumentProviderParty
    //TODO Nuevo Nodo: Lugar de recepción->TenderingTerms->TenderRecipientParty
    //TODO Nuevo Nodo: Proveedor de información adicional->TenderingTerms->AdditionalInformationParty
    //TODO Nuevo Nodo: Información sobre recursos//Lugar de presentación de recursos//Fecha límite de presentación de recursos//Arbitraje->TenderingTerms->AppealTerms
    //TODO Nuevo Nodo: Eventos->TenderingProcess->OpenTenderEvent

    public function __construct()
    {
        $this->CI = &get_instance();
        $this->CI->load->helper('file');
        $this->CI->load->library('parserdatabasebruto');
        $this->CI->load->library('parserdatabaselimpio');
    }

    public function index($rutaDiariaDownloader, $fechaInicioParser, $datosPerfil)
    {
        $this->rutaDiaria = $rutaDiariaDownloader . "/format/";
        $files = get_filenames($this->rutaDiaria, true);

        guardar_log("setLicitacion__" . $datosPerfil->prefijos_tablas . "__" . $fechaInicioParser, "----------------------------------", false);

        foreach ($files as $file) {
            $resultEntries = array();
            $entrada = file_get_contents($file);
            $xml = simplexml_load_string($entrada);
            $filename = basename($file);
            $aux = 0;
            foreach ($xml->entry as $clave => $row) {
                $arrayDeletedEntries = $xml->children('at', true);

                $resultEntries[$filename][$aux]['general'] = $this->nodoEntry($row, $datosPerfil->id);

                $resultEntries[$filename][$aux]['contractInfo'] = $this->nodoContractFolderStatus($row);

                $resultEntries[$filename][$aux]['locatedContractingParty'] = $this->nodoLocatedContractingParty($row);

                $resultEntries[$filename][$aux]['party'] = $this->nodoParty($row);

                $resultEntries[$filename][$aux]['procurementProject'] = $this->nodoPresupuesto($row);

                $resultEntries[$filename][$aux]['procurementProjectLot'] = $this->nodoProcurementProjectLot($row);

                $resultEntries[$filename][$aux]['tenderingTerms'] = $this->nodoTenderingTerms($row);

                $resultEntries[$filename][$aux]['tenderingProcess'] = $this->nodoTenderingProcess($row);

                $resultEntries[$filename][$aux]['tenderingResult'] = $this->nodoTenderResult($row);

                $resultEntries[$filename][$aux]['validNoticeInfo'] = $this->nodoValidNoticeInfo($row);

                $resultEntries[$filename][$aux]['legalDocs'] = $this->nodoLegalDoc($row);

                $resultEntries[$filename][$aux]['technicalDocs'] = $this->nodoTechnicalDocumentReference($row);

                $resultEntries[$filename][$aux]['generalDocs'] = $this->nodoGeneralDocuments($row);

                $resultEntries[$filename][$aux]['additionalDocs'] = $this->nodoAdditionalDocumentReference($row);

                $aux++;
            }

            $this->CI->parserdatabasebruto->setDatosParser($resultEntries, $fechaInicioParser, $datosPerfil);

            $this->CI->parserdatabaselimpio->index();

            //$str = print_r($resultEntries, true);

            //file_put_contents($this->rutaDiaria . "/text_" . $filename . ".txt", $str);
        }

        return;
    }

    private function nodoEntry($xml, $tipoPerfil)
    {
        $resultEntries = array();

        $resultEntries['url_id_licitacion'] = (string) $xml->id;
        $resultEntries['id_licitacion'] = (string) substr($xml->id, strrpos($xml->id, '/') + 1);
        $resultEntries['link_uri'] = (string) $this->existAttribute($xml, "link", "string", 'href');
        $resultEntries['summary'] = (string) $xml->summary;
        $resultEntries['title'] = (string) $xml->title;
        $resultEntries['updated'] = (string) $xml->updated;
        $resultEntries['tipo_perfil_licitacion'] = $tipoPerfil;
        return $resultEntries;
    }

    private function nodoContractFolderStatus($xml)
    {
        $resultEntries = array();
        if (isset($xml->ContractFolderStatus)) {
            $resultEntries['ContractFolderID'] = (string) $xml->ContractFolderStatus->ContractFolderID;
            $resultEntries['ContractFolderStatusCode'] = (string) $xml->ContractFolderStatus->ContractFolderStatusCode;
            $resultEntries['ContractFolderStatusCodeAttr'] = $this->existAttribute($xml->ContractFolderStatus, "ContractFolderStatusCode", "string", 'listURI');
        }
        $resultFinal = $this->array_remove_empty($resultEntries);
        return $resultFinal;
    }

    private function nodoLocatedContractingParty($xml)
    {
        $resultEntries = array();
        if (isset($xml->ContractFolderStatus->LocatedContractingParty) && !empty($xml->ContractFolderStatus->LocatedContractingParty)) {
            $LocatedContractingParty = $xml->ContractFolderStatus->LocatedContractingParty;

            $resultEntries['locatedContractingParty']['contractingPartyTypeCode'] = $this->existNodo($LocatedContractingParty, "ContractingPartyTypeCode", 'string');
            $resultEntries['locatedContractingParty']['contractingPartyTypeCodeUri'] = $this->existAttribute($LocatedContractingParty, "ContractingPartyTypeCode", 'string', 'listURI');

            if (isset($LocatedContractingParty->ActivityCode)) {
                if (count($LocatedContractingParty->ActivityCode) > 1) {
                    for ($i = 0; $i < count($LocatedContractingParty->ActivityCode); $i++) {
                        $resultEntries['activity'][$i]['activityCode'] = (string) $LocatedContractingParty->ActivityCode[$i];
                        $resultEntries['activity'][$i]['activityCodeUri'] = (string) $LocatedContractingParty->ActivityCode[$i]->attributes()['listURI'];
                    }
                } else {
                    $resultEntries['activity'][0]['activityCode'] = $this->existNodo($LocatedContractingParty, "ActivityCode", 'string');
                    $resultEntries['activity'][0]['activityCodeUri'] = $this->existAttribute($LocatedContractingParty, "ActivityCode", 'string', 'listURI');

                }
            }

            $resultEntries['locatedContractingParty']['buyerProfileURIID'] = $this->existNodo($LocatedContractingParty, "BuyerProfileURIID", 'string');

            if (isset($LocatedContractingParty->ParentLocatedParty)) {
                $this->RecurseXML($LocatedContractingParty->ParentLocatedParty);
            }
        }
        $resultFinal = $this->array_remove_empty($resultEntries);
        return $resultFinal;
    }

    private function nodoParty($xml)
    {
        $resultEntries = array();
        $contractFolder = $xml->ContractFolderStatus->LocatedContractingParty;

        if (isset($contractFolder->Party)) {
            //Datos Empresa -> direccion,nif, etc
            //LocatedContractingParty->Party
            $party = $contractFolder->Party;
            $resultEntries['party']['websiteURI'] = $this->existNodo($party, "WebsiteURI", 'string');

            if (isset($party->PartyIdentification) && !empty($party->PartyIdentification)) {
                for ($i = 0; $i < count($party->PartyIdentification); $i++) {
                    $resultEntries['partyIdentification'][$i]['idPartyIdent'] = $this->existNodo($party->PartyIdentification[$i], "ID", 'string');
                    $resultEntries['partyIdentification'][$i]['attr'] = $this->existAttribute($party, $party->PartyIdentification[$i]->ID, "string", 'schemeName');
                }
            }

            $resultEntries['party']['partyName'] = $this->existNodo($party->PartyName, "Name", 'string');
            $resultEntries['party']['city'] = $this->existNodo($party->PostalAddress, "CityName", 'string');
            $resultEntries['party']['codpostal'] = $this->existNodo($party->PostalAddress, "PostalZone", 'string');
            $resultEntries['party']['direccion'] = $this->existNodo($party->PostalAddress->AddressLine, "Line", 'string');
            $resultEntries['party']['country'] = $this->existNodo($party->PostalAddress->Country, "Name", 'string');
            $resultEntries['party']['contact_name'] = $this->existNodo($party->Contact, "Name", 'string');
            $resultEntries['party']['contact_email'] = $this->existNodo($party->Contact, "ElectronicMail", 'string');
        }
        $resultFinal = $this->array_remove_empty($resultEntries);
        return $resultFinal;
    }

    private function nodoPresupuesto($xml)
    {
        $resultEntries = array();

        $procurementProject = $xml->ContractFolderStatus->ProcurementProject;

        if (isset($procurementProject)) {
            //ProcurementProject

            $resultEntries['budget']['name'] = $this->existNodo($procurementProject, 'Name', 'string');
            $resultEntries['budget']['typeCode'] = $this->existNodo($procurementProject, 'TypeCode', 'string');
            $resultEntries['budget']['subTypeCode'] = $this->existNodo($procurementProject, 'SubTypeCode', 'string');

            if (isset($procurementProject->BudgetAmount)) {
                $resultEntries['budget']['estimatedOverallContractAmount'] = $this->existNodo($procurementProject->BudgetAmount, 'EstimatedOverallContractAmount', 'string');
                $resultEntries['budget']['totalAmount'] = $this->existNodo($procurementProject->BudgetAmount, 'TotalAmount', 'string');
                $resultEntries['budget']['taxExclusiveAmount'] = $this->existNodo($procurementProject->BudgetAmount, 'TaxExclusiveAmount', 'string');
            }

            if (isset($procurementProject->RequiredCommodityClassification)) {
                for ($i = 0; $i < count($procurementProject->RequiredCommodityClassification); $i++) {
                    $resultEntries['itemClass'][$i]['itemClassification_value'] = $this->existNodo($procurementProject->RequiredCommodityClassification[$i], 'ItemClassificationCode', 'string');
                    $resultEntries['itemClass'][$i]['itemClassification_attr'] = (string) $procurementProject->RequiredCommodityClassification[$i]->ItemClassificationCode['listURI'];
                }
            }

            if (isset($procurementProject->RealizedLocation)) {
                $resultEntries['budget']['countrySubentity'] = $this->existNodo($procurementProject->RealizedLocation, 'CountrySubentity', 'string');
                if (isset($procurementProject->RealizedLocation->CountrySubentityCode)) {
                    $resultEntries['budget']['countrySubentityCode'] = $this->existNodo($procurementProject->RealizedLocation, 'CountrySubentityCode', 'string');
                    $resultEntries['budget']['countrySubentityCodeAttr'] = $this->existAttribute($procurementProject->RealizedLocation, "CountrySubentityCode", "string", 'listURI');
                }

                if (isset($procurementProject->RealizedLocation->Address)) {
                    $resultEntries['budget']['cityName'] = $this->existNodo($procurementProject->RealizedLocation->Address->Country, 'CityName', 'string');
                    $resultEntries['budget']['IdentificationCode'] = $this->existNodo($procurementProject->RealizedLocation->Address->Country, 'IdentificationCode', 'string');
                    $resultEntries['budget']['countryName'] = $this->existNodo($procurementProject->RealizedLocation->Address->Country, 'Name', 'string');
                }
            }

            $resultEntries['budget']['durationMesure'] = $this->existNodo($procurementProject->PlannedPeriod, 'DurationMeasure', 'string');
            $resultEntries['budget']['duracion_inicio'] = $this->existNodo($procurementProject->PlannedPeriod, 'StartDate', 'string');
            $resultEntries['budget']['duracion_fin'] = $this->existNodo($procurementProject->PlannedPeriod, 'EndDate', 'string');
            $resultEntries['budget']['medida'] = $this->existAttribute($procurementProject->PlannedPeriod, "DurationMeasure", "string", 'unitCode');

            $resultEntries['budget']['contractExtension'] = $this->existNodo($procurementProject->ContractExtension, 'OptionsDescription', 'string');
        }

        $resultFinal = $this->array_remove_empty($resultEntries);
        return $resultFinal;
    }

    private function nodoProcurementProjectLot($xml)
    {
        $resultEntries = array();
        $procurementProjectLot = $xml->ContractFolderStatus->ProcurementProjectLot;

        if (isset($procurementProjectLot)) {
            for ($i = 0; $i < count($procurementProjectLot); $i++) {
                $resultEntries[$i]['idProcurementLot'] = $this->existNodo($procurementProjectLot[$i], 'ID', 'string');
                $resultEntries[$i]['name'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject, 'Name', 'string');
                $resultEntries[$i]['totalAmount'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject->BudgetAmount, 'TotalAmount', 'string');
                $resultEntries[$i]['taxExclusiveAmount'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject->BudgetAmount, 'TaxExclusiveAmount', 'string');

                $clasificacionItems = $procurementProjectLot[$i]->ProcurementProject->RequiredCommodityClassification;
                if (isset($clasificacionItems)) {
                    for ($j = 0; $j < count($clasificacionItems); $j++) {
                        $resultEntries[$i]['itemClassification'][$j]['idItem'] = $this->existNodo($clasificacionItems[$j], "ItemClassificationCode", "string");
                        $resultEntries[$i]['itemClassification'][$j]['id_attr'] = $this->existAttribute($clasificacionItems[$j], "ItemClassificationCode", "string", 'listURI');
                    }
                }

                if (isset($procurementProjectLot[$i]->ProcurementProject->RealizedLocation)) {
                    $resultEntries[$i]['countrySubentity'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject->RealizedLocation, 'CountrySubentity', 'string');
                    $resultEntries[$i]['countrySubentityCode'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject->RealizedLocation, 'CountrySubentityCode', 'string');
                    $resultEntries[$i]['identificationCode'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject->RealizedLocation->Address->Country, 'IdentificationCode', 'string');
                    $resultEntries[$i]['nameLocation'] = $this->existNodo($procurementProjectLot[$i]->ProcurementProject->RealizedLocation->Address->Country, 'Name', 'string');
                }
            }
        }
        $resultFinal = $this->array_remove_empty($resultEntries);
        return $resultFinal;
    }

    private function nodoTenderResult($xml)
    {
        $resultEntries = array();
        $tenderResult = $xml->ContractFolderStatus->TenderResult;
        for ($i = 0; $i < count($tenderResult); $i++) {
            $resultEntries[$i]['resultCode'] = $this->existNodo($tenderResult[$i], 'ResultCode', 'string');
            $resultEntries[$i]['description'] = $this->existNodo($tenderResult[$i], 'Description', 'string');
            $resultEntries[$i]['awardDate'] = $this->existNodo($tenderResult[$i], 'AwardDate', 'string');
            $resultEntries[$i]['receivedTenderQuantity'] = $this->existNodo($tenderResult[$i], 'ReceivedTenderQuantity', 'string');
            $resultEntries[$i]['lowerTenderAmount'] = $this->existNodo($tenderResult[$i], 'LowerTenderAmount', 'string');
            $resultEntries[$i]['higherTenderAmount'] = $this->existNodo($tenderResult[$i], 'HigherTenderAmount', 'string');
            $resultEntries[$i]['startDate'] = $this->existNodo($tenderResult[$i], 'StartDate', 'string');
            $resultEntries[$i]['smeawardedIndicator'] = $this->existNodo($tenderResult[$i], 'SMEAwardedIndicator', 'string');
            //AwardedTenderedProject
            $resultEntries[$i]['contract_id'] = $this->existNodo($tenderResult[$i]->Contract, 'ID', 'string');
            $resultEntries[$i]['contract_issueDate'] = $this->existNodo($tenderResult[$i]->Contract, 'IssueDate', 'string');

            $winningParty = $tenderResult[$i]->WinningParty;
            if (isset($winningParty)) {
                $resultEntries[$i]['partyIdentification'] = $this->existNodo($winningParty->PartyIdentification, 'ID', 'string');
                $resultEntries[$i]['partyName'] = $this->existNodo($winningParty->PartyName, 'Name', 'string');
            }
            $awardedTenderedProject = $tenderResult[$i]->AwardedTenderedProject;
            if (isset($awardedTenderedProject)) {
                $resultEntries[$i]['procurementProjectLotID'] = $this->existNodo($awardedTenderedProject, 'ProcurementProjectLotID', 'string');
                $resultEntries[$i]['TaxExclusiveAmount'] = $this->existNodo($awardedTenderedProject->LegalMonetaryTotal, 'TaxExclusiveAmount', 'string');
                $resultEntries[$i]['PayableAmount'] = $this->existNodo($awardedTenderedProject->LegalMonetaryTotal, 'PayableAmount', 'string');
            }
        }
        //$resultFinal = $this->array_remove_empty($resultEntries);
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function nodoTenderingTerms($xml)
    {
        $resultEntries = array();
        $TenderingTerms = $xml->ContractFolderStatus->TenderingTerms;

        if (isset($TenderingTerms)) {

            $resultEntries[0]['requiredCurriculaIndicator'] = $this->existNodo($TenderingTerms, 'RequiredCurriculaIndicator', 'string');
            $resultEntries[0]['variantConstraintIndicator'] = $this->existNodo($TenderingTerms, 'VariantConstraintIndicator', 'string');
            $resultEntries[0]['fundingProgramCode'] = $this->existNodo($TenderingTerms, 'FundingProgramCode', 'string');
            if (isset($TenderingTerms->RequiredFinancialGuarantee->GuaranteeTypeCode)) {
                $resultEntries[0]['guaranteeTypeCode'] = $this->existNodo($TenderingTerms->RequiredFinancialGuarantee, 'GuaranteeTypeCode', 'string');
                $resultEntries[0]['guaranteeTypeCode_attr'] = $this->existAttribute($TenderingTerms->RequiredFinancialGuarantee, "GuaranteeTypeCode", "string", 'listURI');
                $resultEntries[0]['requiredFinancialGuarantee_Amount'] = $this->existNodo($TenderingTerms->RequiredFinancialGuarantee, 'AmountRate', 'string');
            }

            $resultEntries[0]['procurementLegislationDocumentReference'] = $this->existNodo($TenderingTerms->ProcurementLegislationDocumentReference, 'ID', 'string');
            $resultEntries[0]['allowedSubcontractTerms'] = $this->existNodo($TenderingTerms->AllowedSubcontractTerms, 'Description', 'string');

            $tendererAwardingTerms = $TenderingTerms->AwardingTerms;
            if (isset($tendererAwardingTerms) && !empty($tendererAwardingTerms)) {
                for ($i = 0; $i < count($tendererAwardingTerms->AwardingCriteria); $i++) {
                    $resultEntries[1][$i]['evaluationCriteriaTypeCode'] = $this->existNodo($tendererAwardingTerms[$i], 'Description', 'string');
                    $resultEntries[1][$i]['description'] = $this->existNodo($tendererAwardingTerms[$i], 'WeightNumeric', 'string');
                }
            }

            $tendererQualificationRequest = $TenderingTerms->TendererQualificationRequest;
            if (isset($tendererQualificationRequest) && !empty($tendererQualificationRequest)) {
                $resultEntries[0]['description'] = $this->existNodo($tendererQualificationRequest, 'Description', 'string');
                $resultEntries[0]['personalSituation'] = $this->existNodo($tendererQualificationRequest, 'PersonalSituation', 'string');
                for ($i = 0; $i < count($tendererQualificationRequest); $i++) {
                    if (isset($tendererQualificationRequest[$i]->TechnicalEvaluationCriteria->EvaluationCriteriaTypeCode)) {
                        $resultEntries[2][$i]['evaluationCriteriaTypeCode'] = $this->existNodo($tendererQualificationRequest[$i]->TechnicalEvaluationCriteria, 'EvaluationCriteriaTypeCode', 'string');
                        $resultEntries[2][$i]['evaluationCriteriaTypeCode_attr'] = $this->existAttribute($tendererQualificationRequest[$i]->TechnicalEvaluationCriteria, "EvaluationCriteriaTypeCode", "sting", 'listURI');
                        $resultEntries[2][$i]['description'] = $this->existNodo($tendererQualificationRequest[$i]->TechnicalEvaluationCriteria, 'Description', 'string');
                    }

                }
            }

            if (isset($TenderingTerms->TendererQualificationRequest->FinancialEvaluationCriteria)
                && !empty($TenderingTerms->TendererQualificationRequest->FinancialEvaluationCriteria)) {
                $financialEvaluationCriteria = $TenderingTerms->TendererQualificationRequest->FinancialEvaluationCriteria;
                for ($i = 0; $i < count($financialEvaluationCriteria); $i++) {
                    $resultEntries[3][$i]['evaluationCriteriaTypeCode'] = $this->existNodo($financialEvaluationCriteria[$i], 'EvaluationCriteriaTypeCode', 'string');
                    $resultEntries[3][$i]['evaluationCriteriaTypeCode_attr'] = $this->existAttribute($financialEvaluationCriteria[$i], "EvaluationCriteriaTypeCode", "string", 'listURI');
                    $resultEntries[3][$i]['description'] = $this->existNodo($financialEvaluationCriteria[$i], 'Description', 'string');
                }
            }

            if (isset($TenderingTerms->TendererQualificationRequest->SpecificTendererRequirement)
                && !empty($TenderingTerms->TendererQualificationRequest->SpecificTendererRequirement)) {
                $specificTendererRequirement = $TenderingTerms->TendererQualificationRequest->SpecificTendererRequirement;
                for ($i = 0; $i < count($specificTendererRequirement); $i++) {

                    $resultEntries[4][$i]['evaluationCriteriaTypeCode'] = $this->existNodo($specificTendererRequirement[$i]->SpecificTendererRequirement, 'RequirementTypeCode', 'string');
                    $resultEntries[4][$i]['evaluationCriteriaTypeCode_attr'] = $this->existAttribute($specificTendererRequirement[$i]->SpecificTendererRequirement, "RequirementTypeCode", "string", 'listURI');
                }
            }

            $resultEntries[0]['language'] = $this->existNodo($TenderingTerms->Language, 'ID', 'string');
        }

        //$resultFinal = $this->array_remove_empty($resultEntries);
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function nodoTenderingProcess($xml)
    {
        $resultEntries = array();
        $tenderingProcess = $xml->ContractFolderStatus->TenderingProcess;

        if (isset($tenderingProcess)) {
            //TenderingProcess
            $resultEntries['procedureCode'] = $this->existNodo($tenderingProcess, 'ProcedureCode', 'string');
            $resultEntries['procedureCode_attr'] = $this->existAttribute($tenderingProcess, "ProcedureCode", "string", 'listURI');

            $resultEntries['urgencyCode'] = $this->existNodo($tenderingProcess, 'UrgencyCode', 'string');
            $resultEntries['urgencyCode_attr'] = $this->existAttribute($tenderingProcess, "UrgencyCode", "string", 'listURI');

            $resultEntries['contractingSystemCode'] = $this->existNodo($tenderingProcess, 'ContractingSystemCode', 'string');
            $resultEntries['contractingSystemCode_attr'] = $this->existAttribute($tenderingProcess, "ContractingSystemCode", "string", 'listURI');

            $resultEntries['partPresentationCode'] = $this->existNodo($tenderingProcess, 'PartPresentationCode', 'string');
            $resultEntries['partPresentationCode_attr'] = $this->existAttribute($tenderingProcess, "PartPresentationCode", "string", 'listURI');

            $resultEntries['submissionMethodCode'] = $this->existNodo($tenderingProcess, 'SubmissionMethodCode', 'string');
            $resultEntries['submissionMethodCode_attr'] = $this->existAttribute($tenderingProcess, "SubmissionMethodCode", "string", 'listURI');

            $resultEntries['maximumLotPresentationQuantity'] = $this->existNodo($tenderingProcess, 'MaximumLotPresentationQuantity', 'string');
            $resultEntries['maximumTendererAwardedLotsQuantity'] = $this->existNodo($tenderingProcess, 'MaximumTendererAwardedLotsQuantity', 'string');
            $resultEntries['deadLineEndDate'] = $this->existNodo($tenderingProcess->TenderSubmissionDeadlinePeriod, 'EndDate', 'string');
            $resultEntries['deadLineEndTime'] = $this->existNodo($tenderingProcess->TenderSubmissionDeadlinePeriod, 'EndTime', 'string');
            $resultEntries['deadLineDescription'] = $this->existNodo($tenderingProcess->TenderSubmissionDeadlinePeriod, 'Description', 'string');
            $resultEntries['auctionTerms'] = $this->existNodo($tenderingProcess->AuctionTerms, 'AuctionConstraintIndicator', 'string');
            $resultEntries['LotsCombinationContractingAuthorityRights'] = $this->existNodo($tenderingProcess, 'LotsCombinationContractingAuthorityRights', 'string');
            $resultEntries['documentAvailablePeriod_EndDate'] = $this->existNodo($tenderingProcess->DocumentAvailabilityPeriod, 'EndDate', 'string');
            $resultEntries['documentAvailablePeriod_EndTime'] = $this->existNodo($tenderingProcess->DocumentAvailabilityPeriod, 'EndTime', 'string');
        }
        //$resultFinal = $this->array_remove_empty($resultEntries);
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function nodoLegalDoc($xml)
    {
        $resultEntries = array();
        $legalDocumentReference = $xml->ContractFolderStatus->LegalDocumentReference;

        if (isset($legalDocumentReference)) {

            for ($i = 0; $i < count($legalDocumentReference); $i++) {
                $resultEntries[$i]['idDoc'] = $this->existNodo($legalDocumentReference[$i], 'ID', 'string');
                $resultEntries[$i]['attachment'] = $this->existNodo($legalDocumentReference[$i]->Attachment->ExternalReference, 'URI', 'string');
                $resultEntries[$i]['documentHash'] = $this->existNodo($legalDocumentReference[$i]->Attachment->ExternalReference, 'DocumentHash', 'string');
            }

        }
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function nodoTechnicalDocumentReference($xml)
    {
        $resultEntries = array();
        $technicalDocumentReference = $xml->ContractFolderStatus->TechnicalDocumentReference;

        if (isset($technicalDocumentReference)) {

            for ($i = 0; $i < count($technicalDocumentReference); $i++) {
                $resultEntries[$i]['idDoc'] = $this->existNodo($technicalDocumentReference[$i], 'ID', 'string');
                $resultEntries[$i]['attachment'] = $this->existNodo($technicalDocumentReference[$i]->Attachment->ExternalReference, 'URI', 'string');
                $resultEntries[$i]['documentHash'] = $this->existNodo($technicalDocumentReference[$i]->Attachment->ExternalReference, 'DocumentHash', 'string');
            }

        }
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function nodoAdditionalDocumentReference($xml)
    {
        $resultEntries = array();
        $additionalDocumentReference = $xml->ContractFolderStatus->AdditionalDocumentReference;

        if (isset($additionalDocumentReference)) {

            for ($i = 0; $i < count($additionalDocumentReference); $i++) {
                $resultEntries[$i]['idDoc'] = $this->existNodo($additionalDocumentReference[$i], 'ID', 'string');
                $resultEntries[$i]['attachment'] = $this->existNodo($additionalDocumentReference[$i]->Attachment->ExternalReference, 'URI', 'string');
                $resultEntries[$i]['documentHash'] = $this->existNodo($additionalDocumentReference[$i]->Attachment->ExternalReference, 'DocumentHash', 'string');
            }

        }
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function nodoValidNoticeInfo($xml)
    {
        $resultEntries = array();
        $validNoticeInfo = $xml->ContractFolderStatus->ValidNoticeInfo;

        if (isset($validNoticeInfo)) {
            for ($i = 0; $i < count($validNoticeInfo); $i++) {
                $resultEntries[$i]['noticeTypeCode'] = $this->existNodo($validNoticeInfo[$i], 'NoticeTypeCode', 'string');
                $resultEntries[$i]['publicationMediaName'] = $this->existNodo($validNoticeInfo[$i]->AdditionalPublicationStatus, 'PublicationMediaName', 'string');

                if (isset($validNoticeInfo[$i]->AdditionalPublicationStatus)) {
                    for ($j = 0; $j < count($validNoticeInfo[$i]->AdditionalPublicationStatus->AdditionalPublicationDocumentReference); $j++) {

                        $resultEntries[$i]['fechas'][$j]['fechas'] = $this->existNodo($validNoticeInfo[$i]->AdditionalPublicationStatus->AdditionalPublicationDocumentReference[$j], 'IssueDate', 'string');
                        if ($validNoticeInfo[$i]->AdditionalPublicationStatus->AdditionalPublicationDocumentReference[$j]->DocumentTypeCode) {
                            $resultEntries[$i]['documento'][$j]['documento'] = $this->existNodo($validNoticeInfo[$i]->AdditionalPublicationStatus->AdditionalPublicationDocumentReference[$j]->Attachment->ExternalReference, 'URI', 'string');
                            $resultEntries[$i]['documento'][$j]['filename'] = $this->existNodo($validNoticeInfo[$i]->AdditionalPublicationStatus->AdditionalPublicationDocumentReference[$j]->Attachment->ExternalReference, 'FileName', 'string');

                        }
                    }
                }
            }
        }

        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultEntries;
    }

    private function nodoGeneralDocuments($xml)
    {
        $resultEntries = array();
        $generalDocument = $xml->ContractFolderStatus->GeneralDocument->GeneralDocumentDocumentReference;

        if (isset($generalDocument)) {

            for ($i = 0; $i < count($generalDocument); $i++) {
                $resultEntries[$i]['idDoc'] = $this->existNodo($generalDocument[$i], 'ID', 'string');
                $resultEntries[$i]['attachment'] = $this->existNodo($generalDocument[$i]->Attachment->ExternalReference, 'URI', 'string');
                $resultEntries[$i]['fileName'] = $this->existNodo($generalDocument[$i]->Attachment->ExternalReference, 'FileName', 'string');
            }

        }
        $resultFinal = $this->checkArrayValuesEmpty($resultEntries);
        return $resultFinal;
    }

    private function existNodo($nodo, $nodoHijo, $tipo)
    {

        if (isset($nodo) && @count($nodo) > 0) {
            return $this->switchTipo($tipo, $nodo->{$nodoHijo});
        } else {
            return "";
        }
    }

    private function existAttribute($nodo, $nodoHijo, $tipo, $nombreAttributo)
    {
        $nodoFinal = $nodo->{$nodoHijo};
        if (isset($nodoFinal) && !empty($nodoFinal)) {
            //if (@count($nodo->{$nodoHijo}) > 0) {
            return $this->switchTipoAttribute($tipo, $nodo->{$nodoHijo}, $nombreAttributo);
            //}
        } else {
            return "";
        }
    }

    private function switchTipo($tipo, $nodo)
    {
        switch ($tipo) {
            case 'string':
                return (string) $nodo;
                break;
            case 'int':
                return (int) $nodo;
                break;
            case 'array':
                return (array) $nodo;
                break;
        }
    }

    private function switchTipoAttribute($tipo, $nodo, $attributo)
    {
        switch ($tipo) {
            case 'string':
                return (string) $nodo->attributes()[$attributo];
                break;
        }
    }

    private function recurseXML($xml, $parent = "")
    {
        //TODO: 01-02-22- me he quedado acabando esto
        $child_count = 0;
        $result = array();
        $mapaNodo = array();
        foreach ($xml as $key => $value) {
            $child_count++;
            if ($this->RecurseXML($value, $parent . "." . $key) == 0) // no childern, aka "leaf node"
            {
                //print($parent . "." . (string) $key . " = " . (string) $value . "<BR>\n");

            }
        }
        return $child_count;
    }

    public function array_remove_empty($haystack)
    {
        foreach ($haystack as $key => $value) {
            if (is_array($value)) {
                $haystack[$key] = $this->array_remove_empty($haystack[$key]);
            }

            if (empty($haystack[$key])) {
                unset($haystack[$key]);
            }
        }

        return $haystack;
    }

    public function checkArrayValuesEmpty($arrayCheck)
    {
        $valuesTotales = count($arrayCheck);
        $valuesVacios = 0;
        foreach ($arrayCheck as $key => $value) {

            if (is_array($value)) {
                $arrayCheck[$key] = $this->checkArrayValuesEmpty($arrayCheck[$key]);
            } else {
                $value = trim($value);
                if (empty($arrayCheck[$key])) {
                    $valuesVacios++;
                }
            }

        }

        if ($valuesTotales == $valuesVacios) {
            $this->array_remove_empty($arrayCheck);
        } else {
            return $arrayCheck;
        }
    }

}

/* End of file ParserFile.php */
/* Location: ./application/libraries/ParserFile.php */
