<?php
/**
 * ============================================================================
 * groups/view.php - View Group Details
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$userId = getUserId();
$groupId = intval($_GET['id'] ?? 0);

if (!$groupId) {
    redirect('/groups/', 'Group not found', 'error');
}

$database = new Database();
$db = $database->getConnection();

// Get group details
$sql = "SELECT g.*, 
        u.full_name as creator_name,
        gm.role as user_role,
        gm.status as membership_status
        FROM groups g
        LEFT JOIN users u ON g.created_by = u.id
        LEFT JOIN group_members gm ON g.id = gm.group_id AND gm.user_id = ?
        WHERE g.id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userId, $groupId]);
$group = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$group) {
    redirect('/groups/', 'Group not found', 'error');
}

// Check if user is member
$isMember = !empty($group['user_role']);
$isAdmin = $group['user_role'] === 'admin';
$isModerator = in_array($group['user_role'], ['admin', 'moderator']);

// Get members
$sql = "SELECT gm.*, u.full_name, u.profile_picture
        FROM group_members gm
        JOIN users u ON gm.user_id = u.id
        WHERE gm.group_id = ? AND gm.status = 'active'
        ORDER BY 
            CASE gm.role 
                WHEN 'admin' THEN 1
                WHEN 'moderator' THEN 2
                ELSE 3
            END,
            u.full_name";
$stmt = $db->prepare($sql);
$stmt->execute([$groupId]);
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent posts
$sql = "SELECT gp.*, 
        u.full_name as author_name,
        u.profile_picture as author_avatar
        FROM group_posts gp
        JOIN users u ON gp.user_id = u.id
        WHERE gp.group_id = ?
        ORDER BY gp.is_pinned DESC, gp.created_at DESC
        LIMIT 20";
$stmt = $db->prepare($sql);
$stmt->execute([$groupId]);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = $group['group_name'];
include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
.group-cover {
    height: 300px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    position: relative;
    overflow: hidden;
}

.group-header {
    margin-top: -80px;
    position: relative;
    z-index: 10;
}

.group-avatar-large {
    width: 150px;
    height: 150px;
    border: 5px solid white;
    border-radius: 20px;
}

.member-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.post-card {
    border-radius: 10px;
}

.stat-card {
    text-align: center;
    padding: 15px;
    border-radius: 10px;
    background: #f8f9fa;
}
</style>

<div class="container-fluid p-0">
    <!-- Cover Photo -->
    <div class="group-cover" style="background: <?php echo $group['group_cover'] ? 'url(' . $group['group_cover'] . ') center/cover' : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'; ?>">
        <?php if (!$group['group_cover']): ?>
            <div class="d-flex align-items-center justify-content-center h-100">
                <i class="bi bi-people-fill text-white" style="font-size: 5rem; opacity: 0.3;"></i>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Group Header -->
    <div class="container">
        <div class="group-header">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="row align-items-end">
                        <div class="col-auto">
                            <?php if ($group['group_avatar']): ?>
                                <img src="<?php echo htmlspecialchars($group['group_avatar']); ?>" 
                                     class="group-avatar-large"
                                     alt="<?php echo htmlspecialchars($group['group_name']); ?>">
                            <?php else: ?>
                                <div class="group-avatar-large bg-light d-flex align-items-center justify-content-center">
                                    <i class="bi bi-people-fill text-muted" style="font-size: 4rem;"></i>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="col">
                            <h2 class="mb-1"><?php echo htmlspecialchars($group['group_name']); ?></h2>
                            <p class="text-muted mb-2">
                                <i class="bi bi-<?php echo $group['privacy'] === 'public' ? 'globe' : ($group['privacy'] === 'private' ? 'lock' : 'shield-lock'); ?>"></i>
                                <?php echo ucfirst($group['privacy']); ?> Group
                                <?php if ($group['category']): ?>
                                    • <?php echo ucwords(str_replace('_', ' ', $group['category'])); ?>
                                <?php endif; ?>
                            </p>
                            <p class="mb-0">
                                <strong><?php echo $group['member_count']; ?></strong> members
                            </p>
                        </div>
                        <div class="col-auto">
                            <?php if (!$isMember): ?>
                                <a href="<?php echo APP_URL; ?>/groups/join.php?id=<?php echo $groupId; ?>" 
                                   class="btn btn-primary">
                                    <i class="bi bi-plus-circle"></i> Join Group
                                </a>
                            <?php else: ?>
                                <div class="btn-group">
                                    <button class="btn btn-outline-secondary">
                                        <i class="bi bi-check-circle-fill text-success"></i> Joined
                                    </button>
                                    <button class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" 
                                            data-bs-toggle="dropdown">
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <?php if ($isAdmin): ?>
                                            <li><a class="dropdown-item" href="<?php echo APP_URL; ?>/groups/edit.php?id=<?php echo $groupId; ?>">
                                                <i class="bi bi-gear me-2"></i>Edit Group
                                            </a></li>
                                            <li><hr class="dropdown-divider"></li>
                                        <?php endif; ?>
                                        <li><a class="dropdown-item text-danger" href="#" onclick="leaveGroup(<?php echo $groupId; ?>); return false;">
                                            <i class="bi bi-box-arrow-right me-2"></i>Leave Group
                                        </a></li>
                                    </ul>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Navigation Tabs -->
            <ul class="nav nav-tabs mt-3" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" data-bs-toggle="tab" href="#posts">
                        <i class="bi bi-file-post"></i> Posts
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#about">
                        <i class="bi bi-info-circle"></i> About
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#members">
                        <i class="bi bi-people"></i> Members
                    </a>
                </li>
                <?php if ($isMember): ?>
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/chat/one-on-one.php?group_id=<?php echo $groupId; ?>">
                        <i class="bi bi-chat-dots"></i> Group Chat
                    </a>
                </li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</div>

<div class="container py-4">
    <div class="row">
        <!-- Main Content -->
        <div class="col-md-8">
            <div class="tab-content">
                <!-- Posts Tab -->
                <div class="tab-pane fade show active" id="posts">
                    <?php if ($isMember): ?>
                        <!-- Create Post -->
                        <div class="card border-0 shadow-sm mb-3">
                            <div class="card-body">
                                <div class="d-flex gap-2">
                                    <img src="<?php echo getAvatarUrl($_SESSION['profile_picture']); ?>" 
                                         class="rounded-circle" 
                                         width="40" height="40">
                                    <button class="btn btn-light flex-grow-1 text-start" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#createPostModal">
                                        Write something...
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Posts List -->
                    <?php if (!empty($posts)): ?>
                        <?php foreach ($posts as $post): ?>
                            <div class="card border-0 shadow-sm post-card mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-start mb-3">
                                        <img src="<?php echo getAvatarUrl($post['author_avatar']); ?>" 
                                             class="rounded-circle me-3" 
                                             width="45" height="45">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0"><?php echo htmlspecialchars($post['author_name']); ?></h6>
                                            <small class="text-muted">
                                                <?php echo timeAgo($post['created_at']); ?>
                                                <?php if ($post['is_pinned']): ?>
                                                    • <i class="bi bi-pin-fill"></i> Pinned
                                                <?php endif; ?>
                                            </small>
                                        </div>
                                    </div>
                                    
                                    <p><?php echo nl2br(htmlspecialchars($post['content'])); ?></p>
                                    
                                    <div class="d-flex gap-3 text-muted">
                                        <button class="btn btn-link text-decoration-none">
                                            <i class="bi bi-heart"></i> <?php echo $post['likes_count']; ?>
                                        </button>
                                        <button class="btn btn-link text-decoration-none">
                                            <i class="bi bi-chat"></i> <?php echo $post['comments_count']; ?>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="bi bi-file-post text-muted" style="font-size: 4rem;"></i>
                            <h5 class="mt-3">No posts yet</h5>
                            <p class="text-muted">Be the first to post in this group!</p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- About Tab -->
                <div class="tab-pane fade" id="about">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <h5>About This Group</h5>
                            <p><?php echo nl2br(htmlspecialchars($group['description'] ?? 'No description provided.')); ?></p>
                            
                            <?php if ($group['rules']): ?>
                                <hr>
                                <h6>Group Rules</h6>
                                <p><?php echo nl2br(htmlspecialchars($group['rules'])); ?></p>
                            <?php endif; ?>
                            
                            <hr>
                            <p class="mb-1">
                                <strong>Created by:</strong> <?php echo htmlspecialchars($group['creator_name']); ?>
                            </p>
                            <p class="mb-0">
                                <strong>Created:</strong> <?php echo date('F j, Y', strtotime($group['created_at'])); ?>
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Members Tab -->
                <div class="tab-pane fade" id="members">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <h5 class="mb-3">Members (<?php echo count($members); ?>)</h5>
                            
                            <?php foreach ($members as $member): ?>
                                <div class="d-flex align-items-center mb-3">
                                    <img src="<?php echo getAvatarUrl($member['profile_picture']); ?>" 
                                         class="member-avatar me-3">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-0">
                                            <?php echo htmlspecialchars($member['full_name']); ?>
                                            <?php if ($member['role'] === 'admin'): ?>
                                                <span class="badge bg-danger">Admin</span>
                                            <?php elseif ($member['role'] === 'moderator'): ?>
                                                <span class="badge bg-warning">Moderator</span>
                                            <?php endif; ?>
                                        </h6>
                                        <small class="text-muted">
                                            Joined <?php echo timeAgo($member['joined_at']); ?>
                                        </small>
                                    </div>
                                    <?php if ($isAdmin && $member['user_id'] != $userId): ?>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-link" data-bs-toggle="dropdown">
                                                <i class="bi bi-three-dots-vertical"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li><a class="dropdown-item" href="#" onclick="promoteMember(<?php echo $member['user_id']; ?>, 'moderator')">
                                                    <i class="bi bi-shield-check me-2"></i>Make Moderator
                                                </a></li>
                                                <li><a class="dropdown-item text-danger" href="#" onclick="removeMember(<?php echo $member['user_id']; ?>)">
                                                    <i class="bi bi-person-x me-2"></i>Remove
                                                </a></li>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sidebar -->
        <div class="col-md-4">
            <!-- Stats -->
            <div class="row g-2 mb-3">
                <div class="col-6">
                    <div class="stat-card">
                        <h4 class="mb-0"><?php echo $group['member_count']; ?></h4>
                        <small class="text-muted">Members</small>
                    </div>
                </div>
                <div class="col-6">
                    <div class="stat-card">
                        <h4 class="mb-0"><?php echo count($posts); ?></h4>
                        <small class="text-muted">Posts</small>
                    </div>
                </div>
            </div>
            
            <!-- Admins -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body">
                    <h6 class="mb-3">Admins</h6>
                    <?php foreach (array_filter($members, fn($m) => $m['role'] === 'admin') as $admin): ?>
                        <div class="d-flex align-items-center mb-2">
                            <img src="<?php echo getAvatarUrl($admin['profile_picture']); ?>" 
                                 class="rounded-circle me-2" 
                                 width="30" height="30">
                            <small><?php echo htmlspecialchars($admin['full_name']); ?></small>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
function leaveGroup(groupId) {
    if (confirm('Are you sure you want to leave this group?')) {
        window.location.href = '<?php echo APP_URL; ?>/groups/leave.php?id=' + groupId;
    }
}

function removeMember(userId) {
    if (confirm('Are you sure you want to remove this member?')) {
        // AJAX call to remove member
        $.post('<?php echo APP_URL; ?>/groups/ajax/remove-member.php', {
            group_id: <?php echo $groupId; ?>,
            user_id: userId
        }, function(response) {
            if (response.success) {
                location.reload();
            } else {
                alert('Failed to remove member');
            }
        });
    }
}

function promoteMember(userId, role) {
    $.post('<?php echo APP_URL; ?>/groups/ajax/update-role.php', {
        group_id: <?php echo $groupId; ?>,
        user_id: userId,
        role: role
    }, function(response) {
        if (response.success) {
            location.reload();
        } else {
            alert('Failed to update role');
        }
    });
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
?>