<?php
require_once 'header.php'; 

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

// --- Handle New Message Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['body'])) {
    $body = trim($_POST['body']);
    // Insert the user's reply
    $stmt = $conn->prepare("INSERT INTO messages (conversation_id, sender_id, sender_type, body) VALUES (?, ?, 'user', ?)");
    $stmt->bind_param("iis", $conversation_id, $user_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-messages.php?id=$conversation_id"); // Refresh to show new message
    exit();
}

// Security Check: Make sure this conversation belongs to the logged-in user
$stmt = $conn->prepare("SELECT id, subject FROM conversations WHERE id = ? AND user_id = ?");
$stmt->bind_param("ii", $conversation_id, $user_id);
$stmt->execute();
$conversation = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$conversation) { header("Location: messages.php"); exit(); }
$page_title = 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; background-color: #f8f9fa; 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: var(--bs-primary); color: white; margin-left: auto; border-bottom-right-radius: 0.25rem; }
    .chat-bubble.received { background-color: #e9ecef; color: #212529; margin-right: auto; border-bottom-left-radius: 0.25rem; }
    .chat-bubble .timestamp { font-size: 0.75rem; color: rgba(255,255,255,0.7); display: block; margin-top: 0.25rem; text-align: right; }
    .chat-bubble.received .timestamp { color: #6c757d; }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><?php echo $page_title; ?></h1>
    <a href="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 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'] == 'user') ? '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 message here..." 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 require_once 'footer.php'; ?>
