<?php
/*
 * API: ChatBot ©
 * Features: sends and retrieves messages from / to Watson Assistant via cURL
 * References: https://www.ibm.com/watson/developercloud/assistant/api/v1/
 * Author: Luca Crippa - luca.crippa88@gmail.com
 * Date: April 2018
 */

  if(isset($_POST['message'])){

    $workspace_id = '676f9cf6-549c-46ae-99c7-d3272eb7f8bf';
    // Release date of the API version in YYYY-MM-DD format.
    $release_date = '2018-07-10';
    // Username of a user for the service credentials.
    //$username = '07ba4310-90b5-4d37-af22-3ddd4e9ae7b5';
    // Password of a user for the service credentials.
    //$password = 'HplaSVdX71Ke';
    $apiKey = '4xmDMZBrbFZgqq8KoapmuJ2on4mSSD8TnBVoM3FlZtH8';

    // (*) Release date allows you to use an older version of the Watson Assistant API, to have compatibility cross releases

    // Make a request message for Watson API in json
    $data['input']['text'] = $_POST['message'];
    if(isset($_POST['context']) && $_POST['context']){
      $data['context'] = json_decode($_POST['context'], JSON_UNESCAPED_UNICODE); // Encode multibyte Unicode characters literally (default is to escape as \uXXXX)
    }
    $data['alternate_intents'] = false;

    // Encode json data
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);

    // Post the json to Watson Assistant API via cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/93f6f940-2dbb-4733-8f73-89300b729919/v1/workspaces/676f9cf6-549c-46ae-99c7-d3272eb7f8bf/message?version=2019-08-01'); // Instructions here: https://www.ibm.com/watson/developercloud/assistant/api/v1/curl.html?curl#message
    $username = 'apiKey';
    $password = $apiKey;
    curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password); // Set cURL Watson Assistant credentials
    curl_setopt($ch, CURLOPT_POST, true );
    /*$headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: Basic';
    $headers[] = 'x-api-key: ' . $apiKey;*/

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set cURL headers
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

    // Prepare response, close cURL and send response to front-end
    $result = trim(curl_exec($ch)); // Prepare
    curl_close($ch); // Close
    echo json_encode($result, JSON_UNESCAPED_UNICODE); // Send
  }

?>
