<?php
if($_COOKIE['sejahtera_role'] == 10)
{
	include_once ("includes/setup_pemohon.inc.php");
}
else
{
	include_once ("includes/setup.inc.php");
}
$myID = fetch_postget_val('id',$_POST, $_GET);
$id_program = fetch_postget_val('program',$_POST, $_GET);

$indicator_Query = "SELECT A.*, B.nama AS nama_terima, C.desk_dun AS dun_terima, D.desk_daerah AS daerah_terima, E.nama AS nama_sah, F.desk_dun AS dun_sah, G.desk_daerah AS daerah_sah, H.nama AS nama_saheft, I.desk_dun AS dun_saheft, J.desk_daerah AS daerah_saheft, K.desk_program
				  FROM m_pemohon A
				  LEFT JOIN t_pengguna B ON B.id_pengguna = A.id_terima
				  LEFT JOIN i_dun C ON C.id_dun = B.id_dun
				  LEFT JOIN i_daerah D ON D.id_daerah = B.id_daerah
				  LEFT JOIN t_pengguna E ON E.id_pengguna = A.id_sah
				  LEFT JOIN i_dun F ON F.id_dun = E.id_dun
				  LEFT JOIN i_daerah G ON G.id_daerah = E.id_daerah
				  LEFT JOIN t_pengguna H ON H.id_pengguna = A.id_saheft
				  LEFT JOIN i_dun I ON I.id_dun = H.id_dun
				  LEFT JOIN i_daerah J ON J.id_daerah = H.id_daerah
				  LEFT JOIN i_program K ON K.id_program = A.id_program
				  WHERE A.id_pemohon = ? AND A.id_program = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $myID, PDO::PARAM_INT);
$PDO_stmt->bindValue(2, $id_program, PDO::PARAM_INT);
$PDO_stmt->execute();
$indicator_List['m_pemohon'] = $PDO_stmt->fetch(PDO::FETCH_ASSOC);

$indicator_Query = "SELECT *
				  FROM m_waris
				  WHERE status = 1 AND id_pemohon = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $myID, PDO::PARAM_INT);
$PDO_stmt->execute();
$indicator_List['m_waris'] = $PDO_stmt->fetch(PDO::FETCH_ASSOC);


//get all borang info
$indicator_Query = "SELECT *
				  FROM u_borangdiv 
				  WHERE id_borangdiv NOT IN (1,2,8,9)
				  ORDER BY susunan";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->execute();
$borangDivList = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$borangDivList[$result['id_borangdiv']] = $result;
}

$indicator_Query = "SELECT B.*, A.is_check_input
				  FROM u_pautanborang A
				  LEFT JOIN u_borangitem B ON A.id_borangitem = B.id_borangitem
				  WHERE A.id_program = ?
				  AND B.linked_borangitem = 0
				  AND B.id_inputtype IN (1, 8, 20, 2, 3, 17, 11, 18)
				  ORDER BY B.susunan";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $id_program, PDO::PARAM_INT);
$PDO_stmt->execute();
$borangList = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$borangList[$result['id_borangdiv']][] = $result;
}

$borangTabMenu = [];
foreach($borangDivList as $div_key => $div_item)
{
	if(count($borangList[$div_key]) > 0)
	{
		$borangTabMenu[$div_key] = $div_item;
	}
}

//var_dump($indicator_List);
//***********************************************************************************************************************
// PRINT PDF
//***********************************************************************************************************************
require_once('classes/tcpdf/config/tcpdf_config.php');
require_once('classes/tcpdf/tcpdf.php');
include_once ("classes/phpqrcode/qrlib.php");

$errorCorrectionLevel ='L';
$matrixPointSize = 1;
$url = $indicator_List['m_pemohon']['kpbaru_pemohon'];
$filename = 'qrcodes/'.$indicator_List['m_pemohon']['kpbaru_pemohon'].'.png';
QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 1);	

