<?php
require_once('../config.php');
require_once('tcpdf_include.php');

$valid = true;


$site_cd = $_REQUEST['site_cd'];
$mst_rowid = $_REQUEST['mst_rowid'];


// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 048');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
	
// set default header data
$pdf->SetHeaderData(EVNG_HEADER_LOGO, EVNG_HEADER_LOGO_WIDTH,EVNG_HEADER_TITLE);

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

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$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 (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
	require_once(dirname(__FILE__).'/lang/eng.php');
	$pdf->setLanguageArray($l);
}

// ---------------------------------------------------------

// set font
$pdf->SetFont('helvetica', 'B', 10);

// add a page
$pdf->AddPage();


$wko_mst_type;
$wko_mst_wo_no;
$wko_mst_assetno;
$asset_name;

$sql = "SELECT wko_mst_type, wko_mst_wo_no from wko_mst (NOLOCK) where RowID = '".$mst_rowid."'" ;
$stmt = sqlsrv_query( $conn, $sql);

if( !$stmt ) {
     $error_message = "Error selecting table (Work Order)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}


do {
     while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
		
		$wko_mst_type = $row['wko_mst_type'];
		$wko_mst_wo_no = $row['wko_mst_wo_no'];
		
	 }
} while ( sqlsrv_next_result($stmt) );

if($wko_mst_type == "G"){
	
	$sql = "SELECT  wko_mst_assetno, cf_site.site_name , wko_det_pm_grp from wko_mst (NOLOCK) 
	
			INNER JOIN wko_det (NOLOCK)
			ON		wko_mst.site_cd = wko_det.site_cd
			AND		wko_mst.rowid = wko_det.mst_rowid
			AND 	wko_mst_type  IN ('P')
			
			LEFT JOIN cf_site
            ON wko_mst.site_cd = cf_site.site_cd
			
			where wko_mst.RowID = '".$mst_rowid."'
			
			UNION ALL
			
			SELECT wko_mst_assetno, cf_site.site_name, wko_det_pm_grp from wko_mst (NOLOCK) 
	
			INNER JOIN wko_det (NOLOCK)
			ON		wko_mst.site_cd = wko_det.site_cd
			AND		wko_mst.rowid = wko_det.mst_rowid
			AND 	wko_mst_type  IN ('G')
			
			LEFT JOIN cf_site
            ON wko_mst.site_cd = cf_site.site_cd
			
			where wko_mst.RowID = '".$mst_rowid."'
			
			" ;
	$stmt = sqlsrv_query( $conn, $sql);

	if( !$stmt ) {
		 $error_message = "Error selecting table (Work Order)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}


	do {
		 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
			
			$wko_mst_assetno = $row['wko_mst_assetno'];

			if ($wko_mst_assetno === null || $wko_mst_assetno === '') {
				$wko_mst_assetno = $row['wko_det_pm_grp'];
			}

			$wko_det_pm_grp = $row['wko_det_pm_grp'];
			$site_name      = $row['site_name'];
			$asset_name = 'PM Group:';
			
		 }
	} while ( sqlsrv_next_result($stmt) );

	
}else{
	
	if($wko_mst_type == "C"){
		
		$sql = "SELECT  wko_mst_assetno, cf_site.site_name from wko_mst (NOLOCK) 
	
			INNER JOIN wko_det (NOLOCK)
			ON		wko_mst.site_cd = wko_det.site_cd
			AND		wko_mst.rowid = wko_det.mst_rowid
			AND 	wko_mst_type  IN ('C')
			
			LEFT JOIN cf_site
            ON wko_mst.site_cd = cf_site.site_cd
			
			where wko_mst.RowID = '".$mst_rowid."'" ;
			
		$stmt = sqlsrv_query( $conn, $sql);

		if( !$stmt ) {
			 $error_message = "Error selecting table (Work Order)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}


		do {
			 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				
				$wko_mst_assetno = $row['wko_mst_assetno'];
				$site_name = $row['site_name'];
				$asset_name = 'Asset No:';
			 }
		} while ( sqlsrv_next_result($stmt) );
		
	}else{
		
		$sql = "SELECT  wko_mst_assetno, cf_site.site_name from wko_mst (NOLOCK) 
	
			INNER JOIN wko_det (NOLOCK)
			ON		wko_mst.site_cd = wko_det.site_cd
			AND		wko_mst.rowid = wko_det.mst_rowid
			AND 	wko_mst_type  IN ('C', 'P')
			
			LEFT JOIN cf_site
            ON wko_mst.site_cd = cf_site.site_cd
			
			where wko_mst.RowID = '".$mst_rowid."'" ;
			
		$stmt = sqlsrv_query( $conn, $sql);

		if( !$stmt ) {
			 $error_message = "Error selecting table (Work Order)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}


		do {
			 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				
				$wko_mst_assetno = $row['wko_mst_assetno'];
				$site_name = $row['site_name'];
				$asset_name = 'Asset No:';
				
			 }
		} while ( sqlsrv_next_result($stmt) );
		
	}
}

