<?php

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

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExportXls
{
    protected $CI;
    private $filaDocumentoGeneral = 2;
    private $filaDocumentoTech = 2;
    private $filaDocumentoAdd = 2;
    private $filaDocumentoLegal = 2;
    private $filaProjectLot = 2;
    private $filaDatoLicitacion = 2;

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


    public function exportDatosCompletos()
    {
        $licitacionesResult = $this->CI->Xlsexport_model->getFullDatosUltimasInsertadas();

        $result = array();

        //$start = $this->starttime();
        if ($licitacionesResult['num_rows'] > 0) {
            $result = $this->mapearDatos($licitacionesResult);
        }
        $spreadsheet = new Spreadsheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();
        $spreadsheet->createSheet();

        $spreadsheet = $this->cabecerasOpenPlacspFirstSheet($spreadsheet);
        $spreadsheet = $this->cabecerasOpenPlacsBitacora($spreadsheet, 1);
        $spreadsheet = $this->cabecerasOpenPlacspDocumentos($spreadsheet, 11);
        $spreadsheet = $this->cabecerasOpenPlacspDocumentos($spreadsheet, 12);
        $spreadsheet = $this->cabecerasOpenPlacspDocumentos($spreadsheet, 13);
        $spreadsheet = $this->cabecerasOpenPlacspDocumentos($spreadsheet, 14);
        $spreadsheet = $this->cabeceraMediosComunicacion($spreadsheet);
        $spreadsheet = $this->cabeceraMediosComunicacionDocumentos($spreadsheet);
        $spreadsheet = $this->cabeceraTenderResult($spreadsheet);
        $spreadsheet = $this->cabeceraTipoProcedimiento($spreadsheet);
        $spreadsheet = $this->cabeceraTenderingTerms($spreadsheet);
        $spreadsheet = $this->cabeceraCriterioADjudicacion($spreadsheet);
        $spreadsheet = $this->cabeceraCriteriosFinancieros($spreadsheet);
        $spreadsheet = $this->cabeceraCriteriosTecnicos($spreadsheet);
        $spreadsheet = $this->cabeceraRequisitosParticipacion($spreadsheet);

        $spreadsheet = $this->datosCompletosHojaLicitacion($spreadsheet, $result['hoja1']);
        $spreadsheet = $this->datosCompletosHojaBitacora($spreadsheet, $result);
        $spreadsheet = $this->datosCompletosMediosPublicacion($spreadsheet, $result['validNoticeInfo']);
        $spreadsheet = $this->datosMedioPublicacion($spreadsheet, $result['validNoticeInfoDocumentos']);
        $spreadsheet = $this->datosCriterioAdjudicacion($spreadsheet, $result['tenderAwarding']);
        $spreadsheet = $this->datosCriterioEvaluacionFinanciera($spreadsheet, $result['tenderFinancial']);
        $spreadsheet = $this->datosCriterioEvaluacionTecnica($spreadsheet, $result['tenderTecnicos']);
        $spreadsheet = $this->datosRequisitosParticipacion($spreadsheet, $result['tenderQualification']);

        $spreadsheet = $this->datosCompletosDocumentosGenerales($spreadsheet, $result['generalDocs']);
        $spreadsheet = $this->datosCompletosDocumentosAdicionales($spreadsheet, $result['additDocs']);
        $spreadsheet = $this->datosCompletosDocumentosTecnicos($spreadsheet, $result['techDocs']);
        $spreadsheet = $this->datosCompletosDocumentosLegales($spreadsheet, $result['legalDocs']);
        $spreadsheet = $this->datosCompletosTipoProcedimiento($spreadsheet, $result['tenderProcess']);
        $spreadsheet = $this->datosCompletosOfertas($spreadsheet, $result['tenderingTerms']);
        $spreadsheet = $this->datosCompletosResultadoDelProcedimiento($spreadsheet, $result['tenderResult']);

        $nombreAchivo = 'Licitaciones_' . date("d-m-Y") . '.xlsx';
        $ruta = FCPATH . 'uploads/' . $nombreAchivo;

        $writer = new Xlsx($spreadsheet);


        //emailEnvioExcel();
        // Write the Excel file to filename some_excel_file.xlsx in the current directory
        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $nombreAchivo . '');
        header('Pragma: cache');
        header('Cache-Control: private');
        $writer->save($ruta);
        //$objWriter = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel2007');
        //$objWriter->save(FCPATH . 'uploads/' . $nombreAchivo);*/
    }

    public function starttime()
    {
        $r = explode(' ', microtime());
        $r = $r[1] + $r;
        return $r;
    }

    public function endtime($starttime)
    {
        $r = explode(' ', microtime());
        $r = $r[1] + $r;
        $r = round($r - $starttime, 4);
        return '<strong>Execution Time</strong>: ' . $r . ' seconds<br />';
    }

    public function mapearDatos($licitacionesResult): array
    {
        $result = array();

        foreach ($licitacionesResult['datos'] as $licitacion) {

            $result['hoja1'][$licitacion->id_licitacion]['licitacion'] = array(
                'id_licitacion' => $licitacion->id_licitacion,
                "link_uri" => $licitacion->link_uri,
                "updated" => $licitacion->updated,
                'estadoLicitacion' => $licitacion->estadoLicitacion,
            );
            $result['hoja1'][$licitacion->id_licitacion]['contract'] = array(
                "descripcion" => $licitacion->contrato_status,
                "contractFolderStatusCode" => $licitacion->contractFolderStatusCode,
                "contractFolderID" => $licitacion->contractFolderID,
            );
            $result['hoja1'][$licitacion->id_licitacion]['locatedParty'] = array(
                "contractingPartyTypeCode" => $licitacion->contractingPartyTypeCode,
                "buyerProfileURIID" => $licitacion->buyerProfileURIID,
                "tipo_administracion" => $licitacion->tipo_administracion,
                "itemClassification_attr" => $licitacion->itemClassification_attr,
            );
            $result['hoja1'][$licitacion->id_licitacion]['party'] = array(
                "partyName" => $licitacion->partyName,
                "codpostal" => $licitacion->codpostal,
                "websiteURI" => $licitacion->websiteURI,
                "city" => $licitacion->city,
                "direccion" => $licitacion->direccion,
                "contact_name" => $licitacion->contact_name,
                "contact_email" => $licitacion->contact_email,
                "partyItem" => $licitacion->partyItem,
                "tipoIdParty" => $licitacion->tipoIdParty,
            );
            $result['hoja1'][$licitacion->id_licitacion]['project'] = array(
                "name" => $licitacion->nameProject,
                "estimatedOverallContractAmount" => $licitacion->estimatedOverallContractAmount,
                "taxExclusiveAmount" => $licitacion->taxExclusiveAmount,
                "totalAmount" => $licitacion->totalAmount,
                "tipo_contrato" => $licitacion->tipo_contrato,
                "countrySubentityCode" => $licitacion->countrySubentityCode,
                "countrySubentity" => $licitacion->countrySubentity,
                "durationMesure" => $licitacion->durationMesure,
                "medida" => $licitacion->medida,
                "duracion_inicio" => $licitacion->duracion_inicio,
                "duracion_fin" => $licitacion->duracion_fin,
                "contractExtension" => $licitacion->contractExtension,

            );
            $result['hoja1'][$licitacion->id_licitacion]['tenderProcess'] = array(
                "tipoTender" => $licitacion->tipoTender,
                "contrato_sistema" => $licitacion->contrato_sistema,
                "urgency" => $licitacion->urgency,
                "submision" => $licitacion->submision,
            );
            $result['hoja1'][$licitacion->id_licitacion]['tenderTerms'] = array(
                "procurementLegislationDocumentReference" => $licitacion->procurementLegislationDocumentReference,
                "allowedSubcontractTerms" => $licitacion->allowedSubcontractTerms,
            );
        }

        $result['validNoticeInfo'] = $this->CI->Xlsexport_model->getDatosRelacionadasTablaWithoutLicitacion("global_valid_notice_info", "codice_valid_notice_info", "code", "noticeTypeCode");

        $result['validNoticeInfoDocumentos'] = $this->CI->Xlsexport_model->getTablaByFechaLog("global_valid_notice_info_documento");

        $result['projectLot'] = $this->CI->Xlsexport_model->getProjectLotItem();

        $result['techDocs'] = $this->CI->Xlsexport_model->getTablaByFechaLog("global_technical_documents");

        $result['legalDocs'] = $this->CI->Xlsexport_model->getTablaByFechaLog("global_legal_documents");

        $result['additDocs'] = $this->CI->Xlsexport_model->getTablaByFechaLog("global_additional_documents");

        $result['generalDocs'] = $this->CI->Xlsexport_model->getTablaByFechaLog("global_general_documents");

        $result['tenderProcess'] = $this->CI->Xlsexport_model->getTenderingTermsCodes();

        $result['tenderingTerms'] = $this->CI->Xlsexport_model->getDatosRelacionadasTablaWithoutLicitacion("global_tendering_terms", "codice_codigo_tipo_garantia", "code", "guaranteeTypeCode");

        $result['tenderResult'] = $this->CI->Xlsexport_model->getDatosRelacionadasTablaWithoutLicitacion("global_tender_result", "codice_tender_result", "code", "resultCode");

        $result['tenderFinancial'] = $this->CI->Xlsexport_model->getDatosRelacionadasTablaWithoutLicitacion("global_tendering_terms_financial_evaluation", "codice_tendering_terms_financial", "code", "evaluationCriteriaTypeCode");

        $result['tenderAwarding'] = $this->CI->Xlsexport_model->getTablaByFechaLog("global_tendering_terms_awarding_terms");

        $result['tenderTecnicos'] = $this->CI->Xlsexport_model->getDatosRelacionadasTablaWithoutLicitacion("global_tendering_terms_qualification_request", "codice_tendering_terms_qualification_request", "code", "evaluationCriteriaTypeCode");

        $result['tenderQualification'] = $this->CI->Xlsexport_model->getDatosRelacionadasTablaWithoutLicitacion("global_tendering_terms_specific_terms", "codice_tendering_terms_specific_terms", "code", "evaluationCriteriaTypeCode");

        return $result;
    }

    private function datosCompletosHojaLicitacion($spreadsheet, $datosLicitacion)
    {

        $sheet = $spreadsheet->getSheet(0);
        $sheet->setTitle("Datos Licitación");
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );

        //Primera Publicacion
        $contador = 0;
        foreach ($datosLicitacion as $row) {
            $contador++;
            $primeraPublicacion = $this->primeraPublicacion($row['licitacion']['id_licitacion']);

            $updated = $this->formatFechas($row['licitacion']['updated']);

            $sheet->getStyle("A1:AJ1")->applyFromArray($styleArr);
            $sheet->setCellValue('A' . $this->filaDatoLicitacion, $row['licitacion']['id_licitacion']);
            $sheet->setCellValue('B' . $this->filaDatoLicitacion, $row['licitacion']['link_uri']);
            $sheet->setCellValue('C' . $this->filaDatoLicitacion, $updated);
            $sheet->getStyle('C' . $this->filaDatoLicitacion)
                ->getNumberFormat()
                ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME);
            $sheet->setCellValue('D' . $this->filaDatoLicitacion, $row['licitacion']['estadoLicitacion']);
            $sheet->setCellValue('E' . $this->filaDatoLicitacion, $primeraPublicacion);
            $sheet->getStyle('E' . $this->filaDatoLicitacion)
                ->getNumberFormat()
                ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
            $sheet->setCellValue('F' . $this->filaDatoLicitacion, $row['contract']['descripcion']);
            $sheet->setCellValue('G' . $this->filaDatoLicitacion, $row['contract']['contractFolderID']);
            $sheet->setCellValue('H' . $this->filaDatoLicitacion, $row['project']['name']);
            $sheet->setCellValue('I' . $this->filaDatoLicitacion, $row['project']['estimatedOverallContractAmount']);
            $sheet->getStyle('I' . $this->filaDatoLicitacion)
                ->getNumberFormat()
                ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_ACCOUNTING_EUR);
            $sheet->setCellValue('J' . $this->filaDatoLicitacion, $row['project']['taxExclusiveAmount']);
            $sheet->getStyle('J' . $this->filaDatoLicitacion)
                ->getNumberFormat()
                ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_ACCOUNTING_EUR);

            $sheet->setCellValue('K' . $this->filaDatoLicitacion, $row['locatedParty']['itemClassification_attr']);
            $sheet->setCellValue('L' . $this->filaDatoLicitacion, $row['project']['tipo_contrato']);
            $sheet->setCellValue('M' . $this->filaDatoLicitacion, $row['project']['countrySubentity']);
            $sheet->setCellValue('N' . $this->filaDatoLicitacion, $row['party']['partyName']);
            $sheet->setCellValue('O' . $this->filaDatoLicitacion, ($row['party']['tipoIdParty'] == "DIR3") ? $row['party']['partyItem'] : "");
            $sheet->setCellValue('P' . $this->filaDatoLicitacion, $row['locatedParty']['buyerProfileURIID']);
            $sheet->setCellValue('Q' . $this->filaDatoLicitacion, $row['locatedParty']['tipo_administracion']);
            $sheet->setCellValue('R' . $this->filaDatoLicitacion, $row['party']['codpostal']);
            $sheet->setCellValue('S' . $this->filaDatoLicitacion, $row['tenderProcess']['tipoTender']);
            $sheet->setCellValue('T' . $this->filaDatoLicitacion, $row['tenderProcess']['contrato_sistema']);
            $sheet->setCellValue('U' . $this->filaDatoLicitacion, $row['tenderProcess']['urgency']);
            $sheet->setCellValue('V' . $this->filaDatoLicitacion, $row['tenderProcess']['submision']);
            $sheet->setCellValue('W' . $this->filaDatoLicitacion, $row['tenderTerms']['procurementLegislationDocumentReference']);
            $sheet->setCellValue('X' . $this->filaDatoLicitacion, $row['tenderTerms']['allowedSubcontractTerms']);
            $sheet->setCellValue('Y' . $this->filaDatoLicitacion, $row['project']['durationMesure']);
            $sheet->setCellValue('Z' . $this->filaDatoLicitacion, $row['project']['medida']);
            $sheet->setCellValue('AA' . $this->filaDatoLicitacion, $this->formatFechas($row['project']['duracion_inicio']));
            $sheet->getStyle('AA' . $this->filaDatoLicitacion)
                ->getNumberFormat()
                ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
            $sheet->setCellValue('AB' . $this->filaDatoLicitacion, $this->formatFechas($row['project']['duracion_fin']));
            $sheet->getStyle('AB' . $this->filaDatoLicitacion)
                ->getNumberFormat()
                ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
            $sheet->setCellValue('AC' . $this->filaDatoLicitacion, $row['project']['contractExtension']);
            $sheet->setCellValue('AD' . $this->filaDatoLicitacion, $row['party']['websiteURI']);
            $sheet->setCellValue('AE' . $this->filaDatoLicitacion, $row['party']['city']);
            $sheet->setCellValue('AF' . $this->filaDatoLicitacion, $row['party']['direccion']);
            $sheet->setCellValue('AG' . $this->filaDatoLicitacion, $row['party']['contact_name']);
            $sheet->setCellValue('AH' . $this->filaDatoLicitacion, $row['party']['contact_email']);
            $this->filaDatoLicitacion++;
        }

        return $spreadsheet;
    }

    private function formatFechas($fecha)
    {
        $fechaFinal = "";

        if ($fecha != "0000-00-00" && $fecha != "0000-00-00 00:00:00") {
            $fechaFormat = new DateTime($fecha);
            $fechaFinal = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($fechaFormat);
        } else if ($fecha === "0000-00-00") {
            //$fechaFinal = "00/00/0000";
            $fechaFinal = "";
        } else if ($fecha === "0000-00-00 00:00:00") {
            //$fechaFinal = "00/00/0000 00:00";
            $fechaFinal = "";
        }

        return $fechaFinal;
    }

    private function primeraPublicacion($idLicitacion)
    {
        $result = "";

        $fechasPublicaciones = $this->CI->Xlsexport_model->getFechasPublicadas($idLicitacion);

        if ($fechasPublicaciones['num_rows'] > 0) {
            $primeraFechaFormat = new Datetime($fechasPublicaciones['datos']->fecha);
            $result = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($primeraFechaFormat);
        }
        return $result;
    }

    private function datosCompletosHojaBitacora($spreadsheet, $datosLicitacion)
    {
        $sheet = $spreadsheet->getSheet(1);
        $sheet->setTitle("Bitacora");
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:F1")->applyFromArray($styleArr);
        $contador = 0;
        foreach ($datosLicitacion['projectLot']['datos'] as $bitacora) {
            $contador++;
            $sheet->SetCellValue('A' . $this->filaProjectLot, $bitacora['id_ajena_licitacion']);
            $sheet->SetCellValue('B' . $this->filaProjectLot, $bitacora['name']);
            $sheet->setCellValue('C' . $this->filaProjectLot, $bitacora['idProcurementLot']);
            $sheet->SetCellValue('D' . $this->filaProjectLot, $bitacora['taxExclusiveAmount']);
            $sheet->SetCellValue('E' . $this->filaProjectLot, $bitacora['countrySubentity']);
            $sheet->SetCellValue('F' . $this->filaProjectLot, $bitacora['itemClassification_attr']);
            $this->filaProjectLot++;
        }
        return $spreadsheet;
    }

    private function datosCompletosMediosPublicacion($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(2);
        $sheet->setTitle("Medios de publicación");

        if ($datos['num_rows'] > 0) {
            $contador = 0;
            $aux = 2;
            foreach ($datos['datos'] as $datos) {
                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['code_desc']);
                $sheet->SetCellValue('C' . $aux, $datos['publicationMediaName']);
                $aux++;
            }
        }

        return $spreadsheet;
    }

    private function datosMedioPublicacion($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(3);
        $sheet->setTitle("Documentos Medios Comm");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $row) {
                $contador++;
                $sheet->SetCellValue('A' . $aux, $row['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $row['documento']);
                $sheet->SetCellValue('C' . $aux, $row['filename']);

                $aux++;
            }
        }
        return $spreadsheet;
    }

    private function datosCompletosResultadoDelProcedimiento($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(4);
        $sheet->setTitle("Resultado del Procedimiento");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {
                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['code_desc']);
                $sheet->SetCellValue('C' . $aux, $datos['description']);
                $sheet->SetCellValue('D' . $aux, $this->formatFechas($datos['awardDate']));
                $sheet->getStyle('D' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
                $sheet->SetCellValue('E' . $aux, $datos['receivedTenderQuantity']);
                $sheet->SetCellValue('F' . $aux, $datos['lowerTenderAmount']);
                $sheet->getStyle('F' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_ACCOUNTING_EUR);
                $sheet->SetCellValue('G' . $aux, $datos['higherTenderAmount']);
                $sheet->getStyle('G' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_ACCOUNTING_EUR);
                $sheet->SetCellValue('H' . $aux, $datos['abnormallyLowTendersIndicator']);
                //$sheet->SetCellValue('I' . $aux, $datos['startDate']);
                $sheet->SetCellValue('I' . $aux, $this->formatFechas($datos['startDate']));
                $sheet->getStyle('I' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME);
                $sheet->SetCellValue('J' . $aux, $datos['smeawardedIndicator']);
                $sheet->SetCellValue('K' . $aux, $datos['contract_id']);
                $sheet->SetCellValue('L' . $aux, $this->formatFechas($datos['contract_issueDate']));
                $sheet->getStyle('L' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME);
                $sheet->SetCellValue('M' . $aux, $datos['partyIdentification']);
                $sheet->SetCellValue('N' . $aux, $datos['partyName']);
                $sheet->SetCellValue('O' . $aux, $datos['TaxExclusiveAmount']);
                $sheet->getStyle('O' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_ACCOUNTING_EUR);

                $aux++;
            }
        }
        return $spreadsheet;
    }

    private function datosCompletosTipoProcedimiento($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(5);
        $sheet->setTitle("Tipo Procedimiento");

        //$datos = $this->Xlsexport_model->getTenderProcessRelacion();
        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {

                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['tipoTender']);
                $sheet->SetCellValue('C' . $aux, $datos['urgency']);
                $sheet->SetCellValue('D' . $aux, $datos['contrato_sistema']);
                $sheet->SetCellValue('E' . $aux, $datos['partPresentationCode']);
                $sheet->SetCellValue('F' . $aux, $datos['submision']);
                $sheet->SetCellValue('G' . $aux, $datos['maximumLotPresentationQuantity']);
                $sheet->SetCellValue('H' . $aux, $datos['maximumTendererAwardedLotsQuantity']);
                $sheet->SetCellValue('I' . $aux, $datos['lotsCombinationContractingAuthorityRights']);
                $sheet->SetCellValue('J' . $aux, $this->formatFechas($datos['deadLineEndDate']));
                $sheet->getStyle('J' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
                $sheet->SetCellValue('K' . $aux, $datos['deadLineEndTime']);
                $sheet->SetCellValue('L' . $aux, $datos['deadLineDescription']);
                $sheet->SetCellValue('M' . $aux, $datos['auctionTerms']);
                $sheet->SetCellValue('N' . $aux, $this->formatFechas($datos['documentAvailablePeriod_EndDate']));
                $sheet->getStyle('N' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
                $sheet->SetCellValue('O' . $aux, $datos['documentAvailablePeriod_EndTime']);
                $sheet->getStyle('O' . $aux)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);

                $aux++;
            }
        }

        return $spreadsheet;
    }

    private function datosCompletosOfertas($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(6);
        $sheet->setTitle("Ofertas");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {

                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['variantConstraintIndicator']);
                $sheet->SetCellValue('C' . $aux, $datos['code_desc']);
                $sheet->SetCellValue('D' . $aux, $datos['requiredFinancialGuarantee_Amount']);
                $sheet->SetCellValue('E' . $aux, $datos['allowedSubcontractTerms']);
                $sheet->SetCellValue('F' . $aux, $datos['description']);
                $sheet->SetCellValue('G' . $aux, $datos['personalSituation']);
                $sheet->SetCellValue('H' . $aux, $datos['procurementLegislationDocumentReference']);
                $sheet->SetCellValue('I' . $aux, $datos['fundingProgramCode']);
                $sheet->SetCellValue('J' . $aux, $datos['fundingProgramCode2']);
                $sheet->SetCellValue('K' . $aux, $datos['fundingProgram']);
                $aux++;
            }
        }

        return $spreadsheet;
    }

    private function datosCriterioAdjudicacion($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(7);
        $sheet->setTitle("Criterio Adjudicación");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {

                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['description']);
                $sheet->SetCellValue('C' . $aux, $datos['evaluationCriteriaTypeCode']);
                $aux++;
            }
        }

        return $spreadsheet;
    }

    private function datosCriterioEvaluacionFinanciera($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(8);
        $sheet->setTitle("CriteriosEvaluacionFinanciera");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {

                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['code_desc']);
                $sheet->SetCellValue('C' . $aux, $datos['description']);
                $aux++;
            }
        }
        return $spreadsheet;
    }

    private function datosCriterioEvaluacionTecnica($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(9);
        $sheet->setTitle("Criterios Evaluación Técnica");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {

                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['code_desc']);
                $sheet->SetCellValue('C' . $aux, $datos['description']);
                $aux++;
            }
        }

        return $spreadsheet;
    }

    private function datosRequisitosParticipacion($spreadsheet, $datos)
    {
        $sheet = $spreadsheet->getSheet(10);
        $sheet->setTitle("Requisitos Participación");

        if ($datos['num_rows'] > 0) {
            $aux = 2;
            $contador = 0;
            foreach ($datos['datos'] as $datos) {

                $contador++;
                $sheet->SetCellValue('A' . $aux, $datos['id_ajena_licitacion']);
                $sheet->SetCellValue('B' . $aux, $datos['code_desc']);
                $aux++;
            }
        }
        return $spreadsheet;
    }

    private function datosCompletosDocumentosGenerales($spreadsheet, $datosLicitacion)
    {
        $sheet = $spreadsheet->getSheet(11);
        $sheet->setTitle("Documentos Generales");
        $contador = 0;
        foreach ($datosLicitacion['datos'] as $doc) {

            $contador++;
            $sheet->SetCellValue('A' . $this->filaDocumentoGeneral, $doc['id_ajena_licitacion']);
            $sheet->SetCellValue('B' . $this->filaDocumentoGeneral, $doc['attachment']);
            $sheet->SetCellValue('C' . $this->filaDocumentoGeneral, $doc['fileName']);

            $this->filaDocumentoGeneral++;
        }

        return $spreadsheet;
    }

    private function datosCompletosDocumentosAdicionales($spreadsheet, $datosLicitacion)
    {
        $sheet = $spreadsheet->getSheet(12);
        $sheet->setTitle("Documentos Adicionales");
        $contador = 0;
        foreach ($datosLicitacion['datos'] as $doc) {

            $contador++;
            $sheet->SetCellValue('A' . $this->filaDocumentoAdd, $doc['id_ajena_licitacion']);
            $sheet->SetCellValue('B' . $this->filaDocumentoAdd, $doc['attachment']);
            $sheet->SetCellValue('C' . $this->filaDocumentoAdd, $doc['idDoc']);

            $this->filaDocumentoAdd++;
        }
        return $spreadsheet;
    }

    private function datosCompletosDocumentosTecnicos($spreadsheet, $datosLicitacion)
    {
        $sheet = $spreadsheet->getSheet(13);
        $sheet->setTitle("Documentos Técnicos");
        $contador = 0;
        foreach ($datosLicitacion['datos'] as $doc) {

            $contador++;
            $sheet->SetCellValue('A' . $this->filaDocumentoTech, $doc['id_ajena_licitacion']);
            $sheet->SetCellValue('B' . $this->filaDocumentoTech, $doc['attachment']);
            $sheet->SetCellValue('C' . $this->filaDocumentoTech, $doc['idDoc']);

            $this->filaDocumentoTech++;
        }
        return $spreadsheet;
    }

    private function datosCompletosDocumentosLegales($spreadsheet, $datosLicitacion)
    {
        $sheet = $spreadsheet->getSheet(14);
        $sheet->setTitle("Documentos Legales");
        $contador = 0;
        foreach ($datosLicitacion['datos'] as $doc) {

            $contador++;
            $sheet->SetCellValue('A' . $this->filaDocumentoLegal, $doc['id_ajena_licitacion']);
            $sheet->SetCellValue('B' . $this->filaDocumentoLegal, $doc['attachment']);
            $sheet->SetCellValue('C' . $this->filaDocumentoLegal, $doc['idDoc']);

            $this->filaDocumentoLegal++;
        }
        return $spreadsheet;
    }

    private function cabecerasOpenPlacspFirstSheet($spreadsheet)
    {
        $spreadsheet->setActiveSheetIndex(0);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', "Identificador");
        $spreadsheet->getActiveSheet()->SetCellValue('B1', "Link licitación");
        $spreadsheet->getActiveSheet()->SetCellValue('C1', "Fecha actualización");
        $spreadsheet->getActiveSheet()->SetCellValue('D1', "Vigente/Anulada/Archivada");
        $spreadsheet->getActiveSheet()->SetCellValue('E1', "Primera publicación");
        $spreadsheet->getActiveSheet()->SetCellValue('F1', "Estado");
        $spreadsheet->getActiveSheet()->SetCellValue('G1', "Número de expediente");
        $spreadsheet->getActiveSheet()->SetCellValue('H1', "Objeto del Contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('I1', "Valor estimado del contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('J1', "Presupuesto base sin impuestos");
        $spreadsheet->getActiveSheet()->SetCellValue('K1', "CPV");
        $spreadsheet->getActiveSheet()->SetCellValue('L1', "Tipo de contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('M1', "Lugar de ejecución");
        $spreadsheet->getActiveSheet()->SetCellValue('N1', "Órgano de Contratación");
        $spreadsheet->getActiveSheet()->SetCellValue('O1', "DIR3");
        $spreadsheet->getActiveSheet()->SetCellValue('P1', "Enlace al Perfil de Contratante del OC");
        $spreadsheet->getActiveSheet()->SetCellValue('Q1', "Tipo de Administración");
        $spreadsheet->getActiveSheet()->SetCellValue('R1', "Código Postal");
        $spreadsheet->getActiveSheet()->SetCellValue('S1', "Tipo de procedimiento");
        $spreadsheet->getActiveSheet()->SetCellValue('T1', "Sistema de contratación");
        $spreadsheet->getActiveSheet()->SetCellValue('U1', "Tramitación");
        $spreadsheet->getActiveSheet()->SetCellValue('V1', "Forma de presentación de la oferta");
        $spreadsheet->getActiveSheet()->SetCellValue('W1', "Directiva de aplicación");
        $spreadsheet->getActiveSheet()->SetCellValue('X1', "Subcontratación permitida");
        $spreadsheet->getActiveSheet()->SetCellValue('Y1', "Duración Contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('Z1', "Tipo de duración");
        $spreadsheet->getActiveSheet()->SetCellValue('AA1', "Inicio contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('AB1', "Fin contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('AC1', "Extension Contrato");
        $spreadsheet->getActiveSheet()->SetCellValue('AD1', "URL Organo Contratación");
        $spreadsheet->getActiveSheet()->SetCellValue('AE1', "Ciudad Organo Contratación");
        $spreadsheet->getActiveSheet()->SetCellValue('AF1', "Dirección Organo Contratación");
        $spreadsheet->getActiveSheet()->SetCellValue('AG1', "Nombre Contacto Organo Contratación");
        $spreadsheet->getActiveSheet()->SetCellValue('AH1', "Email contacto Organo Contratación");
        return $spreadsheet;
    }

    //Cabeceras
    private function cabecerasOpenPlacspDocumentos($spreadsheet, $hojaActiva)
    {
        $sheet = $spreadsheet->getSheet($hojaActiva);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:D1")->applyFromArray($styleArr);
        $spreadsheet->setActiveSheetIndex($hojaActiva);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', "Identificador");
        $spreadsheet->getActiveSheet()->SetCellValue('B1', "Link Documento");
        $spreadsheet->getActiveSheet()->SetCellValue('C1', "Nombre Documento");

        return $spreadsheet;
    }

    private function cabecerasOpenPlacsBitacora($spreadsheet, $hojaActiva)
    {
        $sheet = $spreadsheet->getSheet($hojaActiva);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:F1")->applyFromArray($styleArr);
        $spreadsheet->setActiveSheetIndex($hojaActiva);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', "Identificador");
        $spreadsheet->getActiveSheet()->SetCellValue('B1', "Objeto del lote");
        $spreadsheet->getActiveSheet()->SetCellValue('C1', "Número de lote");
        $spreadsheet->getActiveSheet()->SetCellValue('D1', "Importe sin Impuestos");
        $spreadsheet->getActiveSheet()->SetCellValue('E1', "Lugar de ejecución del lote");
        $spreadsheet->getActiveSheet()->SetCellValue('F1', "CPV");

        return $spreadsheet;
    }

    private function cabeceraMediosComunicacion($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(2);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:C1")->applyFromArray($styleArr);
        $spreadsheet->setActiveSheetIndex(2);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Tipo de anuncio');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Medio de publicación');

        return $spreadsheet;
    }

    private function cabeceraMediosComunicacionDocumentos($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(3);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:C1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Documento');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Nombre Documento');

        return $spreadsheet;
    }

    private function cabeceraTenderResult($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(4);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:O1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Tipo de resultado');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Motivación adjudicación');
        $spreadsheet->getActiveSheet()->SetCellValue('D1', 'Fecha del acuerdo');
        $spreadsheet->getActiveSheet()->SetCellValue('E1', 'Número de licitadores participadores');
        $spreadsheet->getActiveSheet()->SetCellValue('F1', 'Importe Oferta mas baja');
        $spreadsheet->getActiveSheet()->SetCellValue('G1', 'Importe Oferta mas alta');
        $spreadsheet->getActiveSheet()->SetCellValue('H1', 'Ofertas Temerarias Descartadas');
        $spreadsheet->getActiveSheet()->SetCellValue('I1', 'Fecha de entrada en vigor');
        $spreadsheet->getActiveSheet()->SetCellValue('J1', 'Identifica si es una PYME');
        $spreadsheet->getActiveSheet()->SetCellValue('K1', 'Identificador del contrato');
        $spreadsheet->getActiveSheet()->SetCellValue('L1', 'Fecha de formalización');
        $spreadsheet->getActiveSheet()->SetCellValue('M1', 'Adjudicatario CIF');
        $spreadsheet->getActiveSheet()->SetCellValue('N1', 'Nombre Adjudicatario');
        $spreadsheet->getActiveSheet()->SetCellValue('O1', 'Importe de adjudicación sin impuestos');
        return $spreadsheet;
    }

    private function cabeceraTipoProcedimiento($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(5);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:O1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Tipo de Procedimiento');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Tipo de Tramitación');
        $spreadsheet->getActiveSheet()->SetCellValue('D1', 'Sistema de Contratación');
        $spreadsheet->getActiveSheet()->SetCellValue('E1', 'Número de lotes a los que se debe ofertar');
        $spreadsheet->getActiveSheet()->SetCellValue('F1', 'Presentación de la oferta');
        $spreadsheet->getActiveSheet()->SetCellValue('G1', 'Número de lotes a los que se puede ofertar');
        $spreadsheet->getActiveSheet()->SetCellValue('H1', 'Número máximo de lotes que se puede adjudicar un licitador');
        $spreadsheet->getActiveSheet()->SetCellValue('I1', 'El poder adjudicador se reserva el derecho de adjudicar contratos que combinen lotes');
        $spreadsheet->getActiveSheet()->SetCellValue('J1', 'Fecha limite para la presentación de ofertas');
        $spreadsheet->getActiveSheet()->SetCellValue('K1', 'Tiempo limite para la presentación de ofertas');
        $spreadsheet->getActiveSheet()->SetCellValue('L1', 'Texto descriptivo de fecha limite de presentación de ofertas');
        $spreadsheet->getActiveSheet()->SetCellValue('M1', 'Usa subasta electronica');
        $spreadsheet->getActiveSheet()->SetCellValue('N1', 'Fecha límite para obtener los pliegos');
        $spreadsheet->getActiveSheet()->SetCellValue('O1', 'Hora límite para obtener los pliegos');

        return $spreadsheet;
    }

    private function cabeceraTenderingTerms($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(6);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:K1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Indica que se pueden ofertar variantes');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Tipo de garantia');
        $spreadsheet->getActiveSheet()->SetCellValue('D1', 'Porcentaje de la garantíaa');
        $spreadsheet->getActiveSheet()->SetCellValue('E1', 'Porcentaje de subcontratación máximo especificado para este contrato.');
        $spreadsheet->getActiveSheet()->SetCellValue('F1', 'Descripción del objeto de la subcontratación');
        $spreadsheet->getActiveSheet()->SetCellValue('G1', 'Descripción textual de los requisitos específicos del operador económico para poder participar en la licitación');
        $spreadsheet->getActiveSheet()->SetCellValue('H1', 'Contrato sujeto a regulación armonizadaF');
        $spreadsheet->getActiveSheet()->SetCellValue('I1', 'Financiación de la UE');
        $spreadsheet->getActiveSheet()->SetCellValue('J1', 'Fuente de financiación europea');
        $spreadsheet->getActiveSheet()->SetCellValue('K1', 'Descripción / Programa específico de la UE');

        return $spreadsheet;
    }

    private function cabeceraCriterioADjudicacion($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(7);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:C1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Descripción textual del criterio de adjudicación');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Ponderación');

        return $spreadsheet;
    }

    private function cabeceraCriteriosFinancieros($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(8);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:C1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Tipo criterio de evaluación financiera');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Descripción textual del criterio de evaluación financiera');

        return $spreadsheet;
    }

    private function cabeceraCriteriosTecnicos($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(9);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:C1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Tipo criterio de evaluación técnica');
        $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Descripción textual del criterio de evaluación técnica');

        return $spreadsheet;
    }

    private function cabeceraRequisitosParticipacion($spreadsheet)
    {
        $sheet = $spreadsheet->getSheet(10);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $sheet->getStyle("A1:B1")->applyFromArray($styleArr);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Identificador');
        $spreadsheet->getActiveSheet()->SetCellValue('B1', 'Tipo Requisitos Participacion');

        return $spreadsheet;
    }
}

/* End of file ExportXls.php */
/* Location: ./application/controllers/ExportXls.php */
