<?php
include_once ("includes/setup.inc.php");

$program = fetch_postget_val('program',$_POST, $_GET);
$dun = fetch_postget_val('dun',$_POST, $_GET);
$tahun = fetch_postget_val('tahun',$_POST, $_GET);
$carabayar = fetch_postget_val('carabayar',$_POST, $_GET);
$current_year = date('Y');

$PDO_stmt = $PDO->prepare("SELECT * FROM i_bank WHERE aktif = 1 ORDER BY susunan");
$PDO_stmt->bindValue(1, $daerah_sc, PDO::PARAM_INT);
$PDO_stmt->execute();
$bank_List = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$bank_List[$result['id_bank']] = $result;
}

$PDO_stmt = $PDO->prepare("SELECT * FROM i_daerah WHERE aktif = 1 ORDER BY susunan");
$PDO_stmt->bindValue(1, $daerah_sc, PDO::PARAM_INT);
$PDO_stmt->execute();
$daerah_List = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$daerah_List[$result['id_daerah']] = $result;
}

if($dun > 0)
{
	$PDO_stmt = $PDO->prepare("SELECT * 
	FROM i_dun 
	WHERE id_dun > 1 
	AND id_dun = ?
	AND aktif = 1 
	ORDER BY susunan");
	$PDO_stmt->bindValue(1, $dun, PDO::PARAM_INT);
}
else
{
	$PDO_stmt = $PDO->prepare("SELECT * 
	FROM i_dun 
	WHERE id_dun > 1 
	AND aktif = 1 
	ORDER BY susunan");
}
$PDO_stmt->execute();
$dun_List = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$dun_List[$result['id_dun']] = $result;
}

$kadun_name = ($dun > 0)?$dun_List[$dun]['desk_dun']:"SEMUA";

$PDO_stmt = $PDO->prepare("SELECT * FROM i_program 
WHERE aktif = 1 
AND id_program = ?
ORDER BY susunan");
$PDO_stmt->bindValue(1, $program, PDO::PARAM_INT);
$PDO_stmt->execute();
$program_List = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$program_List[$result['id_program']] = $result;
}


//*********************************************************************************************************
//(FOR EFT)
//*********************************************************************************************************
$pemohon_List = [];

//to get i_kawalan cutoff date
$PDO_stmt = $PDO->prepare("
	SELECT *
	FROM i_kawalan
	WHERE id_program = ?
");
$PDO_stmt->bindValue(1, $program, PDO::PARAM_INT);
$PDO_stmt->execute();
$queryList_EFT = [];
$queryList_Tunai = [];
while($res = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	if(in_array($carabayar, array(2,3)))
	{
		$cutoff = $res['tkh_cutoff_EFT'];
		$cutoff_saheft = $res['tkh_cutoff_sah_EFT'];
		$cutoff_aktif = $res['tkh_cutoff_aktifmohon'];
		$tahun_bayar = $tahun;
		$select_column = "SELECT A.*, i_daerah.id_daerah, i_dun.id_dun, i_daerah.desk_daerah, i_dun.desk_dun";
		$query = getNonBayarEftQuery($PDO, $select_column, $cutoff, $cutoff_saheft, $tahun_bayar, $cutoff_aktif);
		//$query .= ' AND A.id_program = '.$res['id_program'];
		if($tahun_bayar != $current_year)
		{
			$query .= ' AND A.id_program_ori = '.$res['id_program'];
		}
		else
		{
			$query .= ' AND A.id_program = '.$res['id_program'];
		}
		if($dun > 0)
		{
			$query .= ' AND A.id_dun = '.$dun;
		}
		$query .= ' ORDER BY A.nama_pemohon, i_daerah.desk_daerah, i_dun.desk_dun';
		$queryList_EFT[] = $query;
	}
	
	if(in_array($carabayar, array(1,3)))
	{
		$cutoff = $res['tkh_cutoff_tunai'];
		$cutoff_saheft = $res['tkh_cutoff_sah_EFT'];
		$cutoff_aktif = $res['tkh_cutoff_aktifmohon'];
		$tahun_bayar = $tahun;
		$select_column = "SELECT A.*, i_daerah.id_daerah, i_dun.id_dun, i_daerah.desk_daerah, i_dun.desk_dun";
		$query = getNonBayarTunaiQuery($PDO, $select_column, $cutoff, $cutoff_saheft, $tahun_bayar, $cutoff_aktif);
		//$query .= ' AND A.id_program = '.$res['id_program'];
		if($tahun_bayar != $current_year)
		{
			$query .= ' AND A.id_program_ori = '.$res['id_program'];
		}
		else
		{
			$query .= ' AND A.id_program = '.$res['id_program'];
		}
		if($dun > 0)
		{
			$query .= ' AND A.id_dun = '.$dun;
		}
		$query .= ' ORDER BY A.nama_pemohon, i_daerah.desk_daerah, i_dun.desk_dun';
		$queryList_Tunai[] = $query;
	}
}

foreach ($queryList_EFT as $queries)
{
	$PDO_stmt2 = $PDO->prepare($queries);
	$PDO_stmt2->execute();
	while($result = $PDO_stmt2->fetch(PDO::FETCH_ASSOC))
	{
		$result['cara_bayar'] = 'EFT';
		if($result['id_byrkepada'] == 2)
		{
			$result['cara_bayar'] = 'EFT (KEPADA WARIS)';
		}
		$pemohon_List[] = $result;
	}
}

foreach ($queryList_Tunai as $queries)
{
	$PDO_stmt2 = $PDO->prepare($queries);
	$PDO_stmt2->execute();
	while($result = $PDO_stmt2->fetch(PDO::FETCH_ASSOC))
	{
		$result['cara_bayar'] = 'TUNAI';
		if($result['id_carabayar'] == 2)
		{
			$result['cara_bayar'] = 'EFT (LEPAS TARIKH CUT OFF)';
		}
		$pemohon_List[] = $result;
	}
}

//*********************************************************************************************************
//END (FOR TUNAI)
//*********************************************************************************************************

//***********************************************************************************************************************
// PRINT EXCEL
//***********************************************************************************************************************

$AUTHOR = 'jj';
$TITLE = 'SENARAI PENERIMA BELUM DIBAYAR TAHUN '.$tahun.' '.$program_List[$program]['kod_program'].' KADUN '.$kadun_name;
$FILE_NAME = str_replace(' ', '_', $TITLE);

/** Error reporting */
//error_reporting(E_ALL);
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);
//$objPHPExcel->getDefaultStyle()->getFont()->setBold(true); //set all bold

// 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

//***********************************************************************************************************************
//PART 1
//***********************************************************************************************************************
//print table header
$START_COLUMN = 1; //normally start at 0
$END_COLUMN = 9; //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

//set anything before print table
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $ROW_INDEX++, $TITLE);
$ROW_INDEX++; //move to next row
$ROW_INDEX++; //move to next row

