<?php
include "../config/conn.php";
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

if (PHP_SAPI == 'cli')
	die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../lib/PHPExcel.php';
require_once dirname(__FILE__) . '/../lib/PHPExcel/IOFactory.php';
// Create new PHPExcel object
//$objPHPExcel = new PHPExcel();
$objPHPExcel = PHPExcel_IOFactory::load("../file/templateDownloadTMAmks.xls");
$objWorksheet = $objPHPExcel->getActiveSheet();

/*$objWorksheet->fromArray(
	array(
		array('',	2010,	2011,	2012),
		array('Q1',   12,   15,		21),
		array('Q2',   56,   73,		86),
		array('Q3',   52,   61,		69),
		array('Q4',   30,   32,		0),
	)
);*/

$baseRow = 8;
$startRow = $baseRow;
$endRow = $baseRow;
$sql="SELECT DISTINCT ReceivedDate,jam_value AS ReceivedTime,UNIX_TIMESTAMP(CONCAT(ReceivedDate,'-',DATE_FORMAT(a.ReceivedTime,'%H:0'))) AS tgl,max(a.WLevel) AS WLevel, FORMAT(a.WLevel*100,0) AS klWLevel,ML,a.ML,a.Ph,a.WTemp,a.ATemp,a.AHum,a.Tds,a.Vib,Rain
FROM ".$_GET['pos']." AS a
INNER JOIN m_jam AS b ON DATE_FORMAT(b.jam_value,'%H:0') = DATE_FORMAT(a.ReceivedTime,'%H:0')
WHERE 1=1 AND a.WLevel!=0 AND a.WLevel>=1 AND a.ReceivedDate>='".$_GET['tgls']."' AND a.ReceivedDate<='".$_GET['tglf']."' GROUP BY ReceivedDate,jam_value
ORDER BY a.ReceivedDate ASC,b.jam_value ASC";
$query2=mysql_query($sql);
$rowx = mysql_fetch_array($query2);
$sqll=mysql_query("SELECT * FROM m_lokasi WHERE nama_lokasi='".$_GET['pos']."'");
$ambill=mysql_fetch_array($sqll);
if (mysql_num_rows($query2) > 0 ) {
    $no = 1;
	$total=0;
	$objPHPExcel->setActiveSheetIndex(0)
          ->setCellValue('C'.'4', $ambill['nama_alat'])
          ->setCellValue('C'.'5', date('d/m/Y',strtotime($_GET['tgls']))." sampai ".date('d/m/Y',strtotime($_GET['tglf'])));
	$query4=mysql_query($sql);
	while($row = mysql_fetch_array($query4) ) 
	{
//PH				
if($row['Ph']==7){ $stsph="Netral";}
else if($row['Ph']>7){ $stsph="Basa";}
else if($row['Ph']<7){ $stsph="Asam";}
//TDS
if($row['Tds']==0 || $row['Tds']<50){ $ststds="Ideal Drinking";}
else if($row['Tds']>50 || $row['Tds']<=100){ $ststds="Normal";}
else if($row['Tds']>101 || $row['Tds']<=400){ $ststds="Kemungkinan Berbahaya";}
else if($row['Tds']>401){ $ststds="Potensi Berbahaya";}

$tma=$row['WLevel']+$ambill['kalibrasi'];
if($ambill['nama_lokasi']=="aptechv4_a3"){$atemp=$row['ML']+1; }
else if($ambill['nama_lokasi']=="aptechv4_a2"){$atemp=$row['WTemp']-50; } else {$atemp=$row['WTemp'];}

		$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('B'.$baseRow, $no)
            ->setCellValue('C'.$baseRow, $row['ReceivedDate'])
            ->setCellValue('D'.$baseRow, date('H:i',strtotime($row['ReceivedTime'])))
            ->setCellValue('E'.$baseRow, number_format($tma/100,2))
            ->setCellValue('F'.$baseRow, number_format($row['Rain'],1))
            ->setCellValue('G'.$baseRow, number_format($row['Ph'],1)."-".$stsph)
            ->setCellValue('H'.$baseRow, number_format($atemp,1))
            ->setCellValue('I'.$baseRow, number_format($row['ATemp'],1))
            ->setCellValue('J'.$baseRow, number_format($row['AHum'],0))
            ->setCellValue('K'.$baseRow, number_format($row['Tds'],0)."-".$ststds)
            ->setCellValue('L'.$baseRow, number_format($row['Vib'],0))
            ->setCellValue('M'.$baseRow, number_format($row['ML'],0));
        $baseRow++;

        $no++;

    }

} else {

    

}

//die();
//=================MEMBUAT GRAFIK ================
$dataSeriesLabels1 = array(
    new PHPExcel_Chart_DataSeriesValues(
        'String',
        'Worksheet!$E$7',
        NULL,
        1),
);
$xAxisTickValues1 = array(
    new PHPExcel_Chart_DataSeriesValues(
        'String',
        'Worksheet!$B$8:$B$15',
        NULL,
        3)
);
$dataSeriesValues1 = array(
    new PHPExcel_Chart_DataSeriesValues(
        'Number',
        'Worksheet!$E$8:$E$15',
        NULL,
        3),
);

$series1 = new PHPExcel_Chart_DataSeries(
    PHPExcel_Chart_DataSeries::TYPE_LINECHART, // Tipe Chart
    NULL, // Grouping (Pie charts tidak ada grouping)
    range(0, count($dataSeriesValues1)-1), // Urutan Chart
    $dataSeriesLabels1, // Data Label
    $xAxisTickValues1,  // Data Sumbu X
    $dataSeriesValues1  // Nilai Data
);

// Pengaturan tampilan objek (layout) untuk diagram Pie.
$layout1 = new PHPExcel_Chart_Layout();
$layout1->setShowVal(TRUE);
$layout1->setShowPercent(TRUE);
// Masukkan seri data dalam area plot.
// Area plot akan mengambil data layout dan di gabung dengan data seri
// yang sebelumnya sudah di tentukan.
$plotArea1 = new PHPExcel_Chart_PlotArea(
    $layout1,
    array($series1)
);
// Tentukan legend chart
$legend1 = new PHPExcel_Chart_Legend(
    PHPExcel_Chart_Legend::POSITION_RIGHT,
    NULL,
    false
);
// Tentukan judul chart
$title1 = new PHPExcel_Chart_Title('Statistik Data SIDT');
 
// Pembuatan chart
$chart1 = new PHPExcel_Chart(
    'nama-chartnya', // Nama chart
    $title1,    // Judul chart
    $legend1,   // Legend chart
    $plotArea1, // Area plot
    true, // plotVisibleOnly
    0,    // displayBlanksAs
    NULL, // Label sumbu X
    NULL  // Label sumbu Y - Diagram pie tidak ada sumbu Y
);
 
// Set posisi titik kiri atas dan kanan bawah chart
// Fungsinya untuk menentukan lokasi dibuatnya chart
$chart1->setTopLeftPosition('O7');
$chart1->setBottomRightPosition('U20');
 
// Tambahkan chart ke dalam Worksheet
$objWorksheet->addChart($chart1);
//===================== AKHIR GRAFIK ==============

$objPHPExcel->setActiveSheetIndex(0);
ob_clean();

// Redirect output to a client’s web browser (Excel5)
//header('Content-Type: application/vnd.ms-excel');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

header('Content-Disposition: attachment;filename="DataTMA'.$ambill['nama_alat'].'.xls"');
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 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->setIncludeCharts(TRUE);
$objWriter->save('php://output');
exit; 
?>