<?php
include 'connect.php';
$business = json_decode(file_get_contents('php://input'));

$site_api_url = $API_URL.$business->query->version.'/'.$business->query->lang.'/'.$business->query->project.'/';

$url = $site_api_url.'business/'.$business->data->id.'/metafields';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Accept: application/json',
   'x-api-key: '.$user_key
));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$busresult = curl_exec($ch);
$busdata = json_decode($busresult);

$metafileds_id = '';
if(sizeof($busdata->result) > 0){
	foreach($busdata->result as $mval){
		if($mval->key == 'gtoceriestypes'){
			$metafileds_id = $mval->id;
			break;
		}
	}
}

if(isset($business->params->gtoceriestypes)){


	if($metafileds_id != ''){
		$gtoceriestypes = json_decode($business->params->gtoceriestypes);
		$business->data->gtoceriestypes = $gtoceriestypes;
		$postfields = array(
			"value" => json_encode($gtoceriestypes),
			"value_type" => 'json',
			"key" => 'gtoceriestypes'
		);
		$data_json = json_encode($postfields);

		//file_put_contents('data.txt', "data_json-".json_encode($data_json). "\n", FILE_APPEND);

		$chp = curl_init();
		curl_setopt($chp, CURLOPT_URL, $site_api_url.'business/'.$business->data->id.'/metafields/'.$metafileds_id);
		curl_setopt($chp, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($chp, CURLOPT_POSTFIELDS, $data_json);
		curl_setopt($chp, CURLOPT_CUSTOMREQUEST, 'PUT');
		$headers = array();
		$headers[] = 'Content-Type: application/json';
		$headers[] = 'X-Api-Key: '.$user_key;
		curl_setopt($chp, CURLOPT_HTTPHEADER, $headers);
		$resultd = curl_exec($chp);
		$resultd = json_decode($resultd);
		curl_close($chp);
		//file_put_contents('data.txt', "resultd-".json_encode($resultd). "\n", FILE_APPEND);
	}else{

		$gtoceriestypes = json_decode($business->params->gtoceriestypes);
		$business->data->gtoceriestypes = $gtoceriestypes;
		$postfields = array(
			"value" => json_encode($gtoceriestypes),
			"value_type" => 'json',
			"key" => 'gtoceriestypes'
		);
		$data_json = json_encode($postfields);
		$chd = curl_init();
		curl_setopt($chd, CURLOPT_URL, $site_api_url.'business/'.$business->data->id.'/metafields');
		curl_setopt($chd, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($chd, CURLOPT_POSTFIELDS, $data_json);
		curl_setopt($chd, CURLOPT_POST, 1);
		$headers = array();
		$headers[] = 'Content-Type: application/json';
		$headers[] = 'X-Api-Key: '.$user_key;
		curl_setopt($chd, CURLOPT_HTTPHEADER, $headers);
		$resultd = curl_exec($chd);
		$resultd = json_decode($resultd);
		curl_close($chd);

		//file_put_contents('data.txt', "resultd-".json_encode($resultd). "\n", FILE_APPEND);

	}


}

echo json_encode($business->data);
?>
