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

/**
 *
 * Controller ExportXls
 *
 * This controller for ...
 *
 * @package   CodeIgniter
 * @category  Controller CI
 * @author    Setiawan Jodi <jodisetiawan@fisip-untirta.ac.id>
 * @author    Raul Guerrero <r.g.c@me.com>
 * @link      https://github.com/setdjod/myci-extension/
 * @param     ...
 * @return    ...
 *
 */

class ExportXls extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('excel');
        $this->load->model("Xlsexport_model");
    }

    public function exportDatosCompletos()
    {
        $licitacionesResult = $this->Xlsexport_model->getLicitaciones();
        $result = array();

        //$start = $this->starttime();
        if ($licitacionesResult['num_rows'] > 0) {
            foreach ($licitacionesResult['datos'] as $licitacion) {
                $result[$licitacion->id]['licitacion'] = $licitacion;
                $result[$licitacion->id]['contract'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_contract_folder", $licitacion->id);
                $result[$licitacion->id]['locatedParty'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_located_contracting_party", $licitacion->id);
                $result[$licitacion->id]['party'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_party", $licitacion->id);
                foreach ($result[$licitacion->id]['party'] as $row) {
                    $result[$licitacion->id]['partyActivity'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_party_party_idenfitication", "id_ajena_party", $row['id']);
                }

                $result[$licitacion->id]['project'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_procurement_project", $licitacion->id);
                foreach ($result[$licitacion->id]['project'] as $row) {
                    $result[$licitacion->id]['projectActivity'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_procurement_project_itemClass", "id_ajena_pp", $row['id']);
                }

                $result[$licitacion->id]['projectLot'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_procurement_project_lot", $licitacion->id);
                foreach ($result[$licitacion->id]['projectLot'] as $row) {
                    $result[$licitacion->id]['projectLotActivity'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_procurement_project_lot_item", "id_ajena_ppl", $row['id']);
                }

                $result[$licitacion->id]['tenderResult'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_tender_result", $licitacion->id);
                $result[$licitacion->id]['tenderProcess'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_tendering_process", $licitacion->id);
                $result[$licitacion->id]['tenderTerms'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_tendering_terms", $licitacion->id);
                foreach ($result[$licitacion->id]['tenderTerms'] as $row) {
                    $result[$licitacion->id]['tenderTermsAwarding'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_tendering_terms_awarding_terms", "id_ajena_tt", $row['id']);
                    $result[$licitacion->id]['tenderTermsFinancial'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_tendering_terms_financial_evaluation", "id_ajena_ttfe", $row['id']);
                    $result[$licitacion->id]['tenderTermsQualification'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_tendering_terms_qualification_request", "id_ajena_tt", $row['id']);
                    $result[$licitacion->id]['tenderTermsSpecific'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_tendering_terms_specific_terms", "id_ajena_tt", $row['id']);
                }

                $result[$licitacion->id]['validNoticeInfo'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_valid_notice_info", $licitacion->id);
                foreach ($result[$licitacion->id]['validNoticeInfo'] as $row) {
                    $result[$licitacion->id]['validNoticeInfoDocument'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_valid_notice_info_documento", "id_ajena_vni", $row['id']);
                    $result[$licitacion->id]['validNoticeInfoFecha'] = $this->Xlsexport_model->getDatosRelacionadosByTablaAndLicitacion("maestro_valid_notice_info_fecha", "id_ajena_vni", $row['id']);
                }

                $result[$licitacion->id]['techDocs'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_technical_documents", $licitacion->id);
                $result[$licitacion->id]['legalDocs'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_legal_documents", $licitacion->id);
                $result[$licitacion->id]['generalDocs'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_general_documents", $licitacion->id);
                $result[$licitacion->id]['additDocs'] = $this->Xlsexport_model->getDatosByTablaAndLicitacion("maestro_additional_documents", $licitacion->id);
            }
        }
        //echo ($this->endtime($start));
        //pretty_dump($result);

        $objPHPExcel = new PHPExcel();
        // El libro activo el cual exportar sera el 0

        $filaExcel = 1;
        foreach ($result as $dato) {
            if ($filaExcel == 1) {
                $objPHPExcel = $this->cabecerasOpenPlacspFirstSheet($objPHPExcel);
            } else {
                $objPHPExcel = $this->datosCompletosHojaLicitacion($objPHPExcel, $dato, $filaExcel);
            }

            $filaExcel++;
        }

/*        //Escribimos las cabeceras de cada columna de la bbdd
if ($rowCount == 1) {
$this->cabecerasOpenPlacspFirstSheet($objPHPExcel);
$concesionNombre = $row->concesionNombre;
$codConc = $row->codConc;
$rowCount++;
}
 */
        $nombreAchivo = 'test.xls';

        $ruta = base_url() . 'uploads/' . $nombreAchivo;

        // 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');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save(FCPATH . 'uploads/' . $nombreAchivo);

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(array("url" => $ruta)));
    }

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

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

    private function datosCompletosHojaLicitacion($objPHPExcel, $datosLicitacion, $filaExcel)
    {
        $objPHPExcel->setActiveSheetIndex(0);
        $styleArr = array(
            "font" => array(
                "bold" => true,
                "color" => array("rgb" => "22B9FF"),
                "size" => 13,
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle("A1:AB1")->applyFromArray($styleArr);
        //$sharedStyle1->applyFromArray(array('fill' => array('type' => \PHPExcel\Style\Fill::FILL_SOLID, 'color' => array('argb' => 'FFCCFFCC')), 'borders' => array('bottom' => array('style' => \PHPExcel\Style\Border::BORDER_THIN), 'right' => array('style' => \PHPExcel\Style\Border::BORDER_MEDIUM))));
        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $filaExcel, $datosLicitacion['licitacion']->id_licitacion);
        $objPHPExcel->getActiveSheet()->SetCellValue('B' . $filaExcel, $datosLicitacion['licitacion']->url_id_licitacion);
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $filaExcel, $datosLicitacion['licitacion']->updated);
        $objPHPExcel->getActiveSheet()->SetCellValue('D' . $filaExcel, "");
        $objPHPExcel->getActiveSheet()->SetCellValue('E' . $filaExcel, "Primera publicación");
        $objPHPExcel->getActiveSheet()->SetCellValue('F' . $filaExcel, $datosLicitacion['contract'][0]['contractFolderStatusCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('G' . $filaExcel, $datosLicitacion['contract'][0]['contractFolderID']);
        $objPHPExcel->getActiveSheet()->SetCellValue('H' . $filaExcel, $datosLicitacion['project'][0]['name']);
        $objPHPExcel->getActiveSheet()->SetCellValue('I' . $filaExcel, $datosLicitacion['project'][0]['estimatedOverallContractAmount']);
        $objPHPExcel->getActiveSheet()->SetCellValue('J' . $filaExcel, $datosLicitacion['project'][0]['taxExclusiveAmount']);
        $objPHPExcel->getActiveSheet()->SetCellValue('K' . $filaExcel, $datosLicitacion['project'][0]['totalAmount']);

        $cpvProject = "";
        for ($i = 0; $i < count($datosLicitacion['projectActivity']); $i++) {
            $cpvProject .= $datosLicitacion['projectActivity'][$i]['itemClassification_value'] . ";";
        }

        $cpvParty = "";
        //TODO OBtener solo el DIR3
        for ($i = 0; $i < count($datosLicitacion['partyActivity']); $i++) {
            $cpvParty .= $datosLicitacion['partyActivity'][$i]['idPartyIdent'] . ";";
        }

        $objPHPExcel->getActiveSheet()->SetCellValue('L' . $filaExcel, $cpvProject);
        $objPHPExcel->getActiveSheet()->SetCellValue('M' . $filaExcel, $datosLicitacion['project'][0]['typeCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('N' . $filaExcel, $datosLicitacion['project'][0]['countrySubentityCode'] . " - " . $datosLicitacion['project'][0]['countrySubentity']);
        $objPHPExcel->getActiveSheet()->SetCellValue('O' . $filaExcel, $datosLicitacion['party'][0]['partyName']);
        $objPHPExcel->getActiveSheet()->SetCellValue('P' . $filaExcel, $datosLicitacion['party'][0]['partyName']);
        $objPHPExcel->getActiveSheet()->SetCellValue('Q' . $filaExcel, $datosLicitacion['locatedParty'][0]['contractingPartyTypeCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('R' . $filaExcel, $cpvParty);
        $objPHPExcel->getActiveSheet()->SetCellValue('S' . $filaExcel, $datosLicitacion['locatedParty'][0]['buyerProfileURIID']);
        $objPHPExcel->getActiveSheet()->SetCellValue('T' . $filaExcel, $datosLicitacion['locatedParty'][0]['contractingPartyTypeCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('U' . $filaExcel, $datosLicitacion['party'][0]['codpostal']);
        $objPHPExcel->getActiveSheet()->SetCellValue('V' . $filaExcel, $datosLicitacion['tenderProcess'][0]['procedureCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('W' . $filaExcel, $datosLicitacion['tenderProcess'][0]['contractingSystemCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('X' . $filaExcel, $datosLicitacion['tenderProcess'][0]['urgencyCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('Y' . $filaExcel, $datosLicitacion['tenderProcess'][0]['submissionMethodCode']);
        $objPHPExcel->getActiveSheet()->SetCellValue('Z' . $filaExcel, $datosLicitacion['tenderTerms'][0]['procurementLegislationDocumentReference']);
        $objPHPExcel->getActiveSheet()->SetCellValue('AA' . $filaExcel, $datosLicitacion['tenderTerms'][0]['allowedSubcontractTerms']);
        $objPHPExcel->getActiveSheet()->SetCellValue('AB' . $filaExcel, "");

        return $objPHPExcel;

    }

    private function datosCompletosHojaBitacora($objPHPExcel, $datosLicitacion)
    {

    }

    private function datosCompletosDocumentosGenerales($objPHPExcel)
    {

    }

    private function datosCompletosDocumentosAdicionales($objPHPExcel)
    {

    }

    private function datosCompletosDocumentosTecnicos($objPHPExcel)
    {

    }

    private function datosCompletosDocumentosLegales($objPHPExcel)
    {

    }

    private function cabecerasOpenPlacspFirstSheet($objPHPExcel)
    {
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', "Identificador");
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', "Link licitación");
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', "Fecha actualización");
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', "Vigente/Anulada/Archivada");
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', "Primera publicación");
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', "Estado");
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', "Número de expediente");
        $objPHPExcel->getActiveSheet()->SetCellValue('H1', "Objeto del Contrato");
        $objPHPExcel->getActiveSheet()->SetCellValue('I1', "Valor estimado del contrato");
        $objPHPExcel->getActiveSheet()->SetCellValue('J1', "Presupuesto base sin impuestos");
        $objPHPExcel->getActiveSheet()->SetCellValue('K1', "Presupuesto base con impuestos");
        $objPHPExcel->getActiveSheet()->SetCellValue('L1', "CPV");
        $objPHPExcel->getActiveSheet()->SetCellValue('M1', "Tipo de contrato");
        $objPHPExcel->getActiveSheet()->SetCellValue('N1', "Lugar de ejecución");
        $objPHPExcel->getActiveSheet()->SetCellValue('O1', "Órgano de Contratación");
        $objPHPExcel->getActiveSheet()->SetCellValue('P1', "ID OC en PLACSP");
        $objPHPExcel->getActiveSheet()->SetCellValue('Q1', "NIF OC");
        $objPHPExcel->getActiveSheet()->SetCellValue('R1', "DIR3");
        $objPHPExcel->getActiveSheet()->SetCellValue('S1', "Enlace al Perfil de Contratante del OC");
        $objPHPExcel->getActiveSheet()->SetCellValue('T1', "Tipo de Administración");
        $objPHPExcel->getActiveSheet()->SetCellValue('U1', "Código Postal");
        $objPHPExcel->getActiveSheet()->SetCellValue('V1', "Tipo de procedimiento");
        $objPHPExcel->getActiveSheet()->SetCellValue('W1', "Sistema de contratación");
        $objPHPExcel->getActiveSheet()->SetCellValue('X1', "Tramitación");
        $objPHPExcel->getActiveSheet()->SetCellValue('Y1', "Forma de presentación de la oferta");
        $objPHPExcel->getActiveSheet()->SetCellValue('Z1', "Directiva de aplicación");
        $objPHPExcel->getActiveSheet()->SetCellValue('AA1', "Subcontratación permitida");
        $objPHPExcel->getActiveSheet()->SetCellValue('AB1', "Subcontratación permitida porcentaje");
        return $objPHPExcel;
    }
}

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