// --- Custom Header Block ---
$pdf->SetFillColor(230, 230, 250); // lavender
$pdf->SetTextColor(0, 0, 128); // navy
$pdf->SetFont('helvetica', 'B', 14);
$pdf->MultiCell(0, 5, 'Planned Preventive Maintenance Checklist', 0, 'C', 1, 1);
$pdf->Ln(2);
$pdf->SetMargins(15, 20, 15);
$pdf->SetFont('helvetica', '', 10);
$pdf->SetTextColor(0, 0, 0);
$pdf->MultiCell(0, 6, "Site: $site_cd ($site_name)\nWork Order No: $wko_mst_wo_no\n$asset_name $wko_mst_assetno", 0, 'L');
$pdf->Ln(5);


$pdf->SetFont('helvetica', '', 8);


$sql = "SELECT COUNT=COUNT(*)
		FROM wko_isp 
		WHERE site_cd = '".$site_cd."' 			
		AND mst_rowid = '".$mst_rowid."'" ;
$stmt = sqlsrv_query( $conn, $sql);

if( !$stmt ) {
     $error_message = "Error selecting table (Work Order Check List)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}


do {
     while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
		
		$COUNT = $row['COUNT'];
		
	 }
} while ( sqlsrv_next_result($stmt) );


if($COUNT == 0){
	
}else{
	$sql = "SELECT  
			
			wko_isp_asset_no,
			wko_isp_job_cd,
			wko_isp_job_desc,
			wko_isp_sec_no,
			wko_isp_sec_desc,
			wko_isp_stp_no,
			wko_isp_stp_desc,
			wko_isp_stp_datatype,
			wko_isp_stp_rowid,
			wko_isp_varchar1,
			wko_isp_varchar2,
			wko_isp_varchar3,
			wko_isp_numeric1,
			wko_isp_numeric2,
			wko_isp_numeric3,
			wko_isp_datetime1,
			wko_isp_datetime2,
			wko_isp_datetime3,
			wko_isp_checkbox1,
			wko_isp_checkbox2,
			wko_isp_checkbox3,
			wko_isp_dropdown1,
			wko_isp_dropdown2,
			wko_isp_dropdown3,		
			
			
			total_asset = (Select count(*) from wko_isp where wko_isp.site_cd = A.site_cd and wko_isp_asset_no = A.wko_isp_asset_no and mst_rowid = A.mst_rowid), 
			total_job = (Select count(*) from wko_isp where wko_isp.site_cd = A.site_cd and wko_isp_asset_no = A.wko_isp_asset_no and wko_isp_job_cd = A.wko_isp_job_cd and mst_rowid = A.mst_rowid), 
			total_sec = (Select count(*) from wko_isp where wko_isp.site_cd = A.site_cd and wko_isp_asset_no = A.wko_isp_asset_no and wko_isp_job_cd = A.wko_isp_job_cd and wko_isp_sec_no = A.wko_isp_sec_no and mst_rowid = A.mst_rowid)		
			
			
			FROM wko_isp A
			WHERE site_cd = '".$site_cd."' 			
			AND mst_rowid = '".$mst_rowid."' order by wko_isp_asset_no, wko_isp_job_cd, wko_isp_sec_no,wko_isp_stp_no" ;
$stmt = sqlsrv_query( $conn, $sql);

if( !$stmt ) {
     $error_message = "Error selecting table (Work Order Check List)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}

$cnt3 = 0;
$cnt = 0;
$cnt2 = 0;
$cnt_all = 0;
$prev_job;
$prev_sec_desc;
$json = array();

do {
     while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
		$json[] = $row;
		
		
		$wko_isp_asset_no = $row['wko_isp_asset_no'];
		$wko_isp_job_cd = $row['wko_isp_job_cd'];
		$wko_isp_job_desc = $row['wko_isp_job_desc'];
		$wko_isp_sec_no = $row['wko_isp_sec_no'];
		$wko_isp_sec_desc = $row['wko_isp_sec_desc'];
		$wko_isp_stp_no = $row['wko_isp_stp_no'];
		$wko_isp_stp_desc = $row['wko_isp_stp_desc'];
		$wko_isp_stp_datatype = $row['wko_isp_stp_datatype'];
		$total_asset = $row['total_asset'];
		$total_job = $row['total_job'];
		$total_sec = $row['total_sec'];
		
		if($wko_isp_stp_datatype == 'T'){
			$type = $row['wko_isp_varchar1'];
		}else if($wko_isp_stp_datatype == 'N'){
			$type = $row['wko_isp_numeric1'];
		}else if($wko_isp_stp_datatype == 'D'){
			//$type = $row['wko_isp_datetime1']->format('d-m-Y H:i:s');
			if($row['wko_isp_datetime1'] == null){
				$type = "";
			}else{
				$type = $row['wko_isp_datetime1']->format('d-m-Y H:i');
			}
			
		}else if($wko_isp_stp_datatype == 'Z'){
			$type = $row['wko_isp_dropdown1'];
		}else if($wko_isp_stp_datatype == 'C'){
			$type = $row['wko_isp_checkbox1'];
		}
		$wko_isp_varchar2 = $row['wko_isp_varchar2'];
		
		$cnt3 = $cnt3 + 1;
		$cnt = $cnt + 1;
		$cnt2 = $cnt2 + 1;
		$cnt_all = $cnt_all + 1;
		
		//ASSET
		if ($cnt3 == 1) {
			if (empty($asset)){
				$asset = $wko_isp_asset_no;
				$prev_asset = $wko_isp_asset_no;
			}
			else{
				$asset = "";	
			}
		}elseif($cnt3 >= 2){
			if ($prev_asset == $wko_isp_asset_no) {
				$asset = "";
			}else{
				$asset = $wko_isp_asset_no;
				$prev_asset = $wko_isp_asset_no;
				$cnt3 = 1;
			}
		}
		
		
		//JOB CODE
		if ($cnt == 1) {
			if (empty($job_cd)){
				$asset2 = $wko_isp_asset_no;
				$prev_asset2 = $wko_isp_asset_no;
				
				$job_cd = $wko_isp_job_cd;
				$prev_job = $wko_isp_job_cd;
				
			}
			else{
				$job_cd = "";
				$asset2 = "";					
			}
		}elseif($cnt >= 2){
			if ($prev_job == $wko_isp_job_cd && $prev_asset2 == $wko_isp_asset_no) {
				$job_cd = "";
				$asset2 = "";
				
			}else{
				$job_cd = $wko_isp_job_cd;
				$prev_job = $wko_isp_job_cd;
				
				$asset2 = $wko_isp_asset_no;
				$prev_asset2 = $wko_isp_asset_no;
				
				$cnt = 1;				
				
			}
			
			
		}
		
		if ($cnt2 == 1) {
			if (empty($sec_desc)) {
				$sec_desc = $wko_isp_sec_desc;
				$prev_sec_desc = $wko_isp_sec_desc;
				
				$asset3 = $wko_isp_asset_no;
				$prev_asset3 = $wko_isp_asset_no;
				
				$prev_sec_no = $wko_isp_sec_no;
				
			} else {
				$sec_desc = "";	
			}
		} elseif ($cnt2 >= 2) {
			
		
			if ($prev_sec_desc == $wko_isp_sec_desc && $prev_asset3 == $wko_isp_asset_no) {
				
				if ($prev_job.$prev_sec_desc.$prev_sec_no.$prev_asset  == $wko_isp_job_cd.$wko_isp_sec_desc.$wko_isp_sec_no.$prev_asset) {
					$sec_desc = "";
				} else {
					$sec_desc = $wko_isp_sec_desc;
					$prev_sec_desc = $wko_isp_sec_desc;
					$prev_sec_no = $wko_isp_sec_no;
					$prev_asset = $wko_isp_asset_no;
					$cnt2 = 1;
				}
			
			} else {
				$sec_desc = $wko_isp_sec_desc;
				$prev_sec_desc = $wko_isp_sec_desc;
				
				$asset3 = $wko_isp_asset_no;
				$prev_asset3 = $wko_isp_asset_no;
				
				$prev_sec_no = $wko_isp_sec_no;
				
				$cnt2 = 1;
			}
		}
		
		

		//Section
		// if ($cnt2 == 1) {
			// if (empty($sec_desc)){
				// $sec_desc = $wko_isp_sec_desc;
				// $prev_sec_desc = $wko_isp_sec_desc;
				 // $prev_sec_no = $wko_isp_sec_no;
			// }
			// else{
				// $sec_desc = "";	
			// }
		// }elseif($cnt2 >= 2){
			// if ($prev_job.$prev_sec_desc == $wko_isp_job_cd.$wko_isp_sec_desc) {
				// $sec_desc = "";
			// }else{
				// $sec_desc = $wko_isp_sec_desc;
				// $prev_sec_desc = $wko_isp_sec_desc;
				// $cnt2 = 1;
			// }
		// }
		
		// Section
		// if ($cnt2 == 1) {
			// if (empty($sec_desc)) {
				// $sec_desc = $wko_isp_sec_desc;
				// $prev_sec_desc = $wko_isp_sec_desc;
				
				// $prev_sec_no = $wko_isp_sec_no;
				// $prev_asset = $wko_isp_asset_no;
				
			// } else {
				// $sec_desc = "";	
			// }
		// } elseif ($cnt2 >= 2) {
			
			
			
			// if ($prev_job.$prev_sec_desc.$prev_sec_no.$prev_asset  == $wko_isp_job_cd.$wko_isp_sec_desc.$wko_isp_sec_no.$prev_asset) {
				// $sec_desc = "";
			// } else {
				// $sec_desc = $wko_isp_sec_desc;
				// $prev_sec_desc = $wko_isp_sec_desc;
				// $prev_sec_no = $wko_isp_sec_no;
				// $prev_asset = $wko_isp_asset_no;
				// $cnt2 = 1;
			// }
		// }

		
		

If ($cnt_all == 1 ){
$tbl = <<<EOD
<table border="1" cellpadding="5" cellspacing="0" width="100%">
<tr>
    <th width="15%" style="background-color:#539CEB;color:#FAFAFA; text-align:center; font-weight:bold;">Asset</th>
    <th width="15%" style="background-color:#539CEB;color:#FAFAFA; text-align:center; font-weight:bold;">Job Code</th>
    <th width="20%" style="background-color:#539CEB;color:#FAFAFA; text-align:center; font-weight:bold;">Section</th>
    <th width="20%" style="background-color:#539CEB;color:#FAFAFA; text-align:center; font-weight:bold;">Step</th>
    <th width="15%" style="background-color:#539CEB;color:#FAFAFA; text-align:center; font-weight:bold;">Condition</th>
    <th width="15%" style="background-color:#539CEB;color:#FAFAFA; text-align:center; font-weight:bold;">Remark</th>
</tr>
EOD;
}

$tbl .= <<<EOD
	<tr>
EOD;

If ($cnt3 == 1 ){
$tbl .= <<<EOD
	<td rowspan= "$total_asset">$asset</td>
EOD;
}


If ($cnt == 1 ){
$tbl .= <<<EOD
	<td rowspan= "$total_job">$job_cd</td>
EOD;
}

If ($cnt2 == 1 ){
$tbl .= <<<EOD
	<td rowspan= "$total_sec">$sec_desc</td>
EOD;
}

$tbl .= <<<EOD
	<td >$wko_isp_sec_no . $wko_isp_stp_no $wko_isp_stp_desc</td>
	<td style="text-align: center" >$type</td>
	<td >$wko_isp_varchar2</td>
	</tr>	
EOD;
		
    }
} while ( sqlsrv_next_result($stmt) );
	

if($valid){	
	
 $tbl .= <<<EOD
</table>
EOD;
$pdf->writeHTML($tbl, true, false, false, false, '');	 
}


//returnData($pdf,$site_cd,$mst_rowid);	

	
}





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





function returnData($pdf,$site_cd,$mst_rowid){
	
	$returnData = array(
		'status' => 'SUCCESS',
		'message' => 'Successfully',
		'PDF' => $pdf->Output('example_048.pdf', 'I'),
		'PDF_link' => 'Report/checklist?site_cd='.$site_cd.'&mst_rowid='.$mst_rowid.'');

	echo json_encode($returnData);
	exit();
}

function returnError($error_message){
	
	
	$returnData = array(
	'status' => 'ERROR',
	'message' => $error_message);
	
	echo json_encode($returnData);
	exit();
		
}

//============================================================+
// END OF FILE
//============================================================+
?>