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

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

$student_id = $_SESSION['student_id'];
$group_id = isset($_GET['group_id']) ? intval($_GET['group_id']) : 0;

// Debug: Check if student_id is set correctly
if (!$student_id) {
    die("Error: student_id is not set");
}

// Fetch group members to ensure the student is a member
$sql_check_membership = "SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ?";
$stmt_check_membership = $conn->prepare($sql_check_membership);
$stmt_check_membership->bind_param("ii", $group_id, $student_id);
$stmt_check_membership->execute();
$member_exists = $stmt_check_membership->fetch();
$stmt_check_membership->close();

if (!$member_exists) {
    echo "You are not a member of this group.";
    exit();
}

// Handle new message form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $message = trim($_POST['message']);
    if (!empty($message)) {
        $sql_insert_message = "INSERT INTO group_messages (group_id, sender_id, message) VALUES (?, ?, ?)";
        $stmt_insert_message = $conn->prepare($sql_insert_message);
        $stmt_insert_message->bind_param("iis", $group_id, $student_id, $message);
        $stmt_insert_message->execute();
        $stmt_insert_message->close();

        // Update notifications
        $sql_update_notifications = "INSERT INTO user_notifications (user_id, new_notifications, last_notification, notification_message) 
                                     VALUES (?, 1, CURRENT_TIMESTAMP, ?) 
                                     ON DUPLICATE KEY UPDATE 
                                         new_notifications = new_notifications + 1, 
                                         last_notification = CURRENT_TIMESTAMP, 
                                         notification_message = VALUES(notification_message)";
        $stmt_update_notifications = $conn->prepare($sql_update_notifications);
        $notification_message = "New message in group $group_id";
        $stmt_update_notifications->bind_param("is", $student_id, $notification_message);
        $stmt_update_notifications->execute();
        $stmt_update_notifications->close();
    }
}

// Handle reply form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply']) && isset($_POST['message_id'])) {
    $reply = trim($_POST['reply']);
    $message_id = intval($_POST['message_id']);
    if (!empty($reply)) {
        $sql_insert_reply = "INSERT INTO message_replies (message_id, sender_id, reply) VALUES (?, ?, ?)";
        $stmt_insert_reply = $conn->prepare($sql_insert_reply);
        $stmt_insert_reply->bind_param("iis", $message_id, $student_id, $reply);
        $stmt_insert_reply->execute();
        $stmt_insert_reply->close();

        // Update user notifications
        $sql_update_notifications = "INSERT INTO user_notifications (user_id, new_notifications, last_notification, notification_message) 
                                     VALUES (?, 1, CURRENT_TIMESTAMP, ?) 
                                     ON DUPLICATE KEY UPDATE 
                                         new_notifications = new_notifications + 1, 
                                         last_notification = CURRENT_TIMESTAMP, 
                                         notification_message = VALUES(notification_message)";
        $stmt_update_notifications = $conn->prepare($sql_update_notifications);
        $notification_message = "New reply in group $group_id";
        $stmt_update_notifications->bind_param("is", $student_id, $notification_message);
        $stmt_update_notifications->execute();
        $stmt_update_notifications->close();
    }
}

// Fetch messages and replies
$sql_messages = "SELECT gm.message_id, gm.sender_id, gm.message, gm.timestamp, s.name AS sender_name
                 FROM group_messages gm
                 JOIN students s ON gm.sender_id = s.student_id
                 WHERE gm.group_id = ?
                 ORDER BY gm.timestamp DESC";
$stmt_messages = $conn->prepare($sql_messages);
$stmt_messages->bind_param("i", $group_id);
$stmt_messages->execute();
$result_messages = $stmt_messages->get_result();

