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

// Helper function to calculate the time difference
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = [
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    ];
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

// Get the logged-in student's ID
$student_id = $_SESSION['student_id'];

// Check if student ID is set and valid
if (!$student_id) {
    die("Student ID not found. Please log in.");
}

$group_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Validate group ID
if ($group_id <= 0) {
    die("Invalid Group ID: Group ID must be a positive integer.");
}

// SQL query to get the latest post by the logged-in student
$sql = "SELECT p.post_id, p.group_id, p.student_id, p.post_content, p.timestamp, p.group_image, p.post_sender,
               IF(p.post_sender = 0, 'Anonymous sender', s.name) AS student_name, 
               s.profile_picture
        FROM group_posts p
        LEFT JOIN profiles s ON p.student_id = s.student_id
        WHERE p.group_id = ? AND (p.student_id = ? OR p.post_sender = ?)
        ORDER BY p.timestamp DESC
        LIMIT 2";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iii", $group_id, $student_id, $student_id);
$stmt->execute();
$result = $stmt->get_result();

// Prepare SQL query to fetch group image, name, type, and count members
$sql = "SELECT group_image, group_name, group_type, 
               (SELECT COUNT(*) FROM group_members WHERE group_id = ?) as total_members 
        FROM student_groups WHERE group_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $group_id, $group_id);
$stmt->execute();
$result_group = $stmt->get_result();

// Initialize variables with default values
$group_image = "default_image.png"; // Default image if no image is found
$group_name = "Group Name"; // Default group name if no name is found
$group_type = "public"; // Default group type if not found
$total_members = 0; // Default total members if not found

// Check if image, name, type, and members count are found
if ($result_group->num_rows > 0) {
    $row_group = $result_group->fetch_assoc();
    if (!empty($row_group['group_image'])) {
        $group_image = "uploads/" . htmlspecialchars($row_group['group_image']);
    }
    if (!empty($row_group['group_name'])) {
        $group_name = htmlspecialchars($row_group['group_name']);
    }
    if (!empty($row_group['group_type'])) {
        $group_type = htmlspecialchars($row_group['group_type']);
    }
    if (!empty($row_group['total_members'])) {
        $total_members = (int)$row_group['total_members'];
    }
} else {
    // Additional debugging information
    echo "Debugging Info: <br>";
    echo "Query: " . $sql . "<br>";
    echo "Group ID: " . $group_id . "<br>";
    die("No group found with the provided Group ID.");
}

// Fetch student profile information
$profile_sql = "SELECT name, profile_picture FROM profiles WHERE student_id = ?";
$profile_stmt = $conn->prepare($profile_sql);
$profile_stmt->bind_param("i", $student_id);
$profile_stmt->execute();
$profile_result = $profile_stmt->get_result();
$profile = $profile_result->fetch_assoc();

// Fetch group type
$group_sql = "SELECT group_type FROM student_groups WHERE group_id = ?";
$group_stmt = $conn->prepare($group_sql);
$group_stmt->bind_param("i", $group_id);
$group_stmt->execute();
$group_result = $group_stmt->get_result();
$group = $group_result->fetch_assoc();

// Default values if not found
$profile_picture = !empty($profile['profile_picture']) ? "uploads/" . htmlspecialchars($profile['profile_picture']) : "uploads/default_profile_picture.jpg";
$student_name = htmlspecialchars($profile['name']);
$group_type = !empty($group['group_type']) ? htmlspecialchars($group['group_type']) : "Public group";

