<?php
/**
 * ============================================================================
 * posts/share.php - Share Post API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();
$postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;
$shareContent = isset($_POST['content']) ? trim($_POST['content']) : '';

if (!$postId) {
    echo json_encode(['success' => false, 'error' => 'Invalid post ID']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $postClass = new \App\Post($db);
    
    // Get original post
    $originalPost = $postClass->getPost($postId, $userId);
    
    if (!$originalPost) {
        echo json_encode(['success' => false, 'error' => 'Post not found']);
        exit();
    }
    
    // Create share post
    $sharedContent = $shareContent ?: "Shared a post";
    $sharedPostId = $postClass->create(
        $userId, 
        $sharedContent, 
        'shared', 
        json_encode(['shared_post_id' => $postId]),
        'public'
    );
    
    if ($sharedPostId) {
        // Update shares count
        $query = "UPDATE posts SET shares_count = shares_count + 1 WHERE id = :post_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':post_id', $postId);
        $stmt->execute();
        
        echo json_encode([
            'success' => true,
            'shared_post_id' => $sharedPostId,
            'message' => 'Post shared successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to share post']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>