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

requireLogin();

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

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $groupName = trim($_POST['group_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $privacy = $_POST['privacy'] ?? 'public';
    $category = $_POST['category'] ?? '';
    $rules = trim($_POST['rules'] ?? '');
    
    if (empty($groupName)) {
        $_SESSION['error_message'] = 'Group name is required';
    } else {
        try {
            // Handle avatar upload
            $avatarPath = null;
            if (isset($_FILES['group_avatar']) && $_FILES['group_avatar']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = __DIR__ . '/../assets/uploads/groups/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileName = uniqid() . '_' . basename($_FILES['group_avatar']['name']);
                $uploadFile = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['group_avatar']['tmp_name'], $uploadFile)) {
                    $avatarPath = 'assets/uploads/groups/' . $fileName;
                }
            }
            
            // Create group
            $sql = "INSERT INTO groups (group_name, description, group_avatar, privacy, category, rules, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?)";
            $stmt = $db->prepare($sql);
            $stmt->execute([$groupName, $description, $avatarPath, $privacy, $category, $rules, $userId]);
            
            $groupId = $db->lastInsertId();
            
            // Add creator as admin
            $sql = "INSERT INTO group_members (group_id, user_id, role, status)
                    VALUES (?, ?, 'admin', 'active')";
            $stmt = $db->prepare($sql);
            $stmt->execute([$groupId, $userId]);
            
            $_SESSION['success_message'] = 'Group created successfully!';
            header('Location: ' . APP_URL . '/groups/view.php?id=' . $groupId);
            exit;
            
        } catch (Exception $e) {
            error_log('Create group error: ' . $e->getMessage());
            $_SESSION['error_message'] = 'Failed to create group';
        }
    }
}

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 col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-plus-circle"></i> Create New Group
                    </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" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="group_name" class="form-label">
                                Group Name <span class="text-danger">*</span>
                            </label>
                            <input type="text" 
                                   class="form-control" 
                                   id="group_name" 
                                   name="group_name" 
                                   required
                                   maxlength="100"
                                   placeholder="e.g., Coffee Farmers Uganda">
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" 
                                      id="description" 
                                      name="description" 
                                      rows="4"
                                      placeholder="What is this group about?"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="category" class="form-label">Category</label>
                            <select class="form-select" id="category" name="category">
                                <option value="">Select a category</option>
                                <option value="coffee">Coffee</option>
                                <option value="maize">Maize</option>
                                <option value="sugar_cane">Sugar Cane</option>
                                <option value="beans">Beans</option>
                                <option value="vegetables">Vegetables</option>
                                <option value="poultry">Poultry</option>
                                <option value="dairy">Dairy</option>
                                <option value="livestock">Livestock</option>
                                <option value="general">General Farming</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="privacy" class="form-label">Privacy</label>
                            <select class="form-select" id="privacy" name="privacy">
                                <option value="public">Public - Anyone can join</option>
                                <option value="private">Private - Admin approval required</option>
                                <option value="secret">Secret - Invite only</option>
                            </select>
                            <small class="text-muted">
                                <i class="bi bi-info-circle"></i> 
                                Public groups appear in search. Private groups require approval. Secret groups are hidden.
                            </small>
                        </div>
                        
                        <div class="mb-3">
                            <label for="group_avatar" class="form-label">Group Avatar (Optional)</label>
                            <input type="file" 
                                   class="form-control" 
                                   id="group_avatar" 
                                   name="group_avatar"
                                   accept="image/*">
                            <div id="avatarPreview" class="mt-2"></div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="rules" class="form-label">Group Rules (Optional)</label>
                            <textarea class="form-control" 
                                      id="rules" 
                                      name="rules" 
                                      rows="3"
                                      placeholder="Enter group rules, one per line"></textarea>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-check-lg"></i> Create Group
                            </button>
                            <a href="<?php echo APP_URL; ?>/groups/" class="btn btn-outline-secondary">
                                <i class="bi bi-x-lg"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('group_avatar').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('avatarPreview');
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.innerHTML = `
                <img src="${e.target.result}" 
                     class="img-thumbnail" 
                     style="max-width: 200px; max-height: 200px;">
            `;
        };
        reader.readAsDataURL(file);
    } else {
        preview.innerHTML = '';
    }
});
</script>

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