<?php
include 'db.php';

$phone = $_POST['phone'];
$lastId = isset($_POST['last_id']) ? (int)$_POST['last_id'] : 0;

$sql = "SELECT * FROM SMS 
        WHERE (Sender = '$phone' OR Receiver = '$phone')";

if ($lastId > 0) {
    $sql .= " AND id > $lastId";
}

$sql .= " ORDER BY id ASC";

$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    $msg = htmlspecialchars($row['Body']);
    $time = htmlspecialchars($row['created_at']);
        // Reformat to MM-DD-YYYY
    $date = DateTime::createFromFormat('d-m-Y h:i:sa', $time);
    $formatted_time = $date->format('m-d-Y h:i:sa');
    $id = $row['id'];

    if ($row['Type'] == 'Received') {
        echo "<div class='message received' data-id='$id' style='background-color:white;'>
                <div class='bubble'>$msg</div>
                <div class='timestamp'>$formatted_time</div>
                <button class='delete-btn' onclick='deleteMessage($id)'>🗑</button>
              </div>";
    } else {
        echo "<div class='message sent' data-id='$id'>
                <div class='bubble'>$msg</div>
                <div class='timestamp'>$formatted_time</div>
                <button class='delete-btn' onclick='deleteMessage($id)'>🗑</button>
              </div>";
    }
}
?>
