<?php
    if(is_null($data['data'])){
        $this->flashmessenger->addMessage(array('info'=>'No se encontraton resultados.')); 
        header('Location: Reports.php');
        exit;
    }

    $arrayData = $data['data'];

   

    $primerElemento = reset($arrayData);
    $colTitulosTemp = $primerElemento[0];
   
    $fieldsToPrint = array(        
         'storeName'=>$this->_getTranslation('Sucursal'),
        'productName'=>$this->_getTranslation('PRODUCTO'),
        'dateFormated'=>$this->_getTranslation('FECHA'),
        'hora_creado'=>$this->_getTranslation('HORA'),
        'cantidad_charolas'=>$this->_getTranslation('HORNEADO CHAROLA'),
        'cantidad_piezas'=>$this->_getTranslation('HORNEADO PZA'),
        'costo_pieza'=>$this->_getTranslation('Costo por pieza'),
        'costo_total'=>$this->_getTranslation('Costo total'),
        'precio_venta'=>$this->_getTranslation('Precio Venta'),
        'venta_aproximada'=>$this->_getTranslation('Venta Aprox'),
        'userName'=>$this->_getTranslation('Usuario')

    );
    
    foreach($fieldsToPrint as $titulo => $value){
        if(key_exists($titulo, $colTitulosTemp)){            
            $colTitulos[] = $fieldsToPrint[$titulo];
        }
    }
 
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->freezePane('A4');
    $col = count($colTitulos);
    $lastCol = $this->getColLetter($col-1);
    
    $objPHPExcel->getActiveSheet()->mergeCells("A1:".$lastCol."1");            
    $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(50);
    $objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->setBold(true);
    $objPHPExcel->getActiveSheet()->setCellValue("A1", $this->headerExcelReport);
    $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle("A1")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->getStyle("A1")->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
   
    //  $objPHPExcel->getActiveSheet()->getStyle("A2:".$lastCol."2")->applyFromArray($headerStyleArray);

    // Aplicar el estilo a los encabezados generales
    $objPHPExcel->getActiveSheet()->getStyle("A3:".$lastCol."3")->applyFromArray(array(
        'font' => array(
            'bold' => true,
            'color' => array('rgb' => 'FFFFFF'), // Letra blanca
        ),
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '000000'), // Fondo negro
        ),
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
        ),
    ));

    //$objPHPExcel->getActiveSheet()->getStyle("A2:".$lastCol."2")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // Aplicar el estilo a los encabezados generales
   


    $objPHPExcel->getActiveSheet()->fromArray($colTitulos,NULL,'A3');    
   
    $row=4;  
    $total_venta_aproximada_periodo = 0; // Variable acumuladora para la venta aproximada del periodo

    foreach ($arrayData as $key => $array) { 
        $rowInicio = $row;
        $total_qty_horneado = 0;
        $total_qty_piezas = 0;
        $total_costoTotal = 0;
        $total_venta_aproximada = 0;

        foreach($array as $key => $data ){       
            $arrayRow = array();
            $i = 0;
            foreach ($fieldsToPrint as $field => $value) {
                if(key_exists($field, $data)){ 
                    $col = $this->getColLetter($i);   
                    $objPHPExcel->getActiveSheet()->setCellValue($col . $row, $data[$field]);                                
                    $i++;                                                      
                }  
            }
            
            $total_qty_horneado += round($data['cantidad_charolas'],2);
            $total_qty_piezas += round($data['cantidad_piezas'],2);
            $total_costoTotal += round($data['costo_total'],2);
            $total_venta_aproximada += round($data['venta_aproximada'],2);     
            $total_venta_aproximada_periodo += round($data['venta_aproximada'],2); // Acumula la venta aproximada del periodo              
            $row++;
        }          
        
        $objPHPExcel->getActiveSheet()->getStyle("A$rowInicio:B$row")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle("G$rowInicio:J$row")->getNumberFormat()->setFormatCode('$#,##0.00_ ;[Red]-$#,##0.00');
        
        $objPHPExcel->getActiveSheet()->mergeCells("A$row:B$row");            
        $objPHPExcel->getActiveSheet()->getStyle("A$row:J$row")->getFont()->setBold(true);          
        $objPHPExcel->getActiveSheet()->getStyle("A$row")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->setCellValue("A$row", "TOTAL ".$data['storeName']);
          
        $rowFin = $row - 1;
        $arrayTotales = array();
        $arrayTotales[] = "$total_qty_horneado";
        $arrayTotales[] = "$total_qty_piezas";
        $arrayTotales[] = "";

        $arrayTotales[] = "$total_costoTotal";
        $arrayTotales[] = "";
                
        $arrayTotales[] = "$total_venta_aproximada";    
        
        $objPHPExcel->getActiveSheet()->fromArray($arrayTotales,NULL,'E'.$row);
        $objPHPExcel->getActiveSheet()->getStyle("E$row:J$row")->getNumberFormat()->setFormatCode('$#,##0.00_ ;[Red]-$#,##0.00');     

        $row++;
        $row++;
    }

    // Escribir el total de la venta aproximada del periodo en las celdas específicas
    $objPHPExcel->getActiveSheet()->mergeCells("G2:I2");
    $objPHPExcel->getActiveSheet()->setCellValue("G2", "Venta Aproximada del Periodo");
   
    $objPHPExcel->getActiveSheet()->getStyle("G2:I2")->applyFromArray(array(
        'font' => array(
            'bold' => true,
            'color' => array('rgb' => 'FF0000'), // Letra roja
        ),
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            //'color' => array('rgb' => '000000'), // Fondo negro
        ),
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
        ),
    ));

    $objPHPExcel->getActiveSheet()->setCellValue("J2", $total_venta_aproximada_periodo . " DLLS");
    $objPHPExcel->getActiveSheet()->getStyle("J2")->applyFromArray(array(
        'font' => array(
            'color' => array('rgb' => 'FF0000'), // Letra roja
            'bold' => true,
        ),
    ));
    $objPHPExcel->getActiveSheet()->getStyle("J2")->getNumberFormat()->setFormatCode('$#,##0.00_ ;[Red]-$#,##0.00');
    $objPHPExcel->getActiveSheet()->getStyle("J2")->getFont()->setBold(true);

    foreach(range('A',$lastCol) as $columnID) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
            ->setAutoSize(true);
    }

    $objPHPExcel->setActiveSheetIndex(0);   
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
    if($this->saveFile == true){
        $objWriter->save($this->getTempFolder()."/".$this->getNombreArchivo().".xlsx");
    }else{                
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename=".$this->getNombreArchivo().".xlsx");
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
        exit;
    }
    unset($objWriter);