// Close the database connection
$stmt->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 Interaction Section</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .header {
            text-align: center;
            padding: 20px;
            background-color: white;
        }
        .header img {
            width: 150px;
            height: 150px;
            border-radius: 50%;
        }
        .group-name {
            font-size: 24px;
            margin: 10px 0;
        }
        .group-details {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background-color: #f0f2f5;
        }
        .group-details span {
            font-size: 14px;
            color: #606770;
        }
        .tabs {
            display: flex;
            justify-content: space-around;
            border-bottom: 1px solid #ccc;
        }
        .tabs a {
            text-decoration: none;
            color: #606770;
            padding: 10px 20px;
            display: block;
        }
        .tabs a:hover {
            background-color: #e9ebee;
        }
        .tabs .active {
            border-bottom: 2px solid #1877f2;
            color: #1877f2;
        }
        .actions {
            display: flex;
            justify-content: center;
            padding: 20px;
            background-color: white;
        }
        .actions button {
            margin: 0 10px;
            padding: 10px 20px;
            font-size: 14px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .actions .invite {
            background-color: #1877f2;
            color: white;
        }
        .actions .share {
            background-color: #42b72a;
            color: white;
        }
 .containers {
            max-width: 800px;
            margin: 20px auto;
            background-color: white;
            border-radius: 5px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }
        .post-section {
            flex: 2;
            background-color: #fff;
            border-radius: 5px;
            padding: 10px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        .post-section input[type="text"] {
            width: 100%;
            padding: 10px;
            border-radius: 20px;
            border: 1px solid #ddd;
            outline: none;
        }
        .post-options {
            display: flex;
            justify-content: space-around;
            margin-top: 10px;
        }
        .post-options div {
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        .post-options div img {
            margin-right: 5px;
        }
        .about-section {
            flex: 1;
            margin-left: 20px;
        }
        .about-section .about {
            background-color: #fff;
            border-radius: 5px;
            padding: 10px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        .about-section .about span {
            display: block;
            margin-bottom: 5px;
            padding: 10px;
        }
        .about-section .about span img {
            vertical-align: middle;
            margin-right: 5px;
        }
       
 .post {
            width: 500px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            padding: 10px;
            padding-right: 50px;
            margin: 20px auto;

}
            
        .post-header {
            display: flex;
            align-items: center;
        }
        .post-header img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
        }
        .post-header .post-author {
            display: flex;
            flex-direction: column;
        }
        .post-header .post-author .name {
            font-weight: bold;
        }
        .post-header .post-author .details {
            font-size: 12px;
            color: gray;
        }
        .post-content {
            margin: 10px 0;
        }
        .post-content img {
            width: 100%;
            border-radius: 8px;
            margin-top: 10px;
        }
        .post-actions {
            display: flex;
            justify-content: space-around;
            padding: 10px 0;
            border-top: 1px solid #ddd;
        }
        .post-actions div {
            display: flex;
            align-items: center;
            cursor: pointer;
            color: gray;
        }
        .post-actions div i {
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
       <div class="header">
            <img src="<?php echo $group_image; ?>" alt="Group Image">
            <div class="group-name"><?php echo $group_name; ?></div>
        </div>
        <div class="group-details">
            <span><?php echo ucfirst($group_type); ?> group · <?php echo number_format($total_members); ?> members</span>
            <div class="member-avatars">
                <!-- Add member avatars here -->
            </div>
        </div>
        <div class="tabs">
            <a href="#">About</a>
            <a href="#" class="active">Discussion</a>
            <a href="#">Featured</a>
            <a href="#">People</a>
            <a href="#">Events</a>
            <a href="#">Media</a>
            <a href="#">Files</a>
        </div>
        <div class="actions">
            <button class="invite">Invite</button>
            <button class="share">Share</button>
            <button class="joined">Joined</button>
            <button class="more">...</button>
        </div>
    </div>

    <div class="containers">
        <div class="post-section">
           <input type="text" placeholder="Write something..." onclick="window.location.href='create_group_post.php?id=<?php echo $group_id; ?>';">

                   <div class="post-options">
                <div>
                    <i class="fas fa-user-secret"></i> Anonymous post
                </div>
                <div>
                    <i class="fas fa-photo-video"></i> Photo/video
                </div>
                <div>
                    <i class="fas fa-poll"></i> Poll
                </div>
            </div>
            
        </div>

        <div class="about-section">
            <div class="about">
                <span><i class="fas fa-globe"></i><?php echo ucfirst($group_type); ?> group</span>
                <span>Anyone can see who's in the group and what they post.</span>
                <span><i class="fas fa-eye"></i> Visible</span>
                <span>Anyone can find this group.</span>
            </div>
        </div>
    </div>

     <?php while ($row = $result->fetch_assoc()) { ?>
     <div class="post">
        <div class="post-header">
            <img src="<?php echo ($row['post_sender'] === 'Anonymous Sender') ? 'uploads/default_profile_picture.jpg' : (!empty($row['profile_picture']) ? 'uploads/' . htmlspecialchars($row['profile_picture']) : 'uploads/default_profile_picture.jpg'); ?>" alt="Profile Picture">

            <div class="post-author">
                <div class="name"><?php echo htmlspecialchars($row['student_name']); ?></div>
                <div class="details">
                    <span class="moderator">Moderator</span> · 
                    <span class="top-contributor">Top contributor</span> · 
                    <?php echo time_elapsed_string($row['timestamp']); ?>· <i class="fas fa-globe"></i><span class="more">...</span>
                </div>
            </div>
        </div>
 
        <div class="post-content">
        <p><?php echo htmlspecialchars($row['post_content']); ?></p>
    </div>
    <?php if (!empty($row['group_image'])) { ?>
    <div class="post-image">
        <img src="uploads/<?php echo htmlspecialchars($row['group_image']); ?>" alt="Post Image">
    </div>
    <?php } ?>
        <div class="post-actions">
            <div><i class="far fa-thumbs-up"></i> Like</div>
            <div><i class="far fa-comment"></i> Comment</div>
            <div><i class="fas fa-share"></i> Share</div>
        </div>
    </div>
<?php } ?>
</body>
</html>
