<?php
// Set content type to JSON
header('Content-Type: application/json');

// Include the Composer autoloader
require_once __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;

function detect_intent_texts($projectId, $text, $sessionId, $languageCode = 'en-US')
{
    // Set the path to your service account key file
    $credentialsPath = __DIR__ . '/gcp_creds/dialogflow_key.json';

    // Check if the credentials file exists
    if (!file_exists($credentialsPath)) {
        return "Error: Service account key file not found.";
    }

    try {
        // Create a new sessions client
        $sessionsClient = new SessionsClient([
            'credentials' => $credentialsPath
        ]);

        // Format the session name
        $session = $sessionsClient->sessionName($projectId, $sessionId);

        // Create a new text input
        $textInput = new TextInput();
        $textInput->setText($text);
        $textInput->setLanguageCode($languageCode);

        // Create a new query input
        $queryInput = new QueryInput();
        $queryInput->setText($textInput);

        // Detect the intent
        $response = $sessionsClient->detectIntent($session, $queryInput);
        $queryResult = $response->getQueryResult();
        $fulfillmentText = $queryResult->getFulfillmentText();

        // Close the sessions client
        $sessionsClient->close();

        return $fulfillmentText;

    } catch (Exception $e) {
        // Return a generic error message
        error_log($e->getMessage());
        return "Error processing your request.";
    }
}

// Get the user's message from the POST request
$data = json_decode(file_get_contents('php://input'), true);
$userMessage = $data['message'] ?? '';
$sessionId = $data['sessionId'] ?? session_id(); // Use PHP session ID as Dialogflow session ID

// Your Google Cloud Project ID
$projectId = 'chrivia-asxi';

// Get the bot's reply from Dialogflow
if (!empty($userMessage)) {
    $botReply = detect_intent_texts($projectId, $userMessage, $sessionId);
} else {
    $botReply = 'Please say something.';
}

// Return the bot's reply as JSON
echo json_encode(['reply' => $botReply]);