<?php
require_once 'admin-logic.php';

$conversation_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$conversation_id) { header("Location: manage-messages.php"); exit(); }

// --- Handle Admin Reply Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['body'])) {
    $body = trim($_POST['body']);
    $admin_id = $_SESSION['admin_id'];

    // Insert the admin's reply
    $stmt = $conn->prepare("INSERT INTO messages (conversation_id, sender_id, sender_type, body) VALUES (?, ?, 'admin', ?)");
    $stmt->bind_param("iis", $conversation_id, $admin_id, $body);
    $stmt->execute();
    $stmt->close();
    
    // Update the last reply time for the conversation
    $conn->query("UPDATE conversations SET last_reply_at = NOW(), status = 'open' WHERE id = $conversation_id");
    
    header("Location: view-message.php?id=$conversation_id");
    exit();
}

// Fetch conversation details and the user's name
$stmt = $conn->prepare("SELECT c.id, c.subject, u.full_name FROM conversations c JOIN users u ON c.user_id = u.id WHERE c.id = ?");
$stmt->bind_param("i", $conversation_id);
$stmt->execute();
$conversation = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$conversation) { header("Location: manage-messages.php"); exit(); }
$page_title = 'Conversation: ' . htmlspecialchars($conversation['subject']);

// Fetch all messages for this conversation
$stmt = $conn->prepare("SELECT sender_type, body, created_at FROM messages WHERE conversation_id = ? ORDER BY created_at ASC");
$stmt->bind_param("i", $conversation_id);
$stmt->execute();
$messages = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>
<style>
    .chat-container { max-width: 900px; margin: auto; }
    .chat-box { height: 60vh; overflow-y: auto; padding: 1rem; border-radius: var(--bs-border-radius); }
    .chat-bubble { max-width: 75%; padding: 0.75rem 1rem; margin-bottom: 0.5rem; border-radius: 1rem; }
    .chat-bubble.sent { background-color: #e9ecef; color: #212529; margin-left: auto; border-bottom-right-radius: 0.25rem; }
    .chat-bubble.received { background-color: var(--bs-primary); color: white; margin-right: auto; border-bottom-left-radius: 0.25rem; }
    .chat-bubble .timestamp { font-size: 0.75rem; color: #6c757d; display: block; margin-top: 0.25rem; text-align: right; }
    .chat-bubble.received .timestamp { color: rgba(255,255,255,0.7); }
</style>

<?php include 'admin-header.php'; ?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <div>
        <h1 class="h2"><?php echo $page_title; ?></h1>
        <p class="text-muted">Conversation with <?php echo htmlspecialchars($conversation['full_name']); ?></p>
    </div>
    <a href="manage-messages.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to Conversations</a>
</div>

<div class="card shadow-sm border-0 chat-container">
    <div class="card-body">
        <div class="chat-box bg-light d-flex flex-column gap-2 mb-3">
            <?php foreach ($messages as $msg): ?>
                <div class="d-flex flex-column">
                    <div class="chat-bubble <?php echo ($msg['sender_type'] == 'admin') ? 'sent' : 'received'; ?>">
                        <?php echo nl2br(htmlspecialchars($msg['body'])); ?>
                        <span class="timestamp"><?php echo date('M d, g:i A', strtotime($msg['created_at'])); ?></span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <form method="POST">
            <div class="input-group">
                <textarea name="body" class="form-control" placeholder="Type your reply..." rows="3" required></textarea>
                <button class="btn btn-primary" type="submit" style="min-width: 100px;"><i class="bi bi-send-fill"></i> Send</button>
            </div>
        </form>
    </div>
</div>

<?php include 'admin-footer.php'; ?>
