<?php 
session_start();
include('../../../includes/config.php');

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../../index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$thread_id = isset($_GET['thread_id']) ? (int)$_GET['thread_id'] : 0;

if ($thread_id <= 0) {
    die('Invalid thread ID.');
}

// Validate and normalize thread_id
$validate_stmt = $conn->prepare("
    SELECT id, thread_id 
    FROM messages 
    WHERE thread_id = ? OR id = ?
    LIMIT 1
");
$validate_stmt->bind_param("ii", $thread_id, $thread_id);
$validate_stmt->execute();
$validate_result = $validate_stmt->get_result();
$original = $validate_result->fetch_assoc();
$validate_stmt->close();

if (!$original) {
    die("Thread not found.");
}

// Fix missing thread_id by assigning it to original message
if (empty($original['thread_id'])) {
    $thread_id = $original['id'];
    $fix_stmt = $conn->prepare("UPDATE messages SET thread_id = ? WHERE id = ?");
    $fix_stmt->bind_param("ii", $thread_id, $thread_id);
    $fix_stmt->execute();
    $fix_stmt->close();
} else {
    $thread_id = $original['thread_id'];
}

// Fetch all messages in the thread (in chronological order)
$query = "
    SELECT m.*, u.username AS sender_name
    FROM messages m
    JOIN users u ON m.sender_id = u.id
    WHERE m.thread_id = ? AND (m.receiver_id = ? OR m.sender_id = ?)
    ORDER BY m.created_at ASC
";

$stmt = $conn->prepare($query);
$stmt->bind_param("iii", $thread_id, $user_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$messages = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (!$messages) {
    die('No messages found for this thread.');
}

$last_msg = end($messages);
$raw_subject = $messages[0]['subject'] ?? 'No Subject';
$thread_subject = htmlspecialchars($raw_subject);

// Determine receiver for reply (the opposite of current user)
$reply_receiver_id = ($last_msg['sender_id'] == $user_id) 
    ? $last_msg['receiver_id'] 
    : $last_msg['sender_id'];

// Mark all unread messages in this thread as read
$mark_stmt = $conn->prepare("
    UPDATE messages 
    SET is_read = 1 
    WHERE receiver_id = ? AND is_read = 0 AND thread_id = ?
");
$mark_stmt->bind_param("ii", $user_id, $thread_id);
$mark_stmt->execute();
$mark_stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Conversation: <?= htmlspecialchars($thread_subject) ?></title>
    <link rel="stylesheet" href="../../../css/messaging" />
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            display: flex;
            background-color: #f1f3f4;
            height: 100vh;
        }

        .sidebar {
            width: 240px;
            background-color: #fff;
            padding: 20px;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
        }

        .sidebar h3 {
            margin-bottom: 20px;
            color: #202124;
        }

        .sidebar a {
            display: block;
            color: #202124;
            padding: 10px 15px;
            margin-bottom: 8px;
            border-radius: 4px;
            text-decoration: none;
        }

        .sidebar a:hover,
        .sidebar a.active {
            background-color: #e8f0fe;
            color: #1a73e8;
        }

        .main-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }

        h2 {
            margin-top: 0;
        }

        .message {
            margin-bottom: 20px;
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.08);
        }

        .from-me { border-left: 4px solid #1a73e8; }
        .from-them { border-left: 4px solid #34a853; }

        .message .header {
            font-weight: bold;
            margin-bottom: 6px;
        }

        .message .time {
            font-weight: normal;
            font-size: 0.85em;
            color: #666;
            margin-left: 10px;
        }

        .message .body {
            margin-top: 8px;
            white-space: pre-wrap;
        }

        .attachment {
            margin-top: 8px;
            font-size: 0.95em;
        }

        .reply-form {
            margin-top: 30px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.08);
        }

        .reply-form textarea {
            width: 100%;
            height: 100px;
            padding: 10px;
            font-size: 1em;
            margin-bottom: 10px;
            resize: vertical;
        }

        .reply-form input[type="file"] {
            margin-bottom: 10px;
        }

        .reply-form input[type="submit"] {
            background-color: #1a73e8;
            color: white;
            padding: 10px 18px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .reply-form input[type="submit"]:hover {
            background-color: #155db2;
        }
    </style>
</head>
<body>

<!-- Sidebar -->
<div class="sidebar">
    <h3>Messaging</h3>
    <a href="inbox.php" class="active">Inbox</a>
    <a href="sent.php">Sent</a>
    <a href="compose.php">Compose</a>
</div>

<!-- Main Content -->
<div class="main-content">
    <h2>Conversation: <?= htmlspecialchars($thread_subject) ?></h2>

    <?php foreach ($messages as $msg): ?>
        <div class="message <?= $msg['sender_id'] == $user_id ? 'from-me' : 'from-them' ?>">
            <div class="header">
                <?= htmlspecialchars($msg['sender_name']) ?>
                <span class="time">(<?= date('Y-m-d H:i', strtotime($msg['created_at'])) ?>)</span>
            </div>
            <div class="body"><?= nl2br(htmlspecialchars($msg['body'])) ?></div>
            <?php if (!empty($msg['attachment'])): ?>
                <div class="attachment">
                    📎 Attachment:
                    <a href="../../../uploads/messages/<?= urlencode($msg['attachment']) ?>"
                       target="_blank"
                       download="<?= htmlspecialchars(basename($msg['attachment'])) ?>">
                        <?= htmlspecialchars(basename($msg['attachment'])) ?>
                    </a>
                </div>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>

    <!-- Reply Form -->
    <div class="reply-form">
        <h3>Reply</h3>
        <form action="send_message.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="receiver_id" value="<?= (int)$reply_receiver_id ?>">
            <input type="hidden" name="subject" value="<?= (stripos($thread_subject, 'Re:') === 0 ? $thread_subject : 'Re: ' . $thread_subject) ?>">
            <input type="hidden" name="parent_id" value="<?= (int)$last_msg['id'] ?>">
            <input type="hidden" name="thread_id" value="<?= (int)$thread_id ?>">

            <textarea name="body" placeholder="Write your reply..." required></textarea><br>
            <label>Attach file (optional): <input type="file" name="attachment" /></label><br>
            <input type="submit" value="Send Reply">
        </form>
    </div>
</div>

<script>
if (window.refreshMessageBadge) refreshMessageBadge();
</script>

</body>
</html>

<?php $conn->close(); ?>
