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

class Parserdatabasebruto
{
    protected $idLicitacion = 0;
    protected $fechaInicioParser = "";
    protected $CI;
    protected $nombreLog = "";

    public function __construct()
    {
        $this->CI = &get_instance();
        $this->CI->load->model("Parser_model");
    }

    public function setDatosParser($arrayDatosSucios, $fecha, $datosPerfil)
    {
        $this->fechaInicioParser = $fecha;
        $this->nombreLog = "setLicitacion__" . $datosPerfil->prefijos_tablas . "__" . $this->fechaInicioParser;

        if (!empty($arrayDatosSucios)) {

            foreach ($arrayDatosSucios as $nombreArchivo => $datosArchivo) {
                guardar_log($this->nombreLog, "ARCHIVO ---" . $nombreArchivo, false);

                $this->setDatosMultiples($datosArchivo, "general", "in_datos_iniciales", "DatosIniciales");

                $this->setDatosMultiples($datosArchivo, "contractInfo", "in_contract_folder", "ContractInfo");

                $this->setDocumentosSingle($datosArchivo, "tenderingProcess", ["in_tendering_process", "config_nivel_tendering_process"], "TenderingProcess");

                $this->setProcurementProjectArray($datosArchivo);

                $this->setProcurementProjectLotArray($datosArchivo);

                $this->setTenderingTerms($datosArchivo);

                $this->setLocatedContractingParty($datosArchivo); //, "locatedContractingParty", "in_located_contracting_party", "locatedContractingParty");

                $this->setParty($datosArchivo);

                $this->setValidNoticeInfo($datosArchivo);

                $this->setInsertArryByArray($datosArchivo, "tenderingResult", ["in_tender_result", "config_nivel_tender_result"], "TenderResult");

                $this->setDocumentosSingle($datosArchivo, "legalDocs", ["in_legal_documents", "config_nivel_legal_docs"], "legalDocs");

                $this->setDocumentosSingle($datosArchivo, "technicalDocs", ["in_technical_documents", "config_nivel_technical_docs"], "TechnicalDocs");

                $this->setInsertArryByArray($datosArchivo, "generalDocs", ["in_general_documents", "config_nivel_general_docs"], "GeneralDocs");

                $this->setInsertArryByArray($datosArchivo, "additionalDocs", ["in_additional_documents", "config_nivel_additional_docs"], "additionalDocs");
            }

            $arrayDatosSucios = array();
        }
    }

    private function setProcurementProjectArray($procurementProjectData)
    {
        $result = array();
        $coleccionMapaProcProject = array();
        $countColeccionProcProject = 0;
        $mapaDatos = $this->CI->Parser_model->getMapaByTabla("config_nivel_procurement_project");

        foreach ($mapaDatos['datos'] as $dataField) {
            $coleccionMapaProcProject[] = $dataField->campo_bbdd;
        }
        $countColeccionProcProject = count($coleccionMapaProcProject);

        foreach ($procurementProjectData['procurementProject'] as $rowData) {
            $budget = $rowData['budget'];
            if ($countColeccionProcProject > count($budget)) {
                foreach ($coleccionMapaProcProject as $dataField) {
                    if (!array_key_exists($dataField, $budget)) {
                        $budget[$dataField] = "";
                    }
                }
            }

            if (array_key_exists('itemClass', $rowData)) {
                foreach ($rowData['itemClass'] as $itemClass) {
                    $result['itemClass'][] = $itemClass;
                }
            }

            $result['budget'][] = $budget;
        }

        $this->setDatosMultiples($result, "budget", "in_procurement_project", "ProcurementProject");

        $this->setDatosMultiples($result, "itemclass", "in_procurement_project_itemClass", "ProcurementProject_ItemClass");
    }

    private function setProcurementProjectLotArray($datosToSet)
    {
        $result = array();
        $coleccionMapa = array();
        $countColeccion = 0;
        $mapaDatos = $this->CI->Parser_model->getMapaByTabla("config_nivel_procurement_project_lot");

        foreach ($mapaDatos['datos'] as $dataField) {
            $coleccionMapa[] = $dataField->campo_bbdd;
        }
        $countColeccion = count($coleccionMapa);

        foreach ($datosToSet['procurementProjectLot'] as $rowData) {
            if ($rowData != null) {

                foreach ($rowData['lot'] as $loteIndividual) {
                    $procurementProjectLot = $loteIndividual;
                    if ($countColeccion > count($procurementProjectLot)) {
                        foreach ($coleccionMapa as $dataField) {
                            if (!array_key_exists($dataField, $procurementProjectLot)) {
                                $procurementProjectLot[$dataField] = "";
                            }
                        }
                    }
                    $result['procurementProjectLot'][] = $procurementProjectLot;
                }

                if (array_key_exists('itemClassification', $rowData)) {
                    foreach ($rowData['itemClassification'] as $itemClass) {
                        $result['itemClassification'][] = $itemClass;
                    }
                }
            }
        }

        $this->setDatosMultiples($result, "procurementProjectLot", "in_procurement_project_lot", "procurementProjectLot");

        $this->setDatosMultiples($result, "itemClassification", "in_procurement_project_lot_item", "procurementProjectLot_itemClassification");
    }

