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

// Check if this is a valid request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'error' => 'Only POST method allowed'], 405);
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $articleId = $input['article_id'] ?? null;
    $selectedPlatforms = $input['platforms'] ?? [];

    if (!$articleId) {
        json_response(['success' => false, 'error' => 'Article ID is required'], 400);
    }

    if (empty($selectedPlatforms)) {
        json_response(['success' => false, 'error' => 'At least one platform must be selected'], 400);
    }

    // Verify article exists and is external
    $article = new Article();
    $articleData = $article->getById($articleId);

    if (!$articleData) {
        json_response(['success' => false, 'error' => 'Article not found'], 404);
    }

    if ($articleData['type'] !== 'external') {
        json_response(['success' => false, 'error' => 'Only external articles can be published to platforms'], 400);
    }

    if ($articleData['status'] !== 'published') {
        json_response(['success' => false, 'error' => 'Article must be published first'], 400);
    }

    // Initialize publisher and publish to selected platforms
    $publisher = new Publisher();
    $result = $publisher->publishToSelectedPlatforms($articleId, $selectedPlatforms);

    if ($result['success']) {
        // Get publishing statistics for selected platforms
        $publishingHistory = $publisher->getPublishingHistory($articleId);
        $selectedHistory = array_filter($publishingHistory, function($h) use ($selectedPlatforms) {
            return in_array($h['platform_id'], $selectedPlatforms);
        });

        $successCount = count(array_filter($selectedHistory, function($h) {
            return $h['status'] === 'published';
        }));

        json_response([
            'success' => true,
            'message' => 'Article published to selected platforms',
            'article_id' => $articleId,
            'article_title' => $articleData['title'],
            'platforms_published' => $successCount,
            'publishing_history' => array_values($selectedHistory),
            'results' => $result['results']
        ]);
    } else {
        json_response([
            'success' => false,
            'error' => 'Failed to publish to selected platforms',
            'article_id' => $articleId,
            'results' => $result['results']
        ], 500);
    }

} catch (Exception $e) {
    error_log("Selective publish API error: " . $e->getMessage());
    json_response(['success' => false, 'error' => 'Internal server error'], 500);
}
?>