<?php
/**
 * ============================================================================
 * chat/create-group.php - Create Group Chat
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Create Group';
$userId = getUserId();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $groupName = trim($_POST['group_name'] ?? '');
    $memberIds = $_POST['members'] ?? [];
    
    if (empty($groupName)) {
        $_SESSION['error_message'] = 'Please enter a group name';
    } else {
        $chatClass = new \App\Chat($db);
        
        try {
            // Create group
            $chatId = $chatClass->createGroup($userId, $groupName, $memberIds);
            
            if ($chatId) {
                $_SESSION['success_message'] = 'Group created successfully';
                header('Location: ' . APP_URL . '/chat/one-on-one.php?chat_id=' . $chatId);
                exit();
            } else {
                $_SESSION['error_message'] = 'Failed to create group';
            }
        } catch (Exception $e) {
            $_SESSION['error_message'] = 'Error: ' . $e->getMessage();
        }
    }
}

// Get user's friends for member selection
$query = "SELECT 
            u.id,
            u.full_name,
            u.profile_picture
          FROM users u
          INNER JOIN friendships f ON (u.id = f.friend_id OR u.id = f.user_id)
          WHERE (f.user_id = :user_id OR f.friend_id = :user_id2)
          AND f.status = 'accepted'
          AND u.id != :user_id3
          ORDER BY u.full_name ASC";

$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userId);
$stmt->bindParam(':user_id2', $userId);
$stmt->bindParam(':user_id3', $userId);
$stmt->execute();

$friends = $stmt->fetchAll(PDO::FETCH_ASSOC);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-people"></i> Create Group Chat
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger">
                            <?php 
                            echo htmlspecialchars($_SESSION['error_message']); 
                            unset($_SESSION['error_message']);
                            ?>
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label for="group_name" class="form-label">Group Name *</label>
                            <input type="text" 
                                   class="form-control" 
                                   id="group_name" 
                                   name="group_name" 
                                   placeholder="Enter group name"
                                   required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Select Members</label>
                            
                            <?php if (empty($friends)): ?>
                                <div class="alert alert-info">
                                    <i class="bi bi-info-circle"></i> 
                                    You don't have any friends yet. 
                                    <a href="<?php echo APP_URL; ?>/friends/find-farmers.php">Find farmers to connect with</a>
                                </div>
                            <?php else: ?>
                                <div class="mb-2">
                                    <input type="text" 
                                           class="form-control" 
                                           id="searchMembers" 
                                           placeholder="Search members..."
                                           onkeyup="filterMembers()">
                                </div>
                                
                                <div class="border rounded p-3" style="max-height: 400px; overflow-y: auto;">
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" 
                                               type="checkbox" 
                                               id="selectAll"
                                               onchange="toggleSelectAll()">
                                        <label class="form-check-label fw-bold" for="selectAll">
                                            Select All
                                        </label>
                                    </div>
                                    
                                    <hr>
                                    
                                    <?php foreach ($friends as $friend): ?>
                                        <div class="form-check mb-2 member-item">
                                            <input class="form-check-input member-checkbox" 
                                                   type="checkbox" 
                                                   name="members[]" 
                                                   value="<?php echo $friend['id']; ?>"
                                                   id="member_<?php echo $friend['id']; ?>">
                                            <label class="form-check-label d-flex align-items-center gap-2" 
                                                   for="member_<?php echo $friend['id']; ?>">
                                                <img src="<?php echo getAvatarUrl($friend['profile_picture']); ?>" 
                                                     class="rounded-circle" 
                                                     width="30" height="30"
                                                     alt="<?php echo htmlspecialchars($friend['full_name']); ?>">
                                                <span class="member-name"><?php echo htmlspecialchars($friend['full_name']); ?></span>
                                            </label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                
                                <small class="text-muted">
                                    <i class="bi bi-info-circle"></i> 
                                    You can add more members later
                                </small>
                            <?php endif; ?>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-success">
                                <i class="bi bi-check-lg"></i> Create Group
                            </button>
                            <a href="<?php echo APP_URL; ?>/chat/" class="btn btn-secondary">
                                <i class="bi bi-x-lg"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function filterMembers() {
    const searchTerm = document.getElementById('searchMembers').value.toLowerCase();
    const memberItems = document.querySelectorAll('.member-item');
    
    memberItems.forEach(item => {
        const memberName = item.querySelector('.member-name').textContent.toLowerCase();
        if (memberName.includes(searchTerm)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const memberCheckboxes = document.querySelectorAll('.member-checkbox');
    
    memberCheckboxes.forEach(checkbox => {
        if (checkbox.closest('.member-item').style.display !== 'none') {
            checkbox.checked = selectAllCheckbox.checked;
        }
    });
}

// Update select all checkbox based on individual selections
document.addEventListener('DOMContentLoaded', function() {
    const memberCheckboxes = document.querySelectorAll('.member-checkbox');
    const selectAllCheckbox = document.getElementById('selectAll');
    
    memberCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const visibleCheckboxes = Array.from(memberCheckboxes).filter(cb => 
                cb.closest('.member-item').style.display !== 'none'
            );
            const checkedCount = visibleCheckboxes.filter(cb => cb.checked).length;
            
            selectAllCheckbox.checked = checkedCount === visibleCheckboxes.length && visibleCheckboxes.length > 0;
        });
    });
});
</script>

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