<?php

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if required library is available
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
    die('Library not found. Ensure you have the correct path to autoload.php.');
}
require_once(__DIR__ . '/vendor/autoload.php'); 

if (!isset($openaiClient)) {
    $openaiClient = \Tectalic\OpenAi\Manager::build(new \GuzzleHttp\Client(), new \Tectalic\OpenAi\Authentication('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'));
}

$servername = "localhost";
$username = "antenicenefather_anf";
$password = "363213119.363213119";
$dbname = "antenicenefather_anf";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Database connected successfully!<br>";

$sql = "SELECT id, content_8, gpt_response_4 FROM longform WHERE (gpt_response_7 IS NULL OR gpt_response_7='') AND is_send = 1 LIMIT 1";
$result = $conn->query($sql);
if (!$result) {
    die("SQL query failed: " . $conn->error);
}

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo "Processing entry with ID " . $row["id"] . "<br>";

    $dataToSend = $row["content_8"] . "\n" . $row["gpt_response_4"];
    $response = sendToAPI($dataToSend, $openaiClient);
    echo "Received response from API: " . $response . "<br>";

    $update_sql = "UPDATE longform SET gpt_response_7 = ? WHERE id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("si", $response, $row["id"]);

    if ($stmt->execute()) {
        echo "Updated entry with ID " . $row["id"] . " with response: " . $response . "<br>";
    } else {
        echo "Failed to update entry with ID " . $row["id"] . ". Error: " . $stmt->error . "<br>";
    }
    $stmt->close();
    $conn->close();

    $maxAttempts = 25;
    $attempt = 0;

    $conn = new mysqli($servername, $username, $password, $dbname);

    while($attempt < $maxAttempts) {
        $check_sql = "SELECT gpt_response_7 FROM longform WHERE id = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param("i", $row["id"]);
        $stmt->execute();
        $check_result = $stmt->get_result();
        $data = $check_result->fetch_assoc();

        if(!empty($data['gpt_response_7'])) {
            echo "gpt_response_7 field is now populated!<br>";
            include("9.php");
            break;
        } else {
            echo "Waiting for gpt_response_7 field to be populated...<br>";
            sleep(5);
        }
        $attempt++;
    }

    if ($attempt == $maxAttempts) {
        echo "Max attempts reached. gpt_response_7 is still not populated.<br>";
    }
    $stmt->close();

} else {
    echo "No new content found that is allowed to be sent!";
    $conn->close();
}

if (!function_exists('sendToAPI')) {
    function sendToAPI($dataToSend, $openaiClient) {
        try {
            $apiResponse = $openaiClient->chatCompletions()->create(
                new \Tectalic\OpenAi\Models\ChatCompletions\CreateRequest([
                    'model' => 'gpt-4',
                    'messages' => [
                        [
                            'role' => 'user',
                            'content' => $dataToSend
                        ],
                    ],
                ])
            )->toModel();

            return $apiResponse->choices[0]->message->content;
        } catch (Exception $e) {
            echo "Error communicating with OpenAI API: " . $e->getMessage() . "<br>";
            echo "Data sent to API: " . $dataToSend . "<br>";
            echo "Full Exception: <pre>" . print_r($e, true) . "</pre><br>";
            return ''; 
        }
    }
}

?>
