<?php
// get these values from your DB.
require_once('config.php');
$error_message;
$valid = true;


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

//Version
$sql="	Select Perctage = COALESCE(SUM(Perctage),0), X.columns from (
		SELECT	TotalbyStatus = COALESCE(Count(*),0), 
				Total = (Select Count(*) from wko_mst where MONTH(wko_mst.wko_mst_org_date) = Month(Getdate())	AND	YEAR(wko_mst.wko_mst_org_date)  = Year(Getdate())),
				Perctage = CONVERT(DECIMAL(12,2), (Count(*)*1.0000)/(Select Count(*) from wko_mst where wko_mst.site_cd = '".$site_cd ."'   and MONTH(wko_mst.wko_mst_org_date)  = Month(Getdate())	AND	YEAR(wko_mst.wko_mst_org_date)  = Year(Getdate())))*100,
				columns = CASE WHEN wrk_sts_typ_cd = 'FORCE-CLOSE' Then 'CLOSE' ELSE wrk_sts_typ_cd END
				FROM	wko_mst (NOLOCK), wrk_sts (NOLOCK)
				WHERE	wko_mst.site_cd = '".$site_cd ."'  
				AND		wko_mst.site_cd = wrk_sts.site_cd
				AND		wko_mst.wko_mst_status = wrk_sts_status
				AND		MONTH(wko_mst.wko_mst_org_date) = Month(Getdate())
				AND		YEAR(wko_mst.wko_mst_org_date) = Year(Getdate())
				GROUP BY CASE WHEN wrk_sts_typ_cd = 'FORCE-CLOSE' Then 'CLOSE' ELSE wrk_sts_typ_cd END
		) as X
		GROUP BY X.columns
		ORDER BY CASE WHEN columns = 'OPEN' Then 1  WHEN columns = 'COMPLETE' Then 2  WHEN columns = 'CLOSE' Then 3 end ";
		
$stmt = sqlsrv_query( $conn, $sql);

if( !$stmt ) {
     $error_message = "Error selecting current week report (wko_mst)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
	 
}
$json =array();
do {
     while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {	
	 $json[]= $row;
	
     }
} while ( sqlsrv_next_result($stmt) );


if ($valid) {

	
	//echo $sql;
	returnData($json);	
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
	
}

function returnData($json){
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Successfully',
	'data'=>$json);
	
	echo json_encode($returnData);	
}

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

 
?>