<?php 
    
    $settings = new SettingsRepository(); 
    $sucursales = $data['stores'];
    $areaName = $data['areaBakeryProduction'];
    $detalles = $data['data'];           
    $comentarios = $data['comments'];
    
    $colTitulos[] = 'Producto';
    foreach($sucursales as $store_id => $store_name){
        $colTitulos[] = $store_name;
    }  
    
    $colTitulos[] = 'Total';

    
    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->freezePane('A3');
    $col = count($colTitulos);
    $lastCol = $this->getColLetter($col-1);    
    
    $sheet->mergeCells("A1:".$lastCol."1");            
    $sheet->getRowDimension('1')->setRowHeight(60);
    $sheet->getStyle("A1")->getFont()->setBold(true);
    $sheet->setCellValue("A1", $this->headerExcelReport."\n".'Generado: '.date('M/d/Y  g:i a'));
    $sheet->getStyle('A1')->getAlignment()->setWrapText(true);
    $sheet->getStyle("A1")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle("A1")->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);      
    
    $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle("A2:".$lastCol."2")->getFont()->setBold(true);
    $sheet->fromArray($colTitulos,NULL,'A2');    
    
    $row=3;
    $firstRow = $row;        
   foreach ($detalles as $detalle) {  
        $i=0;    
        $firstCol = $this->getColLetter($i);
        
        $sheet->setCellValue("$firstCol$row",$detalle['description']); 
        $i++;
        
        foreach($sucursales as $store_id => $store_name){   
            $col = $this->getColLetter($i);
            $lastCol = $col;
            if(empty($detalle[$store_id])){$detalle[$store_id] = 0;}
            $sheet->setCellValue("$col$row",$detalle[$store_id]); 
            $i++;
        }          
        
        $col = $this->getColLetter($i);
        $sheet->setCellValue("$col$row","=SUM($firstCol$row:$lastCol$row)"); 
        
        $row++;        
    }

    $sheet->getStyle("A$firstRow:$lastCol$row")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);        
    
    foreach(range('A',$lastCol) as $columnID) {
        $sheet->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);