<?php
session_start();
if (!isset($_SESSION['student_id'])) {
    die("Student not logged in.");
}

$studentId = $_SESSION['student_id'];

include('db_connection.php'); // Ensure this path is correct

function getOnlineFriends($studentId, $conn) {
    $onlineThreshold = 5 * 60; // 5 minutes threshold for being considered online
    $query = "SELECT s.student_id, s.name, p.profile_picture
              FROM student_friends sf
              JOIN students s ON sf.friend_id = s.student_id
              JOIN profiles p ON s.student_id = p.student_id
              WHERE sf.student_id = ? AND sf.status = 'Active' AND UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(sf.last_active) < ?";

    $stmt = $conn->prepare($query);
    if (!$stmt) {
        die("Error preparing statement: " . $conn->error);
    }

    $stmt->bind_param('ii', $studentId, $onlineThreshold);
    $stmt->execute();
    $result = $stmt->get_result();

    $onlineFriends = [];
    while ($row = $result->fetch_assoc()) {
        $onlineFriends[] = $row;
    }
    $stmt->close(); // Close the statement
    return $onlineFriends;
}

function getMessages($studentId, $conn) {
    $query = "SELECT sm.id, sm.sender_id, sm.receiver_id, sm.message, sm.timestamp, sm.status, sm.parent_message_id, p.name AS sender_name, p.profile_picture
              FROM student_messages sm
              JOIN profiles p ON sm.sender_id = p.student_id
              WHERE sm.receiver_id = ? 
              ORDER BY sm.timestamp DESC";

    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $studentId);
    $stmt->execute();
    $result = $stmt->get_result();

    $messages = [];
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }
    $stmt->close(); // Close the statement after use
    return $messages;
}

$onlineFriends = getOnlineFriends($studentId, $conn);
$messages = getMessages($studentId, $conn);

// Query to fetch online students
$sql = "SELECT * FROM profiles WHERE online_status = 1";
$result = $conn->query($sql);

// Check if there are any results
if ($result) {
    $onlineStudents = $result->fetch_all(MYSQLI_ASSOC);
} else {
    $onlineStudents = [];
}

// Don't close the connection here; do it after all operations are complete

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <title>Messages</title>
    <style>
      body {
            font-family: Arial, sans-serif;
            background-color: #18191a;
            color: #e4e6eb;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #242526;
            padding: 20px;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
        }

         .profile-pictures {
            display: flex;
            overflow-x: auto;
            padding: 10px;
            background-color: #242526;
        }

        .profile {
           position: relative;
    text-align: center;
    margin-right: 10px;
        }

        .profile img {
           width: 60px;
    height: 60px;
    border-radius: 50%;
    border: 2px solid #2e89ff;
        }

        .profile p {
               position: relative;
    text-align: center;
    margin-right: 10px;
        }
.status-indicator {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    border: 2px solid #fff;
    background-color: #ccc; /* Default color for offline */
}

.status-indicator.online {
    background-color: #00ff00; /* Green for online */
}

.status-indicator.offline {
    background-color: #ff0000; /* Red for offline */
}
        .messages {
            padding: 10px;
            background-color: #18191a;
        }

        .message-request {
            padding: 10px;
            background-color: #3a3b3c;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .message-request p {
            margin: 0;
            color: #2e89ff;
            font-weight: bold;
        }

        .message {
            display: flex;
            padding: 10px;
            background-color: #242526;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .message img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .message-details {
            flex: 1;
        }

        .message-details p {
            margin: 0;
            color: #e4e6eb;
        }

        .message-details p:first-child {
            font-weight: bold;
        }

        .message-details p:last-child {
            color: #b0b3b8;
        }

        @media (max-width: 768px) {
            .message {
                flex-direction: column;
                align-items: center;
                text-align: center;
            }

            .message img {
                margin-bottom: 10px;
            }

            .profile img {
                .profile-img {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    border: 2px solid #2e89ff;
            }
        }
.add-button {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #2e89ff;
            color: #fff;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            cursor: pointer;
        }

@media (max-width: 768px) {
    .profile-img {
        width: 50px;
        height: 50px;
    }

    .status-indicator {
        width: 12px;
        height: 12px;
    }
}
        @media (max-width: 480px) {
            .profile img {
                width: 40px;
                height: 40px;
            }

            .profile p {
                font-size: 10px;
            }

            .message-request, .message {
                padding: 8px;
            }

            .message img {
                width: 40px;
                height: 40px;
            }

            .message-details p:first-child {
                font-size: 14px;
            }

            .message-details p:last-child {
                font-size: 12px;
            }
            .add-button {
                width: 40px;
                height: 40px;
                font-size: 20px;
            }
             .status-indicator {
        width: 10px;
        height: 10px;
    }
        
        .read-receipt {
    font-size: 12px;
    color: #2e89ff;
}
}
    </style>
</head>
<body>
    <header>Messages</header>
    <div class="profile-pictures">
    <?php if (empty($onlineStudents)): ?>
        <p>No students online</p>
    <?php else: ?>
        <?php foreach ($onlineStudents as $student): ?>
            <?php
            $profilePic = htmlspecialchars($student['profile_picture']);
            $onlineStatus = htmlspecialchars($student['online_status']); // ENUM values: 'online' or 'offline'
            ?>
            <div class="profile">
                <!-- Assuming 'uploads' directory is relative to the script's location -->
                <img src="uploads/<?php echo $profilePic; ?>" alt="Profile Picture" class="profile-img">
                <div class="status-indicator <?php echo $onlineStatus; ?>"></div>
                <p><?php echo htmlspecialchars($student['name']); ?></p>
                <!-- Debugging if the image file is not found -->
                <?php if (!file_exists('uploads/' . $profilePic)): ?>
                    <p style="color: red;">Image not found: <?php echo $profilePic; ?></p>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
    <div class="messages">
    <div class="message-request">
        <p>New message requests</p>
    </div>
    <?php foreach ($messages as $message): ?>
        <a href="reply_message.php?sender_id=<?php echo htmlspecialchars($message['sender_id']); ?>&message_id=<?php echo htmlspecialchars($message['id']); ?>" class="message">
            <!-- Use the sender's profile picture -->
            <img src="uploads/<?php echo htmlspecialchars($message['profile_picture']); ?>" alt="Sender" class="message-img">
            <div class="message-details">
                <p><?php echo htmlspecialchars($message['sender_name']); ?></p>
                <p><?php echo htmlspecialchars($message['message']); ?></p>
                <?php if ($message['status'] == 'Read'): ?>
                    <p class="read-receipt">Read</p>
                <?php endif; ?>
                <?php if ($message['parent_message_id']): ?>
                    <?php
                    // Fetch parent message
                    $parentQuery = "SELECT message FROM student_messages WHERE id = ?";
                    $parentStmt = $conn->prepare($parentQuery);
                    $parentStmt->bind_param('i', $message['parent_message_id']);
                    $parentStmt->execute();
                    $parentResult = $parentStmt->get_result();
                    $parentMessage = $parentResult->fetch_assoc();
                    $parentStmt->close();
                    ?>
                    <div class="parent-message">
                        <p><strong>Message Replied To:</strong> <?php echo htmlspecialchars($parentMessage['message']); ?></p>
                    </div>
                <?php endif; ?>
            </div>
        </a>
    <?php endforeach; ?>
</div>
    <div class="add-button">
        <a href="compose_message.php">
            <i class="fas fa-plus"></i>
        </a>
    </div>
</body>
</html>
