<?php

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

// Include necessary libraries
require_once(__DIR__ . '/vendor/autoload.php');

// Database connection parameters
$servername = "localhost";
$username = "antenicenefather_anf";
$password = "363213119.363213119";
$dbname = "antenicenefather_anf";

// OpenAI Client initialization (replace 'your-api-key' with your actual key)
$openaiClient = \Tectalic\OpenAi\Manager::build(new \GuzzleHttp\Client(), new \Tectalic\OpenAi\Authentication('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'));

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

// Function to send data to OpenAI API
function sendToAPI($dataToSend, $openaiClient) {
    // Implementation of API call...
    // return response;
}

// Processing logic from 1.php
$sql1 = "SELECT id, content_1, content_2 FROM longform WHERE (gpt_response_1 IS NULL OR gpt_response_1='') AND is_send = 1 LIMIT 1";
$result1 = $conn->query($sql1);
if ($result1 && $result1->num_rows > 0) {
    while ($row1 = $result1->fetch_assoc()) {
        // Combine and process the data
        $dataToSend = $row1["content_1"] . " " . $row1["content_2"];
        $response = sendToAPI($dataToSend, $openaiClient);

        // Update the database with the response
        $update_sql = "UPDATE longform SET gpt_response_1 = ? WHERE id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("si", $response, $row1["id"]);
        $stmt->execute();
        $stmt->close();
    }
}

// Processing logic from 2.php
$sql2 = "SELECT id, content_3, gpt_response_1, content_4, content_5, content_6 FROM longform WHERE (gpt_response_2 IS NULL OR gpt_response_2='') AND is_send = 1 LIMIT 1";
$result2 = $conn->query($sql2);
if ($result2 && $result2->num_rows > 0) {
    while ($row2 = $result2->fetch_assoc()) {
        // Combine and process the data
        $dataToSend = $row2["content_3"] . " " . $row2["gpt_response_1"] . " " . $row2["content_4"] . " " . $row2["content_5"] . " " . $row2["content_6"];
        $response = sendToAPI($dataToSend, $openaiClient);

        // Update the database with the response
        $update_sql = "UPDATE longform SET gpt_response_2 = ? WHERE id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("si", $response, $row2["id"]);
        $stmt->execute();
        $stmt->close();
    }
}

$conn->close();
?>