$START_ROW = $ROW_INDEX;
$MY_COLUMN = $START_COLUMN;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Bil');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Nama Pemohon');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'KP Baru');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Daerah');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Kadun');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Cara Bayar');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'No Tel');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Bank');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'No Akaun');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Tarikh Pengesahan');
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, 'Tarikh Pengesahan EFT');
$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$ROW_INDEX.':'.PHPExcel_Cell::stringFromColumnIndex($MY_COLUMN - 1).($ROW_INDEX))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('F4D03F');
$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$ROW_INDEX.':'.PHPExcel_Cell::stringFromColumnIndex($MY_COLUMN - 1).($ROW_INDEX))->getFont()->setBold(true);
$ROW_INDEX++; //move to next row

$MY_COLUMN = $START_COLUMN;
$counter = 1;
$jumlah_list = [];
foreach ($pemohon_List as $dKey => $item)
{
	$MY_COLUMN = $START_COLUMN;
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $counter);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $item['nama_pemohon']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $item['kpbaru_pemohon']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $item['desk_daerah']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $item['desk_dun']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $item['cara_bayar']);
	$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $item['tel_hp'], PHPExcel_Cell_DataType::TYPE_STRING);
	
	$bankinfo = $bank_List[$item['id_bank']]['desk_bank'];
	$accinfo = $item['no_akaun'];
	
	if($item['id_byrkepada'] == 2)
	{
		$indicator_Query = "SELECT A.nama_waris, A.id_bankwaris, A.no_akaunwaris, B.desk_bank
						  FROM m_waris A
						  LEFT JOIN i_bank B ON B.id_bank = A.id_bankwaris
						  WHERE A.id_pemohon = ?
						  AND A.status = 1";
		$PDO_stmt = $PDO->prepare($indicator_Query);
		$PDO_stmt->bindValue(1, $item['id_pemohon'], PDO::PARAM_STR);
		$PDO_stmt->execute();
		$waris_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
		
		$bankinfo = $waris_List['nama_waris'].' - '.$waris_List['desk_bank'];
		$accinfo = $waris_List['no_akaunwaris'];
	}
	
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $bankinfo);
	$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($MY_COLUMN++, $ROW_INDEX, $accinfo, PHPExcel_Cell_DataType::TYPE_STRING);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, formatDate($item['tkh_sah'],'d M Y'));
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($MY_COLUMN++, $ROW_INDEX, formatDate($item['tkh_saheft'],'d M Y'));
	
	$counter++;
	$ROW_INDEX++;
}

$END_ROW = $ROW_INDEX - 1;
//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);

//set border and alignment for table
$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$START_ROW.':'.PHPExcel_Cell::stringFromColumnIndex($MY_COLUMN - 1).$END_ROW)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle($START_COLUMN_ALPHABET.$START_ROW.':'.PHPExcel_Cell::stringFromColumnIndex($MY_COLUMN - 1).$END_ROW)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

//***********************************************************************************************************************
//END PART 1
//***********************************************************************************************************************

// 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);
	
}
//$objPHPExcel->getActiveSheet()->getColumnDimension($START_COLUMN_ALPHABET.':'.$END_COLUMN_ALPHABET)->setAutoSize(true);

// Redirect output to a client抯 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;
//***********************************************************************************************************************
// END PRINT EXCEL
//***********************************************************************************************************************

?>

