<?php
//***********************************************************************************************************************
// PRINT PDF
//***********************************************************************************************************************
if($_POST['printType'] == 0)
{
	require_once('classes/tcpdf/config/tcpdf_config.php');
	require_once('classes/tcpdf/tcpdf.php');

	//include_once ("inc/setup.inc.php");
	error_reporting(0);

	// Extend the TCPDF class to create custom Header and Footer
	class MYPDF extends TCPDF {

		private $myHeaderTitle = array();
		public function setHeaderTable($headerArray)
		{
			$this->myHeaderTitle = array();
			for( $num = 0 ; $num < count($headerArray) ; $num++ )
			{
				$this->myHeaderTitle[] = $headerArray[$num];
			}
		}
		
		private $pageTitle = '';
		public function setHeaderTitle($title)
		{
			$this->pageTitle = $title;
		}
		private $subHeaderTitle = '';
		public function setSubHeaderTitle($title)
		{
			$this->subHeaderTitle = $title;
		}
		//Page header
		public function Header() {
					
			$this->SetFont('helveticaB', '', 14); //CHANGE THIS FOR TITLE FONT
			$this->MultiCell(0, 0, $this->pageTitle, 0, 'C', 0, 1, '', '', true);
			if($this->subHeaderTitle != '')
			{
				$this->SetFont('helvetica', '', 10); //CHANGE THIS FOR TITLE FONT
				$this->MultiCell(0, 0, $this->subHeaderTitle, 0, 'C', 0, 1, '', '', true);
			}
			
			$HTML = '<table border="1" style="text-align:center;padding: 6px;">';
			$HTML .= '<tr style="font-weight: bold;">';
			$counter = 1;
			for( $num = 0 ; $num < count($this->myHeaderTitle) ; $num++ )
			{
				if($this->myHeaderTitle[$num][1] > 0)
				{
					$HTML .= '<th style="width:'.$this->myHeaderTitle[$num][1].'%">'.$this->myHeaderTitle[$num][0].'</th>';
				}
			}
			$HTML .= '</tr>';
			$HTML .= '</table>';
			$this->SetFont('helvetica', '', 10); //CHANGE THIS FOR HEADER TITLE FONT
			$this->writeHTMLCell(0, 0, '', 19, $HTML, 0, 0, 0, true, '', false);
		}

		// Page footer
		public function Footer() {
			
			// Position at 15 mm from bottom
			$this->SetFont('helvetica', '', 8);
			
			$HTML = '<table border="0" style="padding: 3px;">';
			$HTML .= '<tr>';
				$HTML .= '<td style="width:50%">Cetakan : '.dateTimeNow().'</td>';
				$HTML .= '<td style="width:50%;text-align:right">Muka Surat '.$this->getAliasNumPage().'/'.$this->getAliasNbPages().'</td>';
			$HTML .= '</tr>';
			$HTML .= '</table>';
			$this->SetFont('helvetica', '', 10); //CHANGE THIS FOR HEADER TITLE FONT
			$this->writeHTMLCell(0, 0, '', '', $HTML, 0, 0, 0, true, '', false);
			
			//$this->MultiCell(0, 0, 'Dicetak pada '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, 'L', 0, 1, '', '', true);
			//$this->MultiCell(0, 0, 'Muka Surat '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, 'R', 0, 1, '', '', true);
		}
	}
	
	// -----------------------------------------------------------------------------
	// create new PDF document
	$pdf = new MYPDF($PAGE_ORIENTATION==''?"L":$PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); //P for portrait, L for landscape
	$pdf->setHeaderTitle($myTitle);
	$pdf->setSubHeaderTitle($mySubHeaderTitle);
	$pdf->setHeaderTable($headerTitle);
	
	// set document information
	$pdf->SetCreator(PDF_CREATOR);
	$pdf->SetAuthor($AUTHOR);
	$pdf->SetTitle($TITLE);
	$pdf->SetSubject($TITLE);
	$pdf->SetKeywords('TCPDF, PDF, $TITLE');

	// set default header data
	$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

	// set header and footer fonts
	$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
	$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

	// set default monospaced font
	$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

	if($manual_TOP <= 0)
	{
		$manual_TOP = PDF_MARGIN_TOP;
	}
	//set margins
	//$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
	$pdf->SetMargins(5, $manual_TOP, 5);
	$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
	$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

	//set auto page breaks
	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

	//set image scale factor
	$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

	//set some language-dependent strings
	$pdf->setLanguageArray($l);

	// -----------------------------------------------------------------------------
	$pdf->setCellPaddings(0, 0, 0, 0);
	$pdf->AddPage();
	// MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0)
	$pdf->SetFont('helvetica', '', 10); //same font for the whole pdf
	
	$counter = 1; //FOR BIL
	$headerCounter = 0;
	$HTML = '<table border="1" style="text-align:center;padding: 6px;">';
	for( $num = 0 ; $num < count($dataArray) ; $num++ )
	{
		$HTML .= '<tr>';
		if($num == 0)
		{
			$HTML .= '<td style="width:'.$headerTitle[$headerCounter++][1].'%">'.($counter++).'</td>';
		}
		else
		{
			$HTML .= '<td>'.($counter++).'</td>';
		}
		
		if(preg_match('/\_pemohon$/', $_POST['baseName']) || preg_match('/se\_meninggal/', $_POST['baseName']) || preg_match('/general\-maklumat$/', $_POST['baseName']))
		{
			for($colNum = 0 ; $colNum < count($columns) ; $colNum++)
			{
				if(isset($columns[$colNum]['skip_print']))
				{
					//do nothing
				}
				else if (isset($columns[$colNum]['print'])) //filter based on columns array
				{
					if($num == 0 && $colNum != 0)
					{
						$HTML .= '<td style="width:'.$headerTitle[$headerCounter++][1].'%">'.$dataArray[$num][$colNum].'</td>';
					}
					else
					{
						$HTML .= '<td>'.$dataArray[$num][$colNum].'</td>';
					}
				}
			}
		}
		else
		{
			for($num2 = 0 ; $num2 < count($headerTitle) ; $num2++)
			{
				if (isset($columns[$num2]['table']) || isset($columns[$num2]['print'])) //filter based on columns array
				{
					if($num == 0 && $num2 != 0)
					{
						$HTML .= '<td style="width:'.$headerTitle[$headerCounter++][1].'%">'.$dataArray[$num][$num2].'</td>';
					}
					else
					{
						$HTML .= '<td>'.$dataArray[$num][$num2].'</td>';
					}
				}
			}
		}
		$HTML .= '</tr>';
	}
	$HTML .= '</table>';
	
	// writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true)
	if($manualY)
	{
		$pdf->writeHTMLCell(0, 0, '', $manualY, $HTML, 0, 0, 0, true, '', false);
	}
	else
	{
		$pdf->writeHTMLCell(0, 0, '', '', $HTML, 0, 0, 0, true, '', false);
	}

	//Close and output PDF document
	ob_end_clean();
	$pdf->Output($FILE_NAME.'.pdf', 'I');
}
//***********************************************************************************************************************
// END PRINT PDF
//***********************************************************************************************************************


