<?php

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

$arrayData =$data;


 $colTitulos[] = $this->_getTranslation('Sucursal');

// Añadimos las horas al array de títulos de columnas

$colTitulos[] = $this->_getTranslation('Qty');
$colTitulos[] = $this->_getTranslation('Item');
$colTitulos[] = $this->_getTranslation('Ave Price');
$colTitulos[] = $this->_getTranslation('Discount');

$colTitulos[] = $this->_getTranslation('Net');
$colTitulos[] = $this->_getTranslation('Taxas');

$colTitulos[] = $this->_getTranslation('Gross');



$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(50);

$sheet->getStyle("A1")->getFont()->setBold(true);

$sheet->setCellValue("A1", "Sales by Item" . "\n" . "Fecha " . $arrayData['filtros']['date'] . "\n" . "Periodo: " . $arrayData['filtros']['De'] . " - " . $arrayData['filtros']['year']);

$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->fromArray($colTitulos, NULL, 'A2');



$row = 3;

$firstRow = $row;

foreach ($arrayData['sucursales']['id_sucursal'] as $index => $idSucursal) {
    $sheet->setCellValue("A$row", $arrayData['sucursales']['sucursales'][$index]);
   
    // Añadimos las ventas por cada hora
    $totalVenta = 0;
    $colIndex = 'B'; // Empieza en la columna B (la primera después de "Sucursal")
    
    foreach ($arrayData['sales_items'] as $venta) {
      
        if($idSucursal == $venta['idSucursal']){
            $qty = isset($venta['quantity']) ? (int)$venta['quantity'] : 0;

            $sheet->setCellValue("B$row", $qty);
    
            $item = isset($venta['item']) ? (int)$venta['item'] : 0;
            $sheet->setCellValue("C$row", $item);
    
            $ave_price = isset($venta['ave_price']) ? (int)$venta['ave_price'] : 0;
            $sheet->setCellValue("D$row", $ave_price);
    
      
    
            $amount = isset($venta['amount']) ? (int)$venta['amount'] : 0;
            $sheet->setCellValue("E$row", $amount);
    
            $discounts = isset($venta['discounts']) ? (int)$venta['discounts'] : 0;
            $sheet->setCellValue("F$row", $discounts);
            
            $taxes = isset($venta['taxes']) ? (int)$venta['taxes'] : 0;
            $sheet->setCellValue("G$row", $taxes);
    
            // $subtotal = isset($venta['subtotal']) ? (int)$venta['subtotal'] : 0;
            // $sheet->setCellValue("H$row", $subtotal);
    
            $total = isset($venta['total']) ? (int)$venta['total'] : 0;
            $sheet->setCellValue("H$row", $total);
            $row++;
        }
      

       
  
    }
    
    // Añadimos la columna de Total
    //$sheet->setCellValue($colIndex . $row, $totalVenta);

    $row++;
}

$sheet->getStyle("A$firstRow:".$lastCol."$row")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("A$firstRow:".$lastCol."$row")->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$sheet->getStyle("B$firstRow:".$lastCol."$row")->getNumberFormat()->setFormatCode('$#,##0.00_ ;[Red]-#,##0.00');

$lastRow = $row - 1;


$sheet->getStyle("A$row:".$lastCol."$row")->getFont()->setBold(true);
$sheet->getStyle("B$row:".$lastCol."$row")->getNumberFormat()->setFormatCode('$#,##0.00_ ;[Red]-#,##0.00');

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