<?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;

    if (!$articleId) {
        json_response(['success' => false, 'error' => 'Article ID is required'], 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 internationally'], 400);
    }

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

    // Initialize publisher and publish to international platforms
    $publisher = new Publisher();
    $result = $publisher->publishToExternalPlatforms($articleId);

    if ($result) {
        // Get publishing statistics
        $publishingHistory = $publisher->getPublishingHistory($articleId);
        $successCount = count(array_filter($publishingHistory, function($h) {
            return $h['status'] === 'published';
        }));

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

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