<?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);

                foreach ($datosArchivo as $row) {
                    $idLicitacion = $this->setInicioLicitacion($row['general']);

                    if ($idLicitacion['result']) {
                        $this->idLicitacion = $idLicitacion['id'];

                        $this->setDatosSingular($row, "contractInfo", "BRUTO_contract_folder", $this->idLicitacion, "ContractInfo", "id_ajena_licitacion");

                        $this->setDatosSingular($row, "tenderingProcess", "BRUTO_tendering_process", $this->idLicitacion, "TenderingProcess", "id_ajena_licitacion");

                        $this->setProcurementProject($row['procurementProject']);

                        $this->setProcurementProjectLot($row['procurementProjectLot']);

                        $this->setTenderingTerms($row['tenderingTerms']);

                        $this->setLocatedContractingParty($row['locatedContractingParty']);

                        $this->setParty($row['party']);

                        $this->setValidNoticeInfo($row['validNoticeInfo']);

                        $this->setDatosMultiples($row, "tenderingResult", "BRUTO_tender_result", $this->idLicitacion, "TenderResult", "id_ajena_licitacion");

                        $this->setDatosMultiples($row, "legalDocs", "BRUTO_legal_documents", $this->idLicitacion, "LegalDocs", 'id_ajena_licitacion');

                        $this->setDatosMultiples($row, "technicalDocs", "BRUTO_technical_documents", $this->idLicitacion, "TechnicalDocs", "id_ajena_licitacion");

                        $this->setDatosMultiples($row, "generalDocs", "BRUTO_general_documents", $this->idLicitacion, "GeneralDocs", "id_ajena_licitacion");

                        $this->setDatosMultiples($row, "additionalDocs", "BRUTO_additional_documents", $this->idLicitacion, "AdditionalDocs", "id_ajena_licitacion");
                    }
                }
            }
        }

        return;
    }

    private function setInicioLicitacion($datosInicioLicitacion): array
    {
        $result = array("result" => false, "id" => 0);
        $datosInicioLicitacion['fecha_creacion_log'] = $this->fechaInicioParser;
        $insertLicitacion = $this->CI->Parser_model->setInicioLicitacion($datosInicioLicitacion);

        if ($insertLicitacion) {
            $result = array("result" => true, "id" => $datosInicioLicitacion['id_licitacion']);
            guardar_log($this->nombreLog, "Licitacion ID " . $datosInicioLicitacion['id_licitacion'] . " - BBDD Licitación ID " . $insertLicitacion, "false");
        } else {
            $result = array("result" => true, "id" => 0);
            guardar_log($this->nombreLog, "Licitacion ID " . $datosInicioLicitacion['id_licitacion'], "false", 2);
        }

        return $result;
    }

    private function setLocatedContractingParty($contractInfo): void
    {
        $locatedContractingPartyId = $this->setDatosSingular($contractInfo, "locatedContractingParty", "BRUTO_located_contracting_party", $this->idLicitacion, "locatedContractingParty", "id_ajena_licitacion");

        $this->setDatosMultiples($contractInfo, "activity", "BRUTO_located_contracting_party_activity", $locatedContractingPartyId, "locatedContractingParty_Activity", "id_ajena_lcp");

    }

    private function setParty($partyInfo): void
    {
        $partyId = $this->setDatosSingular($partyInfo, "party", "BRUTO_party", $this->idLicitacion, "PartyInfo", "id_ajena_licitacion");

        $this->setDatosMultiples($partyInfo, "partyIdentification", "BRUTO_party_party_idenfitication", $partyId, "PartyInfo_PartyIdentification", "id_ajena_party");

    }

    private function setProcurementProject($procurementInfo): void
    {
        $procurementProjectId = $this->setDatosSingular($procurementInfo, "budget", "BRUTO_procurement_project", $this->idLicitacion, "ProcurementProject", "id_ajena_licitacion");

        $this->setDatosMultiples($procurementInfo, "itemClass", "BRUTO_procurement_project_itemClass", $procurementProjectId, "ProcurementProject_ItemClass", "id_ajena_pp");
    }

    private function setProcurementProjectLot($procurementLotInfo): void
    {
        $resultInsert = 0;

        if (!empty($procurementLotInfo)) {
            $aux = 0;
            foreach ($procurementLotInfo as $row) {
                $setInsert = array();
                $setInsert[$aux] = $row;
                $setInsert[$aux]['id_ajena_licitacion'] = $this->idLicitacion;
                $setInsert[$aux]["fecha_creacion_log"] = $this->fechaInicioParser;
                unset($setInsert[$aux]['itemClassification']);

                if (!empty($setInsert)) {
                    $resultInsert = insertBucle($setInsert, "BRUTO_procurement_project_lot", $this->nombreLog);
                    if (array_key_exists('itemClassification', $row)) {
                        $this->setDatosMultiples($row, "itemClassification", "BRUTO_procurement_project_lot_item", $resultInsert, "ProcurementLotItem", "id_ajena_ppl");
                    }
                }
                $aux++;
            }

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

    private function setTenderingTerms($tenderingTermsInfo): void
    {

        $resultInsert = 0;

        if (!empty($tenderingTermsInfo)) {

            $setInsert = array();
            $setInsert['tenderingTerms'][0] = $tenderingTermsInfo[0];
            $setInsert['tenderingTerms'][0]['id_ajena_licitacion'] = $this->idLicitacion;

            if (!empty($setInsert)) {
                $resultInsert = insertBucle($setInsert['tenderingTerms'], "BRUTO_tendering_terms", $this->nombreLog);

                if ($resultInsert > 0) {
                    $this->setDatosMultiples($tenderingTermsInfo, 1, "BRUTO_tendering_terms_awarding_terms", $resultInsert, "TenderingTermsAwardingTerms", "id_ajena_tt");

                    $this->setDatosMultiples($tenderingTermsInfo, 2, "BRUTO_tendering_terms_qualification_request", $resultInsert, "TenderingTermsQualificationRequest", "id_ajena_tt");

                    $this->setDatosMultiples($tenderingTermsInfo, 3, "BRUTO_tendering_terms_financial_evaluation", $resultInsert, "TenderingTermsFinancialEvaluation", "id_ajena_ttfe");

                    $this->setDatosMultiples($tenderingTermsInfo, 4, "BRUTO_tendering_terms_specific_terms", $resultInsert, "TenderingTermsSpecificRequirement", "id_ajena_tt");
                }
            }

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

    private function setValidNoticeInfo($validNoticeInfo): void
    {

        $resultInsert = 0;

        if (!empty($validNoticeInfo)) {
            $aux = 0;
            foreach ($validNoticeInfo as $row) {
                $setInsert = array();
                $setInsert[$aux] = $row;
                $setInsert[$aux]['id_ajena_licitacion'] = $this->idLicitacion;

                unset($setInsert[$aux]['documento']);
                unset($setInsert[$aux]['fechas']);

                if (!empty($setInsert)) {
                    $resultInsert = insertBucle($setInsert, "BRUTO_valid_notice_info", $this->nombreLog);

                    if ($resultInsert > 0) {
                        $this->setDatosMultiples($row, "documento", "BRUTO_valid_notice_info_documento", $resultInsert, "validNoticeInfoFechas", "id_ajena_vni");

                        $this->setDatosMultiples($row, "fechas", "BRUTO_valid_notice_info_fecha", $resultInsert, "validNoticeInfoDocumento", "id_ajena_vni");
                    }
                }
                $aux++;
            }

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

    private function setDatosSingular($arrayDatos, $arrayKey, $tabla, $idAjena = 0, $nodoLog, $txtIdAjena): int
    {
        $insertedId = 0;
        if (!empty($arrayDatos) && array_key_exists($arrayKey, $arrayDatos)) {
            $arrayInsertar = array();

            $arrayInsertar[0] = $arrayDatos[$arrayKey];

            if ($idAjena > 0) {
                $arrayInsertar[0][$txtIdAjena] = $idAjena;
                $arrayInsertar[0]["fecha_creacion_log"] = $this->fechaInicioParser;
            }
            unset($arrayInsertar[0]['id']);

            $insertedId = insertBucle($arrayInsertar, $tabla, $this->nombreLog);

            if ($insertedId == 0) {
                guardar_log($this->nombreLog, $nodoLog . " Fallido", "false");
            } else {
                guardar_log($this->nombreLog, $nodoLog . " Finalizada Inserción", "false");
            }
        } else {
            guardar_log($this->nombreLog, $nodoLog . " vacio", "false");
        }

        return $insertedId;
    }

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

        if (array_key_exists($arrayKey, $arrayDatos)) {
            if (!empty($arrayDatos[$arrayKey])) {
                $aux = 0;
                foreach ($arrayDatos[$arrayKey] as $row) {
                    $setInsert[$aux] = $row;

                    if ($idAjena > 0) {
                        $setInsert[$aux][$txtIdAjena] = $idAjena;
                        $setInsert[$aux]["fecha_creacion_log"] = $this->fechaInicioParser;
                        unset($setInsert[$aux]['id']);
                    }

                    $aux++;
                }

                if (!empty($setInsert)) {
                    $resultInsert = insertBucle($setInsert, $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 */