//***********************************************************************************************************************
// PRINT EXCEL
//***********************************************************************************************************************
else if($_POST['printType'] == 1)
{
	
	/** Error reporting */
	error_reporting(0);
	ini_set('display_errors', TRUE);
	ini_set('display_startup_errors', TRUE);
	date_default_timezone_set('Europe/London');

	if (PHP_SAPI == 'cli')
		die('This example should only be run from a Web Browser');

	/** Include PHPExcel */
	require_once 'classes/PHPExcel.php';

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

	// Set document properties
	$objPHPExcel->getProperties()->setCreator($AUTHOR)
								 ->setLastModifiedBy($AUTHOR)
								 ->setTitle($TITLE)
								 ->setSubject($TITLE)
								 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
								 ->setKeywords("office 2007 openxml $TITLE")
								 ->setCategory("Test result file");

								 
	//set default style
	$objPHPExcel->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
	
	// Add data
	//One can use the possibility to access cell values by column and row index like (0,1) instead of 'A1' for reading and writing cell values in loops.
	//In PHPExcel column index is 0-based while row index is 1-based. That means 'A1' ~ (0,1)
	$objPHPExcel->setActiveSheetIndex(0);
	$ROW_INDEX = 1; //use this to control row indexing
	
	//set anything before print table
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $ROW_INDEX, $myTitle);
	$ROW_INDEX++; //move to next row
	$ROW_INDEX++; //move to next row

	//print table header
	$START_COLUMN = 0; //normally start at 0
	$END_COLUMN = count($headerTitle) - 1 + $START_COLUMN; //based on number of header
	
	$START_COLUMN_ALPHABET = PHPExcel_Cell::stringFromColumnIndex($START_COLUMN); //convert to alphabet
	$END_COLUMN_ALPHABET = PHPExcel_Cell::stringFromColumnIndex($END_COLUMN); //convert to alphabet
	
	$START_ROW = $ROW_INDEX; //keep a record of start row of table
	
	for( $num = 0 ; $num < count($headerTitle) ; $num++ )
	{
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($num, $ROW_INDEX, $headerTitle[$num][0]);
	}
	$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$ROW_INDEX.':'.$END_COLUMN_ALPHABET.$ROW_INDEX)->getFont()->setBold(true); //set header to bold
	$ROW_INDEX++;
	
	//print table data
	$bilCounter = 1;
	for( $rowNum = 0 ; $rowNum < count($dataArray) ; $rowNum++ )
	{
		if(count($columns) > 5 && $dataArray[$rowNum][0] == '' && $dataArray[$rowNum][1] == '' && $dataArray[$rowNum][2] == ''  && $dataArray[$rowNum][3] == ''  && $dataArray[$rowNum][4] == '') //if first three column are empty, skip print bil (for SM_MM)
		{
			//do nothing
		}
		else
		{	
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $rowNum + $ROW_INDEX, $bilCounter++);
		}
		$colCounter = 1;
		if(preg_match('/in\_/', $_POST['baseName']))
		{
			for($colNum = 0 ; $colNum < count($headerTitle) ; $colNum++)
			{
				if(isset($columns[$colNum]['skip_print']))
				{
					//do nothing
				}
				else if (isset($columns[$colNum]['table']) || isset($columns[$colNum]['print'])) //filter based on columns array
				{
					$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($colCounter, $rowNum + $ROW_INDEX, $dataArray[$rowNum][$colNum]);
					$colCounter++;
				}
			}
		}
		else
		{
			for($colNum = 0 ; $colNum < count($columns) ; $colNum++)
			{
				if(isset($columns[$colNum]['skip_print']))
				{
					//do nothing
				}
				else if (isset($columns[$colNum]['print'])) //filter based on columns array
				{
					$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($colCounter, $rowNum + $ROW_INDEX, $dataArray[$rowNum][$colNum],PHPExcel_Cell_DataType::TYPE_STRING);
					/*
					if(isset($columns[$colNum]['isExplicit']))
					{
						$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($colCounter, $rowNum + $ROW_INDEX, '00110',PHPExcel_Cell_DataType::TYPE_STRING);
					}
					else
					{
						$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($colCounter, $rowNum + $ROW_INDEX, $dataArray[$rowNum][$colNum]);
					}
					*/
					$colCounter++;
				}
			}
		}
		/*
		for($poNum = 0 ; $poNum < count($printonlyheader) ; $poNum++)
		{
			$colNum = $printonlyheader[$poNum][2];
			if($colNum >= 0)
			{
				if(isset($columns[$colNum]['skip_print']))
				{
					//do nothing
				}
				else if (isset($columns[$colNum]['table']) || isset($columns[$colNum]['print'])) //filter based on columns array
				{
					$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($colCounter, $rowNum + $ROW_INDEX, $dataArray[$rowNum][$colNum]);
					$colCounter++;
				}
			}
		}
		*/
		
	}
	$ROW_INDEX += count($dataArray) - 1;
	$END_ROW = $ROW_INDEX; //keep a record of end row of table
	
	//set border and alignment for table
	$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$START_ROW.':'.$END_COLUMN_ALPHABET.$END_ROW)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
	$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$START_ROW.':'.$END_COLUMN_ALPHABET.$END_ROW)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$START_ROW.':'.$END_COLUMN_ALPHABET.$END_ROW)->getAlignment()->setVertical(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$START_ROW.':'.$END_COLUMN_ALPHABET.$END_ROW)->getAlignment()->setWrapText(true);

	// Rename worksheet
	$objPHPExcel->getActiveSheet()->setTitle('Table Data');

	// Set active sheet index to the first sheet, so Excel opens this as the first sheet
	$objPHPExcel->setActiveSheetIndex(0);
	
	//set auto width
	for( $colNum = $START_COLUMN ; $colNum <= $END_COLUMN ; $colNum++ )
	{
		$objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($colNum))->setAutoSize(true);
	}
	
	//set auto height
	$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(-1);
	
	//$objPHPExcel->getActiveSheet()->getColumnDimension($START_COLUMN_ALPHABET.':'.$END_COLUMN_ALPHABET)->setAutoSize(true);

	// Redirect output to a client’s web browser (Excel2007)
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header('Content-Disposition: attachment;filename="'.$FILE_NAME.'.xlsx"');
	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;
	
}
?>