<?php
/**
 * ============================================================================
 * groups/ajax/post-actions.php - Enhanced Post CRUD Operations
 * ============================================================================
 */

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) {
    echo json_encode(['success' => false, 'message' => 'Action required']);
    exit;
}

$database = new \App\Database();
$db = $database->getConnection();
$groupClass = new \App\GroupEnhanced($db);
$media = new \App\Media();

try {
    switch ($action) {
        case 'create_post_with_media':
            $content = trim($_POST['content'] ?? '');
            $mediaUrls = [];
            
            if (empty($content) && empty($_FILES['images']) && empty($_FILES['video'])) {
                echo json_encode(['success' => false, 'message' => 'Post content or media required']);
                exit;
            }
            
            // Upload images if provided
            if (!empty($_FILES['images']['tmp_name'][0])) {
                $imageResult = $media->uploadImages($_FILES['images'], 'posts');
                if ($imageResult['success']) {
                    $mediaUrls = array_merge($mediaUrls, $imageResult['files']);
                }
            }
            
            // Upload video if provided
            if (!empty($_FILES['video']['tmp_name'])) {
                $videoResult = $media->uploadVideo($_FILES['video']);
                if ($videoResult['success']) {
                    $mediaUrls[] = $videoResult['url'];
                }
            }
            
            // Create post
            $result = $groupClass->createPost($groupId, $userId, $content, $mediaUrls);
            echo json_encode($result);
            break;
            
        case 'edit_post':
            $postId = intval($_POST['post_id'] ?? 0);
            $content = trim($_POST['content'] ?? '');
            
            if (empty($content)) {
                echo json_encode(['success' => false, 'message' => 'Content required']);
                exit;
            }
            
            $result = $groupClass->updatePost($postId, $userId, $content, $groupId);
            echo json_encode($result);
            break;
            
        case 'get_post':
            $postId = intval($_POST['post_id'] ?? $_GET['post_id'] ?? 0);
            $post = $groupClass->getPost($postId);
            
            if ($post) {
                echo json_encode([
                    'success' => true,
                    'post' => $post
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Post not found']);
            }
            break;
            
        case 'get_post_likes':
            $postId = intval($_POST['post_id'] ?? $_GET['post_id'] ?? 0);
            $likes = $groupClass->getPostLikes($postId);
            
            foreach ($likes as &$like) {
                $like['time_ago'] = timeAgo($like['created_at']);
            }
            
            echo json_encode([
                'success' => true,
                'likes' => $likes
            ]);
            break;
            
        case 'edit_comment':
            $commentId = intval($_POST['comment_id'] ?? 0);
            $content = trim($_POST['content'] ?? '');
            
            if (empty($content)) {
                echo json_encode(['success' => false, 'message' => 'Content required']);
                exit;
            }
            
            $result = $groupClass->updateComment($commentId, $userId, $content);
            echo json_encode($result);
            break;
            
        case 'delete_comment':
            $commentId = intval($_POST['comment_id'] ?? 0);
            $result = $groupClass->deleteComment($commentId, $userId, $groupId);
            echo json_encode($result);
            break;
            
        case 'ban_member':
            $memberId = intval($_POST['member_id'] ?? 0);
            $result = $groupClass->banMember($groupId, $memberId, $userId);
            echo json_encode($result);
            break;
            
        case 'unban_member':
            $memberId = intval($_POST['member_id'] ?? 0);
            $result = $groupClass->unbanMember($groupId, $memberId, $userId);
            echo json_encode($result);
            break;
            
        case 'get_analytics':
            $analytics = $groupClass->getGroupAnalytics($groupId, $userId);
            
            if ($analytics) {
                echo json_encode([
                    'success' => true,
                    'analytics' => $analytics
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Unauthorized or analytics unavailable']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Unknown action']);
    }
    
} catch (Exception $e) {
    error_log("Post action error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred: ' . $e->getMessage()
    ]);
}