<?php
header('Access-Control-Allow-Origin: *');
try {
	$date = $_GET['date'];
	if(!isset($date)) {
		$date = date('Ymd');
	}
	$customerCode =$_GET['customerCode'];
	if(!isset($customerCode)){
		throw new Exception("Customer Code required");
	}
	//$mysqli = new mysqli("localhost","root","mysql","posapp");
	$mysqli = new mysqli("localhost","prism","prism123","posapp");
	$query = "SELECT * FROM customer_details WHERE CSTCOD = '$customerCode'";
	$query2 = "SELECT c.NAME,c.ADDRESS1,c.ADDRESS2 FROM customer_details c WHERE CSTCOD = '$customerCode'";

	error_log($query);
	$result = $mysqli->query($query);
	$data = mysqli_fetch_assoc ($result);
	$result2 = $mysqli->query($query2);
	$customerAddress= mysqli_fetch_assoc ($result2);
	
	if (mysqli_num_rows($result) == 0) {
		throw new Exception("Customer Code doesn't match");
	}
	$clientIpAddress = $data['STATIC_IP'];
	$port = $data['PORT'];
    $url = "http://".$clientIpAddress.":".$port."/PRISMLIVEAPI.aspx?fordate=".$date;
    error_log('URL==='.$url);
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($curl);
    error_log($result);
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    error_log('http status code =====' . $httpcode);
    curl_close($curl);
	$response = array();
	if($httpcode != 200) {
		if($httpcode == 0) {
		 throw new Exception("Client server down");
		} else {
		 throw new Exception("curl request error");
		}
	} else {
		$result = preg_replace('/[[:cntrl:]]/', '', $result);
		$data = json_decode($result, true);
		error_log("json decode data");
		switch (json_last_error()) {
	        case JSON_ERROR_NONE:
	            error_log(' - No errors');
	        break;
	        case JSON_ERROR_DEPTH:
	            throw new Exception("- Maximum stack depth exceeded");
	        break;
	        case JSON_ERROR_STATE_MISMATCH:
	            throw new Exception("- Underflow or the modes mismatch");
	        break;
	        case JSON_ERROR_CTRL_CHAR:
	            throw new Exception("- Unexpected control character found");
	        break;
	        case JSON_ERROR_SYNTAX:
	            throw new Exception("- Syntax error, malformed JSON");
	        break;
	        case JSON_ERROR_UTF8:
	            throw new Exception("- Malformed UTF-8 characters, possibly incorrectly encoded");
	        break;
	        default:
	            throw new Exception("- Unknown error");
	        break;
    	}
		$response['message'] = 'success';
		$response['data'] = $data;
		$response['customer_address'] = $customerAddress;
		$response['success'] = 1;
	}
	echo json_encode($response,JSON_UNESCAPED_SLASHES);
} catch(Exception $e){
	$response = array();
	$response['success'] = 0;
	$response['data'] = array();
	$response['message'] = $e->getMessage();
    echo json_encode($response,JSON_UNESCAPED_SLASHES);
}
?>
