<?php 

require 'vendor/autoload.php'; // Adjust the path as needed 

use GuzzleHttp\Client; 
use GuzzleHttp\Psr7\Request; 
use GuzzleHttp\Exception\GuzzleException; 

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

// Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check database connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Receive Row ID from AJAX request
$data = json_decode(file_get_contents('php://input'), true);
$rowId = $conn->real_escape_string($data['rowId']);

// Fetch data from the longform table
$sql = "SELECT gpt_response_1, gpt_response_2, gpt_response_3, gpt_response_5 FROM longform WHERE id = '{$rowId}'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Fetch and concatenate data
    $row = $result->fetch_assoc();
    $content = $row['gpt_response_1'].$row['gpt_response_2'].$row['gpt_response_3'].$row['gpt_response_5'];
    $content = str_replace("'", "", $content); // Remove apostrophes
    $content = strip_tags($content); // Strip HTML tags
} else {
    echo "No data found";
    exit;
}

$conn->close();

// Set up the API client
$client = new Client();
$headers = [
    'X-OAI-API-KEY' => 'jvqrfdwnt70lxea4u1ym28p6b3szkhco', // Replace with your actual API key
    'Accept' => 'application/json',
    'Content-Type' => 'application/json'
];

// Prepare the request body
$body = json_encode([
    "content" => $content, 
    "title" => "optional title", // Optional title for the scan
    "aiModelVersion" => "2.0", // AI model version
    "storeScan" => "false" 
]);

// Create and send the request
$request = new Request('POST', 'https://api.originality.ai/api/v1/scan/ai', $headers, $body); 

try {
    $res = $client->send($request);
    $responseBody = json_decode($res->getBody(), true);

    if (isset($responseBody['success']) && $responseBody['success'] === true) {
        // Extract and display the score
        $score = $responseBody['score'] ?? null; 
        if ($score !== null) {
            echo "AI Score: Originality - " . $score['original'] . ", AI Content - " . $score['ai'] . "\n";
        } else {
            echo "Score not available in the response.\n";
        }
    } else {
        echo "Error or unsuccessful response from Originality.AI.\n";
    }
} catch (GuzzleException $e) {
    echo "Request failed: " . $e->getMessage();
}

// Echo the original content
echo "\n\nOriginal Content Sent:\n" . $content;

?>