    private function setTenderingTerms($datosToSet)
    {
        $result = array();
        $coleccionMapa = array();
        $countColeccion = 0;
        $mapaDatos = $this->CI->Parser_model->getMapaByTabla("config_nivel_tendering_terms");

        foreach ($mapaDatos['datos'] as $dataField) {
            $coleccionMapa[] = $dataField->campo_bbdd;
        }
        $countColeccion = count($coleccionMapa);

        foreach ($datosToSet['tenderingTerms'] as $rowData) {
            if ($rowData != null) {

                if (array_key_exists('tenderingTerm', $rowData)) {
                    $tenderTerms = $rowData['tenderingTerm'];
                    if ($countColeccion > count($tenderTerms)) {
                        foreach ($coleccionMapa as $dataField) {
                            if (!array_key_exists($dataField, $tenderTerms)) {
                                $tenderTerms[$dataField] = "";
                            }
                        }
                    }
                    $result['tenderingTerm'][] = $tenderTerms;
                }

                if (array_key_exists('awardingCriteria', $rowData)) {
                    foreach ($rowData['awardingCriteria'] as $itemClass) {
                        $result['awardingCriteria'][] = $itemClass;
                    }
                }

                if (array_key_exists('TendererQualificationRequest', $rowData)) {
                    foreach ($rowData['TendererQualificationRequest'] as $itemClass) {
                        $result['TendererQualificationRequest'][] = $itemClass;
                    }
                }

                if (array_key_exists('FinancialEvaluationCriteria', $rowData)) {
                    foreach ($rowData['FinancialEvaluationCriteria'] as $itemClass) {
                        $result['FinancialEvaluationCriteria'][] = $itemClass;
                    }
                }

                if (array_key_exists('SpecificTendererRequirement', $rowData)) {
                    foreach ($rowData['SpecificTendererRequirement'] as $itemClass) {
                        $result['SpecificTendererRequirement'][] = $itemClass;
                    }
                }
            }
        }

        $this->setDatosMultiples($result, "tenderingTerm", "in_tendering_terms", "tenderingTerm");

        $this->setDatosMultiples($result, "awardingCriteria", "in_tendering_terms_awarding_terms", "awardingCriteria");

        $this->setDatosMultiples($result, "FinancialEvaluationCriteria", "in_tendering_terms_financial_evaluation", "FinancialEvaluationCriteria");

        $this->setDatosMultiples($result, "TendererQualificationRequest", "in_tendering_terms_qualification_request", "TendererQualificationRequest");

        $this->setDatosMultiples($result, "SpecificTendererRequirement", "in_tendering_terms_specific_terms", "SpecificTendererRequirement");
    }

    private function setLocatedContractingParty($datosToSet)
    {
        $result = array();
        $coleccionMapa = array();
        $countColeccion = 0;
        $mapaDatos = $this->CI->Parser_model->getMapaByTabla("config_nivel_located_contracting_party");

        foreach ($mapaDatos['datos'] as $dataField) {
            $coleccionMapa[] = $dataField->campo_bbdd;
        }
        $countColeccion = count($coleccionMapa);

        foreach ($datosToSet['locatedContractingParty'] as $rowData) {
            $locatedContractingParty = $rowData['locatedContractingParty'];
            if ($countColeccion > count($locatedContractingParty)) {
                foreach ($coleccionMapa as $dataField) {
                    if (!array_key_exists($dataField, $locatedContractingParty)) {
                        $locatedContractingParty[$dataField] = "";
                    }
                }
            }

            if (array_key_exists('activity', $rowData)) {
                foreach ($rowData['activity'] as $itemClass) {
                    $result['activity'][] = $itemClass;
                }
            }

            $result['locatedContractingParty'][] = $locatedContractingParty;
        }

        $this->setDatosMultiples($result, "locatedContractingParty", "in_located_contracting_party", "LocatedContractingParty");

        $this->setDatosMultiples($result, "activity", "in_located_contracting_party_activity", "LocatedContractingParty_Activity");
    }

    private function setParty($datosToSet)
    {
        $result = array();
        $coleccionMapa = array();
        $countColeccion = 0;
        $mapaDatos = $this->CI->Parser_model->getMapaByTabla("config_nivel_party");

        foreach ($mapaDatos['datos'] as $dataField) {
            $coleccionMapa[] = $dataField->campo_bbdd;
        }
        $countColeccion = count($coleccionMapa);

        foreach ($datosToSet['party'] as $rowData) {
            $party = $rowData['party'];
            if ($countColeccion > count($party)) {
                foreach ($coleccionMapa as $dataField) {
                    if (!array_key_exists($dataField, $party)) {
                        $party[$dataField] = "";
                    }
                }
            }

            if (array_key_exists('partyIdentification', $rowData)) {
                foreach ($rowData['partyIdentification'] as $itemClass) {
                    $result['partyIdentification'][] = $itemClass;
                }
            }

            $result['party'][] = $party;
        }

        $this->setDatosMultiples($result, "party", "in_party", "Party");

        $this->setDatosMultiples($result, "partyIdentification", "in_party_party_idenfitication", "Party_PartyIdentification");
    }

