<?php
/**
 * ============================================================================
 * groups/ajax/group-actions.php - AJAX Handler for Group Actions
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = getUserId();
$action = $_POST['action'] ?? $_GET['action'] ?? '';
$groupId = intval($_POST['group_id'] ?? $_GET['group_id'] ?? 0);

if (!$action || !$groupId) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$database = new \App\Database();
$db = $database->getConnection();
$groupClass = new \App\Group($db);

try {
    switch ($action) {
        case 'join':
            $result = $groupClass->join($groupId, $userId);
            break;
            
        case 'leave':
            $result = $groupClass->leave($groupId, $userId);
            break;
            
        case 'approve_member':
            $memberId = intval($_POST['member_id'] ?? 0);
            $result = $groupClass->approveMember($groupId, $memberId, $userId);
            break;
            
        case 'reject_member':
            $memberId = intval($_POST['member_id'] ?? 0);
            $result = $groupClass->rejectMember($groupId, $memberId, $userId);
            break;
            
        case 'remove_member':
            $memberId = intval($_POST['member_id'] ?? 0);
            $result = $groupClass->removeMember($groupId, $memberId, $userId);
            break;
            
        case 'add_member':
            $memberId = intval($_POST['member_id'] ?? 0);
            $result = $groupClass->addMember($groupId, $memberId, $userId);
            break;
            
        case 'update_role':
            $memberId = intval($_POST['member_id'] ?? 0);
            $newRole = $_POST['role'] ?? 'member';
            
            if (!in_array($newRole, ['admin', 'moderator', 'member'])) {
                $result = ['success' => false, 'message' => 'Invalid role'];
            } else {
                $result = $groupClass->updateMemberRole($groupId, $memberId, $newRole, $userId);
            }
            break;
            
        case 'create_post':
            $content = trim($_POST['content'] ?? '');
            $mediaUrls = $_POST['media_urls'] ?? null;
            
            if (empty($content)) {
                $result = ['success' => false, 'message' => 'Post content is required'];
            } else {
                $result = $groupClass->createPost($groupId, $userId, $content, $mediaUrls);
            }
            break;
            
        case 'delete_post':
            $postId = intval($_POST['post_id'] ?? 0);
            $result = $groupClass->deletePost($postId, $userId, $groupId);
            break;
            
        case 'like_post':
            $postId = intval($_POST['post_id'] ?? 0);
            $result = $groupClass->likePost($postId, $userId);
            break;
            
        case 'toggle_pin':
            $postId = intval($_POST['post_id'] ?? 0);
            $result = $groupClass->togglePinPost($postId, $groupId, $userId);
            break;
            
        case 'comment':
            $postId = intval($_POST['post_id'] ?? 0);
            $content = trim($_POST['content'] ?? '');
            
            if (empty($content)) {
                $result = ['success' => false, 'message' => 'Comment cannot be empty'];
            } else {
                $result = $groupClass->commentOnPost($postId, $userId, $content);
            }
            break;
            
        case 'get_comments':
            $postId = intval($_POST['post_id'] ?? $_GET['post_id'] ?? 0);
            $comments = $groupClass->getPostComments($postId);
            
            // Add time_ago to each comment
            foreach ($comments as &$comment) {
                $comment['time_ago'] = timeAgo($comment['created_at']);
            }
            
            $result = [
                'success' => true,
                'comments' => $comments
            ];
            break;
            
        default:
            $result = ['success' => false, 'message' => 'Unknown action'];
    }
    
    echo json_encode($result);
    
} catch (Exception $e) {
    error_log("Group action error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred. Please try again.'
    ]);
}
?>