<?php
include "db.php";

if (isset($_GET['action']) && $_GET['action'] == "get") {
    $ip = $_GET['ip'];
    $sql = "SELECT * FROM messages WHERE ip_address='$ip' ORDER BY created_at ASC";
    $result = $conn->query($sql);

    while ($row = $result->fetch_assoc()) {
        $class = ($row['sender'] == 'Agent') ? 'sent' : 'received';
        echo "<div class='message $class'>
                <b>{$row['sender']}:</b> {$row['message']}
                <div class='time'>{$row['created_at']}</div>
              </div>";
    }
    exit;
}

if (isset($_POST['sender']) && isset($_POST['message']) && isset($_POST['ip'])) {
    $sender = htmlspecialchars($_POST['sender']);
    $message = htmlspecialchars($_POST['message']);
    $ip = htmlspecialchars($_POST['ip']);
    $conn->query("INSERT INTO messages (sender, message, ip_address) VALUES ('$sender', '$message', '$ip')");
    exit;
}
?>
