<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'db.php'; // Include your database connection

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $element1 = $_POST['element1'] ?? null;
    $element2 = $_POST['element2'] ?? null;

    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(["status" => "error", "message" => "User not logged in"]);
        exit();
    }

    $userId = $_SESSION['user_id']; // Get the logged-in user ID

    if ($element1 && $element2) {
        // Use OpenAI API to combine elements
        $apiKey = "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"; // Replace with your actual OpenAI API key
        $prompt = "Tu esi spēles amatniecības (crafting) sistēma. Tavs uzdevums ir apvienot divus elementus, ko nodrošina spēlētājs, un radīt jaunu, loģisku rezultātu. Ņem vērā šādus noteikumus:
            1. Katrai kombinācijai ir jāseko loģiskai, dabiskai vai radošai secībai.
            2. Izmanto emocijzīmes (emojis), lai attēlotu iegūto elementu, ja tas ir piemēroti, un neizmanto vairāk kā 2 emocijzīmes.
            3. Atbildē sniedz tikai emocijzīmi un rezultātu, bez pieturzīmēm.

            Piemēri:
            - Apvienot uguni un ūdeni: 🌫️ tvaiks.
            - Apvienot zemi un uguni: 🌋 lava.
            - Apvienot gaisu un zemi: 🌪️ tornādo.
            Tagad apvieno šādus elementus: \"$element1\" un \"$element2\"";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",
            "Authorization: Bearer $apiKey"
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            "model" => "gpt-4",
            "messages" => [
                ["role" => "system", "content" => "You are a creative assistant."],
                ["role" => "user", "content" => $prompt]
            ],
            "max_tokens" => 50,
            "temperature" => 0.7
        ]));

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            echo json_encode(["status" => "error", "message" => curl_error($ch)]);
            curl_close($ch);
            exit;
        }

        curl_close($ch);
        $response = json_decode($response, true);

        if (isset($response['choices'][0]['message']['content'])) {
            $newElement = trim($response['choices'][0]['message']['content']);

            // Check if the new element already exists for this user
            $stmt = $conn->prepare("SELECT COUNT(*) FROM elements WHERE name = ? AND users_id = ?");
            $stmt->bind_param("si", $newElement, $userId);
            $stmt->execute();
            $stmt->bind_result($count);
            $stmt->fetch();
            $stmt->close();

            if ($count > 0) {
                // Element already exists for this user
                echo json_encode(["status" => "exists", "newElement" => $newElement]);
            } else {
                // Insert the new element into the `elements` table with user ID
                $stmt = $conn->prepare("INSERT INTO elements (name, users_id) VALUES (?, ?)");
                $stmt->bind_param("si", $newElement, $userId);

                if ($stmt->execute()) {
                    echo json_encode(["status" => "success", "newElement" => $newElement]);
                } else {
                    echo json_encode(["status" => "error", "message" => $stmt->error]);
                }

                $stmt->close();
            }
        } else {
            echo json_encode(["status" => "error", "message" => "OpenAI API failed."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid input"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Invalid request method"]);
}

$conn->close();
?>
