<?php
/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/


class XenCentral_AdServer_ViewAdmin_Export extends XenForo_ViewAdmin_Base
{
    public function renderRaw()
    {
        $time = date('m/d/y', time());
        $bannersImpressionsArray = $this->_params['banner'];
        $zonesImpressionsArray = $this->_params['zone'];
        $conditions = $this->_params['conditions'];
        $download = array();

        foreach ($zonesImpressionsArray as $zoneId => $zoneImpressions) {
            $download = array_merge($download, array($zoneImpressions));
            foreach ($bannersImpressionsArray as $bannerId => $bannerImpressions) {
                if ($bannerImpressions['bannerInfo']['zoneId'] == $zoneId) {
                    $download = array_merge($download, array($bannerImpressions));
                }
            }
        }

        foreach ($download as $key => $downloadValue) {
            if (isset($downloadValue['bannerStatistics'])) {
                if (empty($downloadValue['bannerStatistics'])) {
                    unset($download[$key]);
                }
            } else {
                if (empty($downloadValue['zoneStatistics'])) {
                    unset($download[$key]);
                }
            }
        }

        //Export PDF
        if ($conditions['export_type'] == "pdf") {
            require_once dirname(__FILE__) . '/' . '../Resources/ExportPdf/fpdf.php';
            $pdf = new FPDF();
            $pdf->AddPage();
            $pdf->SetFont("Arial", "B", "12", "C");

            $colArray = array("dateline", "impression", "click");

            foreach ($download as $value) {

                $pdf->SetX(20);
                if (isset($value['bannerInfo'])) {
                    $pdf->SetFont("Arial", "B", "14", "C");
                    $pdf->Write(19, new XenForo_Phrase('xcas_banner_x', array('title' => $value['bannerInfo']['title'])));
                    $pdf->Ln(15);
                    $pdf->SetFont("Arial", "B", "12", "C");
                    foreach ($colArray as $colValue) {
                        $pdf->Cell(25, 12, new XenForo_Phrase('xcas_col_' . $colValue), 1, 0, 'C');
                    }
                    $pdf->Ln(12);
                } else {
                    $pdf->SetFont("Arial", "B", "18", "C");
                    $pdf->Write(19, new XenForo_Phrase('xcas_zone_x', array('title' => $value['zoneInfo']['title'])));
                    $pdf->Ln(15);
                    $pdf->SetFont("Arial", "B", "12", "C");
                    foreach ($colArray as $colValue) {
                        $pdf->Cell(25, 12, new XenForo_Phrase('xcas_col_' . $colValue), 1, 0, 'C');
                    }
                    $pdf->Ln(12);
                }
                $pdf->SetFont("Arial", "B", "12", "C");
                if (isset($value['bannerStatistics'])) {
                    $exportArray = $value['bannerStatistics'];
                } else {
                    $exportArray = $value['zoneStatistics'];
                }
                foreach ($exportArray as $exportArrayValue) {
                    foreach ($exportArrayValue as $dateValue) {
                        $pdf->Cell(25, 12, $dateValue, 1, 0, 'C');
                    }
                    $pdf->Ln(12);
                }
            }
            $pdf->output("export_stats.pdf", "D");
        } else {
            //Export XLS
            /** Include PHPExcel */
            require_once dirname(__FILE__) . '/' . '../Resources/ExportExcel/Classes/PHPExcel.php';

            // Create new PHPExcel object
            $objPHPExcel = new PHPExcel();

            // Set document properties
            $objPHPExcel->getProperties()->setCreator("XenCentral Ad Server")
                    ->setLastModifiedBy("XenCentral Ad Server")
                    ->setTitle()
                    ->setSubject(new XenForo_Phrase('xcas_banner_statistics'))
                    ->setKeywords(new XenForo_Phrase('xcas_banner_statistics'))
                    ->setCategory(new XenForo_Phrase('xcas_banner_statistics'));


            // Add some data
            $row = 0;
            foreach ($download as $key => $value) {
                if (isset($value['zoneInfo'])) {
                    $title = $value['zoneInfo']['title'];
                    $name = (new XenForo_Phrase('xcas_zone_x', array('title' => $title))) . '';
                } else {
                    $title = $value['bannerInfo']['title'];
                    $name = (new XenForo_Phrase('xcas_banner_x', array('title' => $title))) . '';
                }
                $row++;
                $rowPlus = $row + 1;
                $style = array(
                        'font' => array('bold' => true, 'size' => 12,),
                        'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
                );
                $objPHPExcel->setActiveSheetIndex(0)->getStyle("A$row")->applyFromArray($style);
                $objPHPExcel->setActiveSheetIndex(0)
                        ->mergeCells("A$row:C$row")
                        ->setCellValue("A$row", $name)
                        ->setCellValue("B$row", $title)
                        ->setCellValue("A$rowPlus", (new XenForo_Phrase('xcas_col_dateline')) . '')
                        ->setCellValue("B$rowPlus", (new XenForo_Phrase('xcas_col_impression')) . '')
                        ->setCellValue("C$rowPlus", (new XenForo_Phrase('xcas_col_click')) . '');
                $objPHPExcel->setActiveSheetIndex(0)->getStyle("A$rowPlus")->applyFromArray($style);
                $objPHPExcel->setActiveSheetIndex(0)->getStyle("B$rowPlus")->applyFromArray($style);
                $objPHPExcel->setActiveSheetIndex(0)->getStyle("C$rowPlus")->applyFromArray($style);
                if (isset($value['zoneStatistics'])) {
                    $tmp = $value['zoneStatistics'];
                } else {
                    $tmp = $value['bannerStatistics'];
                }
                $row = $row + 2;
                foreach ($tmp as $dateline => $statistic) {

                    $objPHPExcel->setActiveSheetIndex(0)
                            ->setCellValue("A$row", $statistic['dateline'])
                            ->setCellValue("B$row", $statistic['count'])
                            ->setCellValue("C$row", $statistic['click']);
                    $row++;
                }

            }

            $fileName = 'Export Statistics ' . $time . '.xlsx';

            $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setAutoSize(true);

            // Export file title
            $objPHPExcel->getActiveSheet()->setTitle((new XenForo_Phrase('xcas_banner_statistics')) . '');
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet
            $objPHPExcel->setActiveSheetIndex(0);
            // Redirect output to a client’s web browser (Excel2007)
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0


            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }
}