//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;
	}
	//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);
		/*
		$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);
		$this->MultiCell(0, 0, 'Muka Surat '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, 'R', 0, 1, '', '', true);
	}
}

// -----------------------------------------------------------------------------
// create new PDF document
$pdf = new MYPDF("P", PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); //P for portrait, L for landscape
$TITLE = 'BORANG PERMOHONAN '.$indicator_List['m_pemohon']['desk_program'];
$FILE_NAME = 'BORANG PERMOHONAN';
$output_filename = "borang_".$indicator_List['NoKPPemohon'].".pdf";
$pdf->setHeaderTitle($TITLE);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('PSUKPP');
$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 - 10;
}
//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 - 10);

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

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

$HTML = '<table border="0" style="width:100%;padding:5px;">';
$HTML .= '<tr>';
$HTML .= '<td>';
$HTML .= '<img src="'.$filename.'" style="width:90px;height:90px">';	
$HTML .= '</td>';
$HTML .= '</tr>';
$HTML .= '</table>';
$pdf->writeHTMLCell(0, 0, '', '', $HTML, 0, 1, 0, true, 'L', false);

foreach($borangTabMenu as $div_key => $div_item)
{
	$HTML = '<table border="0" style="width:100%;padding:5px;border:1px solid black;">';
	$HTML .= '<tr>';
	$HTML .= '<td style="text-align:left;border:1px solid black" colspan="3"><h3>'.$div_item['title'].'</h3></td>';
	$HTML .= '</tr>';
	
	$isset_nosiri = 0;
	foreach($borangList[$div_item['id_borangdiv']] as $key => $item)
	{
		if($isset_nosiri == 0 && $div_key == 3)
		{
			$currentValue = $indicator_List[$div_item['main_table']]['no_siri'];
			$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">No. Siri</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.(($currentValue=='')?'-':$currentValue).'</b></td>';
			$HTML .= '</tr>';
			$isset_nosiri = 1;
		}
		
		if($item['id_inputtype'] == 18) //checkbox
		{
			$HTML .= '<tr>';
			$HTML .= '<td colspan="3">';
			$HTML .= '<input type="checkbox" checked="checked"/>';
			$HTML .= $item['label'];
			$HTML .= '</td>';
			$HTML .= '</tr>';
		}
		else if($item['id_inputtype'] == 17) //dropzone
		{
			//get all dokumen from pemohon folder
			$path = 'upload_pemohon/'.$myID.'/*';
			$images = glob($path);
			for($num = 0; $num < count($images); $num++)
			{
				$HTML .= '<tr>';
				$HTML .= '<td style="width:20%">'.($num + 1).'.<td>';
				$HTML .= '<td style="width:2%"></td>';
				$HTML .= '<td><a href="'.$images[$num].'" target="_blank">'.end(explode('/', $images[$num])).'</a></td>';
				$HTML .= '</tr>';
			}
		}
		else if($item['id_inputtype'] == 11) //datatable
		{
			$indicator_Query = "SELECT *
							  FROM u_datatableitem 
							  WHERE id_borangitem = ".$item['id_borangitem'].' order by datatable_index';
			$PDO_stmt = $PDO->prepare($indicator_Query);
			$PDO_stmt->execute();
			$datatableItemList = [];
			while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
			{
				$datatableItemList[$result['type']][] = $result;
			}
			
			$indicator_Query = "SELECT *
								FROM {$datatableItemList[1][0]['table_name']} 
								WHERE id_pemohon = {$myID}";
			$PDO_stmt = $PDO->prepare($indicator_Query);
			$PDO_stmt->execute();
			$datatableResultList = [];
			$count = 1;
			$HTML .= '<tr>';
			$HTML .= '<td colspan="3">';
			//$HTML .= $indicator_Query;
			
			$HTML .= '<table border="1" style="width:100%;text-align:center">';
				$HTML .= '<tr>';
					$HTML .= '<th>Bil</th>';
					foreach($datatableItemList[3] as $dtKey=>$dtItem)
					{
						$HTML .= '<th>'.$dtItem['column_label'].'</th>';
					}
				$HTML .= '</tr>';
				
				while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
				{
					$HTML .= '<tr>';
						$HTML .= '<td>'.($count++).'</td>';
						foreach($datatableItemList[3] as $dtKey=>$dtItem)
						{
							$HTML .= '<td>'.$result[$dtItem['column_name']].'</td>';
						}
					$HTML .= '</tr>';
				}
				
			$HTML .= '</table>';
			
			$HTML .= '</td>';
			$HTML .= '</tr>';
		}
		else
		{
			$HTML .= '<tr>';
				$currentValue = '-';
				switch ($item['id_inputtype']) 
				{
					case '1': //textbox
					case '8': //textbox uncopyable
					case '20': //date textbox
						$currentValue = $indicator_List[$div_item['main_table']][$item['value']];
					break;
					
					case '2': //dropdown
						$tableName = $item['extra_param'];
						$name = 'desk_';
						$identifier = explode("_", $tableName);
						$indicator_Query = "SELECT id_{$identifier[1]} AS id, concat({$name}{$identifier[1]}) as name
											FROM {$tableName}
											WHERE aktif = 1 AND id_{$identifier[1]} = ?
											ORDER BY susunan";
						$PDO_stmt = $PDO->prepare($indicator_Query);
						$PDO_stmt->bindValue(1, $indicator_List[$div_item['main_table']][$item['value']], PDO::PARAM_INT);
						$PDO_stmt->execute();
						$ddResult = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
						$currentValue = $ddResult['name'];
					break;
					
					case '3': //dropdown_sql
						$PDO_stmt = $PDO->prepare($item['extra_param']);
						$PDO_stmt->execute();
						while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
						{
							if($result['id'] == $indicator_List[$div_item['main_table']][$item['value']])
							{
								$currentValue = $result['name'];
								break;
							}
						}
					break;
				}
				$HTML .= '<td style="width:30%">'.$item['label'].'</td>';
				$HTML .= '<td style="width:2%">:</td>';
				$HTML .= '<td style="width:68%"><b>'.(($currentValue=='')?'-':$currentValue).'</b></td>';
			$HTML .= '</tr>';
			
			if($currentValue != '' && $item['value'] == 'tkh_lahir')
			{
				$createDate = new DateTime($currentValue);
				$todayDate = new DateTime(date('Y-m-d'));
				$diff = $todayDate->diff($createDate)->format("%y");
				$HTML .= '<tr>';
					$HTML .= '<td>Umur</td>';
					$HTML .= '<td>:</td>';
					$HTML .= '<td><b>'.$diff.'</b></td>';
				$HTML .= '</tr>';
			}
		}
	}
	$HTML .= '</table>';
	$HTML .= '<br><br>';
	$pdf->writeHTMLCell(0, 0, '', '', $HTML, 0, 1, 0, true, 'L', false);
}

if($indicator_List['m_pemohon']['id_statusmohon'] >= 2)
{
	$HTML = '<table border="0" style="width:100%;padding:5px;border:1px solid black;">';
	$HTML .= '<tr>';
	$HTML .= '<td style="text-align:left;border:1px solid black" colspan="3"><h3>Maklumat Pengesahan</h3></td>';
	$HTML .= '</tr>';
	$HTML .= '<tr>';
		$HTML .= '<td style="width:30%">Tarikh Daftar</td>';
		$HTML .= '<td style="width:2%">:</td>';
		$HTML .= '<td style="width:68%"><b>'.formatDate($indicator_List['m_pemohon']['tkh_daftar'],'d M Y').'</b></td>';
	$HTML .= '</tr>';
	if($indicator_List['m_pemohon']['id_terima'] > 0)
	{						
		$dun_terima = '<br>KADUN : '.$indicator_List['m_pemohon']['dun_terima'];
		$daerah_terima = '<br>DAERAH : '.$indicator_List['m_pemohon']['daerah_terima'];			
		if($indicator_List['m_pemohon']['dun_terima'] == '')
		{											
			$dun_terima = '';
		}			
		if($indicator_List['m_pemohon']['daerah_terima'] == '')
		{											
			$daerah_terima = '';
		}
		
		$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">Tarikh Terima Dokumen</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.formatDate($indicator_List['m_pemohon']['tkh_terima'],'d M Y').'</b></td>';
		$HTML .= '</tr>';		
		$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">Pegawai Terima Dokumen</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.$indicator_List['m_pemohon']['nama_terima'].$dun_terima.$daerah_terima.'</b></td>';
		$HTML .= '</tr>';
	}
	if($indicator_List['m_pemohon']['id_sah'] > 0)
	{	
		$dun_sah = '<br>KADUN : '.$indicator_List['m_pemohon']['dun_sah'];
		$daerah_sah = '<br>DAERAH : '.$indicator_List['m_pemohon']['daerah_sah'];
		
		if($indicator_List['m_pemohon']['dun_sah'] == '')
		{											
			$dun_sah = '';
		}
		
		if($indicator_List['m_pemohon']['daerah_sah'] == '')
		{											
			$daerah_sah = '';
		}
		
		$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">Tarikh Pengesahan</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.formatDate($indicator_List['m_pemohon']['tkh_sah'],'d M Y').'</b></td>';
		$HTML .= '</tr>';		
		$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">Pegawai Pengesahan</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.$indicator_List['m_pemohon']['nama_sah'].$dun_sah.$daerah_sah.'</b></td>';
		$HTML .= '</tr>';
	}
	if($indicator_List['m_pemohon']['id_saheft'] > 0)
	{	
		$dun_saheft = '<br>KADUN : '.$indicator_List['m_pemohon']['dun_saheft'];
		$daerah_saheft = '<br>DAERAH : '.$indicator_List['m_pemohon']['daerah_saheft'];
		
		if($indicator_List['m_pemohon']['dun_saheft'] == '')
		{											
			$dun_saheft = '';
		}
		
		if($indicator_List['m_pemohon']['daerah_saheft'] == '')
		{											
			$daerah_saheft = '';
		}
		
		$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">Tarikh Pengesahan EFT</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.formatDate($indicator_List['m_pemohon']['tkh_saheft'],'d M Y').'</b></td>';
		$HTML .= '</tr>';		
		$HTML .= '<tr>';
			$HTML .= '<td style="width:30%">Pegawai Pengesahan EFT</td>';
			$HTML .= '<td style="width:2%">:</td>';
			$HTML .= '<td style="width:68%"><b>'.$indicator_List['m_pemohon']['nama_saheft'].$dun_saheft.$daerah_saheft.'</b></td>';
		$HTML .= '</tr>';
	}
	$HTML .= '</table>';
	$HTML .= '<br><br>';
	$pdf->writeHTMLCell(0, 0, '', '', $HTML, 0, 1, 0, true, 'L', false);
}

if($indicator_List['m_pemohon']['id_statushidup'] == 2)
{
	$HTML = '<table border="0" style="width:100%;padding:5px;border:1px solid black;">';
	$HTML .= '<tr>';
	$HTML .= '<td style="text-align:left;border:1px solid black" colspan="3"><h3>Khairat Kematian</h3></td>';
	$HTML .= '</tr>';
	$HTML .= '<tr>';
		$HTML .= '<td style="width:30%">Umur</td>';
		$HTML .= '<td style="width:2%">:</td>';
		$HTML .= '<td style="width:68%"><b>'.$diff.'</b></td>';
	$HTML .= '</tr>';
	$HTML .= '</table>';
	$HTML .= '<br><br>';
	$pdf->writeHTMLCell(0, 0, '', '', $HTML, 0, 1, 0, true, 'L', false);
}

$HTML = '<table border="0" style="width:100%;padding:5px;">';
$HTML .= '<tr>';
$HTML .= '<td>';
$HTML .= '<img src="'.$filename.'" style="width:90px;height:90px">';	
$HTML .= '</td>';
$HTML .= '</tr>';
$HTML .= '</table>';
$pdf->writeHTMLCell(0, 0, '', '', $HTML, 0, 1, 0, true, 'L', false);

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

//***********************************************************************************************************************
// END PRINT PDF
//***********************************************************************************************************************

?>