// Fetch replies
$messages_with_replies = [];
while ($message = $result_messages->fetch_assoc()) {
    $message_id = $message['message_id'];
    $sql_replies = "SELECT mr.reply_id, mr.sender_id, mr.reply, mr.timestamp, s.name AS sender_name
                    FROM message_replies mr
                    JOIN students s ON mr.sender_id = s.student_id
                    WHERE mr.message_id = ?
                    ORDER BY mr.timestamp";
    $stmt_replies = $conn->prepare($sql_replies);
    $stmt_replies->bind_param("i", $message_id);
    $stmt_replies->execute();
    $result_replies = $stmt_replies->get_result();
    $message['replies'] = $result_replies->fetch_all(MYSQLI_ASSOC);
    $messages_with_replies[] = $message;
}

$stmt_messages->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Group Messages</title>
    <style>
        /* Basic styling */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .container {
            width: 80%;
            margin: auto;
            overflow: hidden;
            position: relative;
        }
        .message, .reply {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 10px;
            padding: 10px;
        }
        .message.highlight {
            background-color: #e0f7fa; /* Light blue background for new replies */
        }
        .notification-icon {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 20px;
            cursor: pointer;
        }
        .notification-badge {
            background-color: red;
            color: white;
            border-radius: 50%;
            padding: 5px 10px;
            font-size: 14px;
        }
        .reply-form {
            margin-top: 10px;
        }
        .reply-form textarea {
            width: calc(100% - 22px);
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        .reply-form button {
            padding: 5px 10px;
            border: none;
            background-color: #3498db;
            color: #fff;
            border-radius: 3px;
            cursor: pointer;
        }
        .reply-form button:hover {
            background-color: #2980b9;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="notification-icon" id="notification-icon">
            Notifications <span class="notification-badge" id="notification-badge">0</span>
        </div>
        <h2>Group Messages</h2>
        <form action="message_group.php?group_id=<?php echo htmlspecialchars($group_id); ?>" method="post">
            <textarea name="message" rows="4" cols="50" placeholder="Type your message here..." required></textarea>
            <br>
            <button type="submit">Send</button>
        </form>

        <div id="messages-container">
            <!-- Messages will be loaded here -->
            <?php foreach ($messages_with_replies as $message): ?>
                <div class="message" data-message-id="<?php echo htmlspecialchars($message['message_id']); ?>">
                    <strong><?php echo htmlspecialchars($message['sender_name']); ?>:</strong>
                    <p><?php echo htmlspecialchars($message['message']); ?></p>
                    <small><?php echo htmlspecialchars($message['timestamp']); ?></small>
                    <button class="toggle-replies">Show Replies</button>
                    <div class="replies" style="display: none;">
                        <?php foreach ($message['replies'] as $reply): ?>
                            <div class="reply" data-reply-id="<?php echo htmlspecialchars($reply['reply_id']); ?>">
                                <strong><?php echo htmlspecialchars($reply['sender_name']); ?>:</strong>
                                <p><?php echo htmlspecialchars($reply['reply']); ?></p>
                                <small><?php echo htmlspecialchars($reply['timestamp']); ?></small>
                            </div>
                        <?php endforeach; ?>
                        <form class="reply-form" method="post" action="message_group.php?group_id=<?php echo htmlspecialchars($group_id); ?>">
                            <textarea name="reply" rows="2" placeholder="Type your reply here..." required></textarea>
                            <input type="hidden" name="message_id" value="<?php echo htmlspecialchars($message['message_id']); ?>">
                            <br>
                            <button type="submit">Reply</button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- JavaScript to handle toggling replies and notifications -->
    <script>
        document.querySelectorAll('.toggle-replies').forEach(button => {
            button.addEventListener('click', () => {
                const repliesDiv = button.nextElementSibling;
                if (repliesDiv.style.display === 'none') {
                    repliesDiv.style.display = 'block';
                } else {
                    repliesDiv.style.display = 'none';
                }
            });
        });

        document.getElementById('notification-icon').addEventListener('click', () => {
            // Reset notifications on click
            fetch('reset_notifications.php?user_id=<?php echo htmlspecialchars($student_id); ?>')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('notification-badge').innerText = '0';
                })
                .catch(error => console.error('Error resetting notifications:', error));
        });
    </script>
</body>
</html>
