<?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_11, gpt_response_4 FROM longform WHERE (gpt_response_5 IS NULL OR gpt_response_5='') 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_11"] . "\n" . $row["gpt_response_4"];

    $response = sendToAPI($dataToSend, $openaiClient);

    echo "Received response from API: " . $response . "<br>";

    $update_sql = "UPDATE longform SET gpt_response_5 = ? 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>";
    }

    // Close the statement and connection
    if ($stmt) {
        $stmt->close();
    }
    if ($conn) {
        $conn->close();
    }
    include("6.php");
} else {
    echo "No new content found that is allowed to be sent!";
    if ($conn) {
        $conn->close();
    }
}

?>
