<?php

// Function to get ratings from GPT-3.5
function getRatings($foodItem) {
    // Set your OpenAI API key
    $api_key = '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';

    // Set the GPT-3.5 API endpoint
    $api_url = 'https://api.openai.com/v1/engines/gpt-3.5-turbo-instruct/completions';

    // Create two separate prompts
    $prompt1 = "Give a 1-5 rating (1=very unhealthy, 2=unhealthy, 3=average, 4=healthy, 5=very healthy) for '{$foodItem}' for:\n
        - Healthiness: [Your rating from 1 to 5]\n";

    $prompt2 = "Give a 1-5 (1=very low amount, 2=low, 3=medium, 4=high, 5=very high) for '{$foodItem}' for the available amount per serving in the following things:\n
        - Amount of Protein: [Your rating from 1 to 5]\n
        - Amount of Carbs: [Your rating from 1 to 5]\n
        - Amount of Fat: [Your rating from 1 to 5]\n
        - Amount of Sugar: [Your rating from 1 to 5]\n";

    // Create the request data for prompt 1
    $data1 = [
        'prompt' => $prompt1,
        'max_tokens' => 1000,
        'temperature' => 0,
    ];

    // Create the request data for prompt 2
    $data2 = [
        'prompt' => $prompt2,
        'max_tokens' => 1000,
        'temperature' => 0,
    ];

    $headers = [
        'Authorization: Bearer ' . $api_key,
        'Content-Type: application/json',
    ];

    // Send the request for prompt 1 and get the response
    $response1 = file_get_contents($api_url, false, stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => implode("\r\n", $headers),
            'content' => json_encode($data1),
        ],
    ]));

    // Send the request for prompt 2 and get the response
    $response2 = file_get_contents($api_url, false, stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => implode("\r\n", $headers),
            'content' => json_encode($data2),
        ],
    ]));

    // Check for errors
    if ($response1 === false || $response2 === false) {
        echo 'Error occurred while fetching the ratings.';
        return null;
    }

    // Print the entire API responses for debugging
    echo "API Response for Prompt 1: <pre>" . htmlspecialchars($response1) . "</pre>";
    echo "API Response for Prompt 2: <pre>" . htmlspecialchars($response2) . "</pre>";

    // Decode the JSON responses
    $responseData1 = json_decode($response1, true);
    $responseData2 = json_decode($response2, true);

    // Extract the ratings from the responses if available
    $ratings1 = isset($responseData1['choices'][0]['text']) ? $responseData1['choices'][0]['text'] : null;
    $ratings2 = isset($responseData2['choices'][0]['text']) ? $responseData2['choices'][0]['text'] : null;

    return [$ratings1, $ratings2];
}

// Main script
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['food_item'])) {
    $foodItem = $_POST['food_item'];

    // Call the function to get the ratings for both prompts
    $ratings = getRatings($foodItem);

    if ($ratings !== null) {
        list($ratings1, $ratings2) = $ratings;
        echo "Ratings for $foodItem (Healthiness):";
        echo $ratings1;

        echo "<br>" . "Ratings for $foodItem (Nutritional Values):";
        echo $ratings2;
    } else {
        echo "No ratings available for $foodItem.";
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Food Ratings</title>
</head>
<body>
    <h1>Food Ratings</h1>
    <form method="POST">
        <label for="food_item">Enter a food item: </label>
        <input type="text" name="food_item" id="food_item" required>
        <button type="submit">Get Ratings</button>
    </form>
</body>
</html>