<?php 
include "../includes/db.php";
include "../includes/auth.php";

$id = (int)($_GET['id'] ?? 0);
$message = null;
if ($id > 0) {
    $message = $conn->query("SELECT * FROM messages WHERE id=$id")->fetch_assoc();
}

if (!$message) {
    header("Location: messages.php");
    exit;
}

// Mark as read (only if column exists)
$hasIsRead = false;
$colCheck = $conn->query("SHOW COLUMNS FROM messages LIKE 'is_read'");
if ($colCheck && $colCheck->num_rows > 0) {
    $hasIsRead = true;
}
if ($hasIsRead && empty($message['is_read'])) {
    $conn->query("UPDATE messages SET is_read=1 WHERE id=$id");
    $message['is_read'] = 1;
}

include "../includes/header.php"; 
include "../includes/sidebar.php"; 
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="page-title">View Message</h2>
    <a href="messages.php" class="btn btn-secondary">Back to Messages</a>
</div>

<div class="bg-white p-4 rounded">
    <div class="mb-4">
        <h4><?= htmlspecialchars($message['subject']) ?></h4>
    </div>

    <div class="row mb-3">
        <div class="col-md-6">
            <p><strong>From:</strong> <?= htmlspecialchars($message['name']) ?></p>
            <p><strong>Email:</strong> <a href="mailto:<?= htmlspecialchars($message['email']) ?>"><?= htmlspecialchars($message['email']) ?></a></p>
            <?php if (!empty($message['phone'])): ?>
                <p><strong>Phone:</strong> <?= htmlspecialchars($message['phone']) ?></p>
            <?php endif; ?>
        </div>
        <div class="col-md-6">
            <p><strong>Date:</strong> <?= date('M d, Y H:i', strtotime($message['created_at'])) ?></p>
            <p><strong>Status:</strong> <span class="badge bg-success">Read</span></p>
        </div>
    </div>

    <hr>

    <div class="mb-4">
        <h5>Message Content:</h5>
        <div class="bg-light p-3 rounded" style="min-height: 200px;">
            <?= nl2br(htmlspecialchars($message['message'])) ?>
        </div>
    </div>

    <div>
        <button onclick="deleteMessage(<?= $id ?>)" class="btn btn-danger">Delete Message</button>
        <a href="messages.php" class="btn btn-secondary">Back</a>
    </div>
</div>

<script>
function deleteMessage(id) {
    if (confirm('Are you sure you want to delete this message?')) {
        fetch('messages_delete.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + id
        }).then(() => window.location.href = 'messages.php');
    }
}
</script>

<?php include "../includes/footer.php"; ?>
