<?php
session_start();

$db = new mysqli('localhost', 'papino', 'tt1201', 'chatgpt');
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

if (!isset($_SESSION['user_id']) && !isset($_COOKIE['user_auth'])) {
    header('Location: login.php');
    exit;
} else if (!isset($_SESSION['user_id']) && isset($_COOKIE['user_auth'])) {
    $user_id = unserialize(base64_decode($_COOKIE['user_auth']));
    // Validate user_id and set session
    $query = "SELECT * FROM users WHERE id = '$user_id'";
    $result = $db->query($query);
    if ($result && $result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $_SESSION['user_id'] = $user['id'];
    } else {
        header('Location: login.php');
        exit;
    }
}

if (!isset($_SESSION['conversations'])) {
    $_SESSION['conversations'] = [];
}

if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];

function chatGPT($prompt, $apiKey, $db, $history = [])
{
    $ch = curl_init('https://api.openai.com/v1/chat/completions');

    $messages = [];
    foreach ($history as $exchange) {
        $messages[] = ['role' => 'user', 'content' => $exchange['ask']];
        $messages[] = ['role' => 'assistant', 'content' => $exchange['ans']];
    }
    $messages[] = ['role' => 'user', 'content' => $prompt];

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['model' => 'gpt-4-turbo', 'messages' => $messages]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $apiKey]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);

    return json_decode($result, true);
}

function detectAndWrapCode($response) {
    $response = htmlspecialchars($response);
    $response = preg_replace('/(```)(\s*?[\w]*\n)([\s\S]*?)(```)/', '<pre><code>$3</code></pre>', $response);

    // Split response to selectively apply nl2br
    $parts = preg_split('/(<pre><code>.*?<\/code><\/pre>)/', $response, -1, PREG_SPLIT_DELIM_CAPTURE);
    $new_response = '';
    foreach ($parts as $part) {
        if (strpos($part, '<pre><code>') === false) {
            $new_response .= nl2br($part);
        } else {
            $new_response .= $part;
        }
    }
    return $new_response;
}

$apiKey = 'sk-xxxxx';
$responseMessage = '';
$promptToShow = '';

// Pagination setup
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 5; // Set how many conversations you want per page

$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
$total = $db->query("SELECT COUNT(id) AS total FROM ai WHERE user_id = " . $_SESSION['user_id'])->fetch_assoc()['total'];
$pages = ceil($total / $perPage);

$query = "SELECT * FROM ai WHERE user_id = " . $_SESSION['user_id'] . " ORDER BY created_at DESC LIMIT $start, $perPage";
$result = $db->query($query);

$conversations = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $conversations[] = $row;
    }
    $result->free();
}


if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['token']) && $_POST['token'] == $_SESSION['token']) {
    if (!empty($_POST['prompt'])) {
        $prompt = trim($_POST['prompt']);
        $response = chatGPT($prompt, $apiKey, $db, $_SESSION['conversations']);
        if (isset($response['choices'][0]['message']['content'])) {
            $ans = $response['choices'][0]['message']['content'];
            $_SESSION['conversations'][] = ['ask' => $prompt, 'ans' => $ans];
            $ans = $db->real_escape_string($ans);
            $ask = $db->real_escape_string($prompt);
            $user_id = $_SESSION['user_id'];  // Get user id from session
            $query = "INSERT INTO ai (ask, ans, user_id) VALUES ('$ask', '$ans', $user_id)";
            if (!$db->query($query)) {
                echo "Database insert error: " . $db->error;
            }
            $responseMessage = detectAndWrapCode($ans);
            $promptToShow = '';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat with GPT</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <form action="" method="post" id="promptForm">
        <label for="prompt">Enter your prompt:</label><br>
        <textarea id="prompt" name="prompt" rows="6" cols="50"><?php echo htmlspecialchars($promptToShow); ?></textarea><br>
        <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
        <input type="submit" value="Submit">
    </form>
    <div id="conversations">
        <?php if (!empty($_SESSION['conversations'])): ?>
            <div>
                <h2>Latest Conversation:</h2>
                <?php
                // Access the last conversation directly
                $lastConversation = end($_SESSION['conversations']);
                ?>
                <p><strong>You:</strong> <?php echo nl2br(htmlspecialchars($lastConversation['ask'])); ?></p>
                <!-- Processing each response before output -->
                <div><strong>Gpt:</strong> <?php echo detectAndWrapCode($lastConversation['ans']); ?></div>
            </div>
        <?php endif; ?>

        <h2>Past Conversations:</h2>
        <?php foreach ($conversations as $conversation): ?>
            <div class="conversation">
                <p class="ask" onclick="toggleAnswer(this)" data-full-text="<?php echo htmlspecialchars($conversation['ask']); ?>" data-truncated-text="<?php echo htmlspecialchars(strlen($conversation['ask']) > 50 ? substr($conversation['ask'], 0, 47) . '...' : $conversation['ask']); ?>"> 
                    <span class="delete" onclick="deleteConversation(<?php echo $conversation['id']; ?>)">&#10006;</span>               
                    <?php echo nl2br(htmlspecialchars(strlen($conversation['ask']) > 50 ? substr($conversation['ask'], 0, 47) . '...' : $conversation['ask'])); ?>
                    <?php if (strlen($conversation['ask']) > 50): ?>
                        <span class="read-more" onclick="event.stopPropagation(); toggleReadMore(this)">read more</span>
                    <?php endif; ?>                    
                </p>
                <div class="ans"><?php echo detectAndWrapCode($conversation['ans']); ?></div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <div class="pagination">
        <?php for ($i = 1; $i <= $pages; $i++): ?>
            <a href="?page=<?php echo $i; ?>" class="<?php echo ($page === $i) ? 'active' : ''; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
    </div>

    <script src="script.js" defer></script>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            applyHighlighting();
        });

        function toggleAnswer(element) {
            var ans = element.nextElementSibling;
            if (ans.style.display === "none") {
                ans.style.display = "block";
            } else {
                ans.style.display = "none";
            }
        }

        function toggleReadMore(element) {
            const askElement = element.parentNode;
            const isTruncated = askElement.getAttribute('data-is-truncated') !== 'false';
            askElement.innerHTML = isTruncated ? askElement.getAttribute('data-full-text') : askElement.getAttribute('data-truncated-text');
            if (isTruncated) {
                askElement.innerHTML += ' <span class="read-more" onclick="event.stopPropagation(); toggleReadMore(this)">read less</span>';
            } else {
                askElement.innerHTML += ' <span class="read-more" onclick="event.stopPropagation(); toggleReadMore(this)">read more</span>';
            }
            askElement.setAttribute('data-is-truncated', !isTruncated);
        }

        function applyHighlighting() {
            document.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
            });
        }

        function deleteConversation(id) {
            if (confirm('Are you sure you want to delete this conversation?')) {
                fetch('delete_conversation.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ id: id })
                }).then(response => response.json())
                  .then(data => {
                      if (data.success) {
                          alert('Conversation deleted!');
                          location.reload(); // Reload the page to update the conversation list
                      } else {
                          alert('Failed to delete conversation.');
                      }
                  });
            }
        }
    </script>
</body>
</html>