<?php
require_once ('config.php');
require_once('f_logging.php');
$error_message;
$valid = true;
$json_return = array();
$json_return = [];

$ID=$_GET['ID'];
$Folder=$_GET['Folder'];
$dvc_id = $_GET['dvc_id'];
$sync_time = $_GET['sync_time'];
$site_cd = $_GET['site_cd'];
$LoginID = $_GET['LoginID'];


$json = file_get_contents('php://input');
$data = json_decode($json, true);


$uploaddir_2 = $checklist_temp_path."\\temp_".$dvc_id."\\checklist_upload\\";
$uploaddir = "C:\\wamp64\\www\\".$Folder."\\mobile_checklist_temp\\temp_".$dvc_id."\\checklist_upload\\";

if (!is_dir($uploaddir)) {
	mkdir($uploaddir, 0777, true);
}

$date = date('Y-m-d H:i:s');
$sync_time = str_replace(":","",$sync_time);

$path = $uploaddir.$sync_time."_(".$site_cd.")_"."Check_list".".json";


file_put_contents($path,$json);


//$base64FileData = base64_encode($fileData)
$base64FileData = base64_encode($path);
	//$data=unpack("H*hex", $datastring);		
			
	$sql = "INSERT INTO wko_isp_temp_json	(	site_cd, 			audit_user, 		audit_date, 			column1, 		column2, 
												FILE_NAME, 			json_string,		checklist_id) 
						VALUES 				(	?,		 			?, 					getdate(),				?, 				?, 
												?,	 				?,					? ) SELECT SCOPE_IDENTITY() as rowid";
												
												
	$params_update_wko_isp_temp_json = array( $site_cd,$LoginID,'Native','JSON','Checklist_update',$json,$ID);

	$stmt = sqlsrv_query( $conn, $sql, $params_update_wko_isp_temp_json);				
					
	if( !$stmt ) {
		$error_message = "Error insert table (wko_isp_temp_json)";
		returnError($error_message);
		die( print_r( sqlsrv_errors(), true));
	}

	$json_wko_ref = array();
	do {
		while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
			
			
		}
	} while ( sqlsrv_next_result($stmt) );	


$path_2 = $uploaddir_2.$sync_time."_(".$site_cd.")_"."Check_list".".json";

$procedureName = "sp_mobile_checklist_update";
$sql = "exec $procedureName '".$ID."'";

$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
    //die(print_r(sqlsrv_errors(), true));
	//$error_message = "Error updating table (wko_isp)";
	$error_message = $sql;
	returnError($error_message);
	die(print_r(sqlsrv_errors() , true));
	
}else{
	//$error_message = $sql;
	
	returnData();
	
}


function returnData()
{
    $returnData = array(
        'status' => 'SUCCESS',
        'message' => 'Checklist update successfully'
    );

    echo json_encode($returnData);
}

function returnError($error_message)
{
    $json = array();

    $returnData = array(
        'status' => 'ERROR',
        'message' => $error_message
    );

    echo json_encode($returnData);

    

    exit();
}


?>
