<?php
session_start();
include('db_connection.php');
include('functions.php');

// Check if the student is logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: login.php");
    exit();
}

$student_id = $_SESSION['student_id'];

// Mark all unread messages as read
$sql_mark_read = "UPDATE student_messages SET status = 'Read' WHERE receiver_id = ? AND status = 'Unread'";
$stmt_mark_read = $conn->prepare($sql_mark_read);
$stmt_mark_read->bind_param("i", $student_id);
$stmt_mark_read->execute();
$stmt_mark_read->close();

// Fetch all messages received by the student with sender's name and parent message
$sql_messages = "SELECT sm.id, sm.sender_id, sm.message, sm.timestamp, sm.status, s.name AS sender_name, sm.parent_message_id
                 FROM student_messages sm
                 JOIN students s ON sm.sender_id = s.student_id
                 WHERE sm.receiver_id = ?
                 ORDER BY sm.timestamp DESC";
$stmt_messages = $conn->prepare($sql_messages);
$stmt_messages->bind_param("i", $student_id);
$stmt_messages->execute();
$result_messages = $stmt_messages->get_result();

// Fetch student profile information
$sql_profile = "SELECT name, profile_picture FROM students WHERE student_id = ?";
$stmt_profile = $conn->prepare($sql_profile);
$stmt_profile->bind_param("i", $student_id);
$stmt_profile->execute();
$stmt_profile->bind_result($name, $profile_picture);
$stmt_profile->fetch();
$stmt_profile->close();

// Define the path to the profile picture
$profile_picture_path = '/csms/student/uploads/profile_pictures/' . $profile_picture;

// Fetch pending friend requests count using a function if defined
$pending_requests_count = getPendingFriendRequestsCount($student_id);

// Fetch unread messages count using a function if defined
$unread_messages_count = getUnreadMessagesCount($student_id);

// Function to fetch message history
function fetchMessageHistory($conn, $message_id) {
    $history = [];
    while ($message_id) {
        $sql_history = "SELECT sm.id, sm.sender_id, sm.message, sm.timestamp, s.name AS sender_name, sm.parent_message_id
                        FROM student_messages sm
                        JOIN students s ON sm.sender_id = s.student_id
                        WHERE sm.id = ?";
        $stmt_history = $conn->prepare($sql_history);
        $stmt_history->bind_param("i", $message_id);
        $stmt_history->execute();
        $result_history = $stmt_history->get_result();
        if ($result_history->num_rows > 0) {
            $row = $result_history->fetch_assoc();
            array_unshift($history, $row);
            $message_id = $row['parent_message_id'];
        } else {
            break;
        }
    }
    return $history;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Messages</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .header {
            background-color: #34495e;
            color: #fff;
            padding: 15px;
            text-align: center;
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 1000;
        }
        .header .nav-links {
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
        .header .nav-links a, .header .nav-links .dropdown {
            color: #fff;
            text-decoration: none;
            padding: 10px 20px;
            font-weight: bold;
            position: relative;
        }
        .header .nav-links a:hover, .header .nav-links .dropdown:hover {
            background-color: #2c3e50;
            border-radius: 5px;
        }
        .header .dropdown-content {
            display: none;
            position: absolute;
            background-color: #fff;
            min-width: 200px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
            z-index: 1;
        }
        .header .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
        .header .dropdown-content a:hover {
            background-color: #ddd;
        }
        .header .dropdown:hover .dropdown-content {
            display: block;
        }
        .main-content {
            padding: 80px 20px 20px;
        }
        .widget {
            background: #fff;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .widget ul {
            list-style: none;
            padding: 0;
        }
        .widget li {
            margin-bottom: 10px;
        }
        .widget li span {
            display: block;
        }
        .widget .message {
            border-bottom: 1px solid #ddd;
            padding: 10px 0;
        }
        .widget .message.read {
            background-color: #f9f9f9;
        }
        .widget .message .history {
            font-style: italic;
            color: #666;
            margin-bottom: 10px;
        }
        .footer {
            background: #34495e;
            color: #fff;
            text-align: center;
            padding: 10px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="nav-links">
            <a href="dashboard.php">Home</a>
            <a href="view_profile.php">Profile</a>
            <div class="dropdown">
                <a href="#" class="dropdown-toggle">Messages
                    <?php if ($unread_messages_count > 0): ?>
                        <span class="notification-badge"><?php echo htmlspecialchars($unread_messages_count); ?></span>
                    <?php endif; ?>
                </a>
                <div class="dropdown-content">
                    <a href="messages.php">Compose Message</a>
                    <a href="view_message.php">View Messages</a>
                </div>
            </div>
            <div class="dropdown">
                <a href="#" class="dropdown-toggle">Friends
                    <?php if ($pending_requests_count > 0): ?>
                        <span class="notification-badge"><?php echo htmlspecialchars($pending_requests_count); ?></span>
                    <?php endif; ?>
                </a>
                <div class="dropdown-content">
                    <a href="friends.php">View Friends</a>
                    <a href="friend_requests.php">Friend Requests</a>
                    <a href="search_friends.php">Search Friends</a>
                </div>
            </div>
            <a href="groups.php">Groups</a>
            <a href="logout.php">Logout</a>
        </div>
    </div>

    <div class="main-content">
        <div class="widget">
            <h3>Messages</h3>
            <?php if ($result_messages->num_rows > 0): ?>
                <ul>
                    <?php while ($row = $result_messages->fetch_assoc()): ?>
                        <li class="message <?php echo $row['status'] === 'Read' ? 'read' : ''; ?>">
                            <strong>From: <?php echo htmlspecialchars($row['sender_name']); ?></strong>
                            <?php
                            $history = fetchMessageHistory($conn, $row['parent_message_id']);
                            foreach ($history as $hist) {
                                echo '<div class="history">';
                                echo '<strong>' . htmlspecialchars($hist['sender_name']) . ':</strong> ';
                                echo htmlspecialchars($hist['message']);
                                echo '</div>';
                            }
                            ?>
                            <p><?php echo htmlspecialchars($row['message']); ?></p>
                            <small><?php echo htmlspecialchars($row['timestamp']); ?></small>
                            <form action="reply_message.php" method="post">
                                <input type="hidden" name="receiver_id" value="<?php echo htmlspecialchars($row['sender_id']); ?>">
                                <input type="hidden" name="parent_message_id" value="<?php echo htmlspecialchars($row['id']); ?>">
                                <textarea name="message" required></textarea>
                                <button type="submit">Reply</button>
                            </form>
                        </li>
                    <?php endwhile; ?>
                </ul>
            <?php else: ?>
                <p>No messages found.</p>
            <?php endif; ?>
        </div>
    </div>

    <div class="footer">
        &copy; <?php echo date("Y"); ?> Your Website. All rights reserved.
    </div>
</body>
</html>