    private function setDocumentosSingle($datosToSet, $arrayKey, $tablasMapa, $nombreLog)
    {
        if (array_key_exists($arrayKey, $datosToSet)) {
            $result = array();
            $coleccionMapa = array();
            $countColeccion = 0;
            $mapaDatos = $this->CI->Parser_model->getMapaByTabla($tablasMapa[1]);

            foreach ($mapaDatos['datos'] as $dataField) {
                $coleccionMapa[] = $dataField->campo_bbdd;
            }
            $countColeccion = count($coleccionMapa);
            foreach ($datosToSet[$arrayKey] as $rowData) {
                if ($rowData != null) {
                    if ($countColeccion > count($rowData)) {
                        foreach ($coleccionMapa as $dataField) {
                            if (!array_key_exists($dataField, $rowData)) {
                                $resultFinal[$dataField] = "";
                            }
                        }
                    }

                    $result[$arrayKey][] = $rowData;
                }
            }

            $this->setDatosMultiples($result, $arrayKey, $tablasMapa[0], $nombreLog);
        }
    }

    private function setInsertArryByArray($datosToSet, $arrayKey, $tablasMapa, $nombreLog)
    {
        if (array_key_exists($arrayKey, $datosToSet)) {
            $result = array();
            $coleccionMapa = array();
            $countColeccion = 0;
            $mapaDatos = $this->CI->Parser_model->getMapaByTabla($tablasMapa[1]);

            foreach ($mapaDatos['datos'] as $dataField) {
                $coleccionMapa[] = $dataField->campo_bbdd;
            }
            $countColeccion = count($coleccionMapa);
            foreach ($datosToSet[$arrayKey] as $rowData) {

                if ($rowData !== null) {
                    foreach ($rowData as $documento) {

                        $aux = $documento;
                        if ($countColeccion > count($documento)) {
                            foreach ($coleccionMapa as $dataField) {
                                if (!array_key_exists($dataField, $documento)) {
                                    $aux[$dataField] = "";
                                }
                            }
                        }
                        $result[$arrayKey][] = $aux;
                    }
                }
            }

            $this->setDatosMultiples($result, $arrayKey, $tablasMapa[0], $nombreLog);
        }
    }

    private function setValidNoticeInfo($datosToSet): void
    {

        $result = array();
        $coleccionMapa = array();
        $countColeccion = 0;
        $mapaDatos = $this->CI->Parser_model->getMapaByTabla("config_nivel_valid_notice_info");

        foreach ($mapaDatos['datos'] as $dataField) {
            $coleccionMapa[] = $dataField->campo_bbdd;
        }
        $countColeccion = count($coleccionMapa);

        foreach ($datosToSet['validNoticeInfo'] as $rowData) {
            if ($rowData != null) {

                foreach ($rowData['noticeInfo'] as $loteIndividual) {
                    $procurementProjectLot = $loteIndividual;
                    if ($countColeccion > count($procurementProjectLot)) {
                        foreach ($coleccionMapa as $dataField) {
                            if (!array_key_exists($dataField, $procurementProjectLot)) {
                                $procurementProjectLot[$dataField] = "";
                            }
                        }
                    }
                    $result['noticeInfo'][] = $procurementProjectLot;
                }

                if (array_key_exists('fechas', $rowData)) {
                    foreach ($rowData['fechas'] as $itemClass) {
                        $result['fechas'][] = $itemClass;
                    }
                }

                if (array_key_exists('documento', $rowData)) {
                    foreach ($rowData['documento'] as $itemClass) {
                        $result['documento'][] = $itemClass;
                    }
                }
            }
        }

        $this->setDatosMultiples($result, "noticeInfo", "in_valid_notice_info", "ValidNoticeInfo");

        $this->setDatosMultiples($result, "fechas", "in_valid_notice_info_fecha", "ValidNoticeInfo_Fecha");

        $this->setDatosMultiples($result, "documento", "in_valid_notice_info_documento", "ValidNoticeInfo_Documento");
    }

    private function setDatosMultiples($arrayDatos, $arrayKey, $tabla, $nodoLog): void
    {
        $setInsert = array();

        $resultInsert = 0;

        if (array_key_exists($arrayKey, $arrayDatos)) {
            if (!empty($arrayDatos[$arrayKey])) {

                $resultInsert = insertBucle($arrayDatos[$arrayKey], $tabla, $this->nombreLog);

                if ($resultInsert) {
                    //$result = array("result" => true);
                    guardar_log($this->nombreLog, $nodoLog . " Finalizada Inserción", "false");
                } else {
                    //$result = array("result" => true, "id" => 0);
                    guardar_log($this->nombreLog, $nodoLog . " Fallida", "false", 2);
                }
            } else {
                guardar_log($this->nombreLog, $nodoLog . " vacio", "false");
            }
        } else {
            guardar_log($this->nombreLog, $nodoLog . " vacio", "false");
        }
    }
}

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