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

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

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

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Please login first']);
    exit;
}

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

// Get action
$action = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING) ?? 
          filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
$groupId = filter_input(INPUT_POST, 'group_id', FILTER_VALIDATE_INT) ?? 
           filter_input(INPUT_GET, 'group_id', FILTER_VALIDATE_INT);

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

try {
    switch ($action) {
        
        // =============================================
        // MEMBERSHIP ACTIONS
        // =============================================
        
        case 'join':
            if (!$groupId) {
                $result = ['success' => false, 'message' => 'Group ID required'];
                break;
            }
            $result = $groupClass->join($groupId, $userId);
            break;
            
        case 'leave':
            if (!$groupId) {
                $result = ['success' => false, 'message' => 'Group ID required'];
                break;
            }
            $result = $groupClass->leave($groupId, $userId);
            break;
            
        case 'approve_member':
            $memberId = filter_input(INPUT_POST, 'member_id', FILTER_VALIDATE_INT);
            if (!$memberId || !$groupId) {
                $result = ['success' => false, 'message' => 'Member ID and Group ID required'];
                break;
            }
            $result = $groupClass->approveMember($groupId, $memberId, $userId);
            break;
            
        case 'reject_member':
            $memberId = filter_input(INPUT_POST, 'member_id', FILTER_VALIDATE_INT);
            if (!$memberId || !$groupId) {
                $result = ['success' => false, 'message' => 'Member ID and Group ID required'];
                break;
            }
            $result = $groupClass->rejectMember($groupId, $memberId, $userId);
            break;
            
        case 'remove_member':
            $memberId = filter_input(INPUT_POST, 'member_id', FILTER_VALIDATE_INT);
            if (!$memberId || !$groupId) {
                $result = ['success' => false, 'message' => 'Member ID and Group ID required'];
                break;
            }
            $result = $groupClass->removeMember($groupId, $memberId, $userId);
            break;
            
        case 'add_member':
            $memberId = filter_input(INPUT_POST, 'member_id', FILTER_VALIDATE_INT);
            if (!$memberId || !$groupId) {
                $result = ['success' => false, 'message' => 'Member ID and Group ID required'];
                break;
            }
            $result = $groupClass->addMember($groupId, $memberId, $userId);
            break;
            
        case 'update_role':
            $memberId = filter_input(INPUT_POST, 'member_id', FILTER_VALIDATE_INT);
            $role = filter_input(INPUT_POST, 'role', FILTER_SANITIZE_STRING);
            
            if (!$memberId || !$role || !$groupId) {
                $result = ['success' => false, 'message' => 'Member ID, role, and Group ID required'];
                break;
            }
            
            if (!in_array($role, ['admin', 'moderator', 'member'])) {
                $result = ['success' => false, 'message' => 'Invalid role'];
                break;
            }
            
            $result = $groupClass->updateMemberRole($groupId, $memberId, $role, $userId);
            break;
        
        // =============================================
        // POST ACTIONS
        // =============================================
        
        case 'create_post':
            $content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
            $mediaUrls = filter_input(INPUT_POST, 'media_urls', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
            
            if (empty($content) || !$groupId) {
                $result = ['success' => false, 'message' => 'Content and Group ID required'];
                break;
            }
            
            $result = $groupClass->createPost($groupId, $userId, $content, $mediaUrls);
            break;
            
        case 'delete_post':
            $postId = filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
            if (!$postId || !$groupId) {
                $result = ['success' => false, 'message' => 'Post ID and Group ID required'];
                break;
            }
            $result = $groupClass->deletePost($postId, $userId, $groupId);
            break;
            
        case 'like_post':
            $postId = filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
            if (!$postId) {
                $result = ['success' => false, 'message' => 'Post ID required'];
                break;
            }
            $result = $groupClass->likePost($postId, $userId);
            break;
            
        case 'toggle_pin':
            $postId = filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
            if (!$postId || !$groupId) {
                $result = ['success' => false, 'message' => 'Post ID and Group ID required'];
                break;
            }
            $result = $groupClass->togglePinPost($postId, $groupId, $userId);
            break;
            
        case 'comment':
            $postId = filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
            $content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
            
            if (!$postId || empty($content)) {
                $result = ['success' => false, 'message' => 'Post ID and content required'];
                break;
            }
            
            $result = $groupClass->commentOnPost($postId, $userId, $content);
            break;
            
        case 'get_comments':
            $postId = filter_input(INPUT_GET, 'post_id', FILTER_VALIDATE_INT) ?? 
                      filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
            
            if (!$postId) {
                $result = ['success' => false, 'message' => 'Post ID required'];
                break;
            }
            
            $comments = $groupClass->getPostComments($postId);
            
            // Format comments with time ago
            foreach ($comments as &$comment) {
                $comment['time_ago'] = timeAgo($comment['created_at']);
                $comment['profile_picture'] = getAvatarUrl($comment['profile_picture']);
            }
            
            $result = ['success' => true, 'comments' => $comments];
            break;
            
        default:
            $result = ['success' => false, 'message' => 'Invalid action'];
            break;
    }
    
    echo json_encode($result);
    
} catch (Exception $e) {
    error_log("Group action error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred']);
}