<?php
/**
 * ============================================================================
 * posts/create.php - Create Post API
 * ============================================================================
 */
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, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();

// Get POST data
$content = isset($_POST['content']) ? trim($_POST['content']) : '';
$visibility = isset($_POST['visibility']) ? $_POST['visibility'] : 'public';
$location = isset($_POST['location']) ? trim($_POST['location']) : null;

// Validate input
if (empty($content)) {
    echo json_encode(['success' => false, 'error' => 'Content cannot be empty']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $postClass = new \App\Post($db);
    
    // Handle image uploads
    $mediaUrls = [];
    if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
        $uploadDir = __DIR__ . '/../assets/uploads/posts/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $maxSize = 5 * 1024 * 1024; // 5MB
        
        foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $fileSize = $_FILES['images']['size'][$key];
                $fileType = $_FILES['images']['type'][$key];
                
                if ($fileSize > $maxSize) {
                    continue; // Skip files that are too large
                }
                
                if (!in_array($fileType, $allowedTypes)) {
                    continue; // Skip invalid file types
                }
                
                $extension = pathinfo($_FILES['images']['name'][$key], PATHINFO_EXTENSION);
                $filename = uniqid('post_') . '_' . time() . '.' . $extension;
                $uploadPath = $uploadDir . $filename;
                
                if (move_uploaded_file($tmpName, $uploadPath)) {
                    $mediaUrls[] = APP_URL . '/assets/uploads/posts/' . $filename;
                }
            }
        }
    }
    
    $postType = !empty($mediaUrls) ? 'image' : 'text';
    $mediaUrlsJson = !empty($mediaUrls) ? json_encode($mediaUrls) : null;
    
    // Create post
    $postId = $postClass->create($userId, $content, $postType, $mediaUrlsJson, $visibility, $location);
    
    if ($postId) {
        echo json_encode([
            'success' => true,
            'post_id' => $postId,
            'message' => 'Post created successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to create post']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>