#!/usr/bin/env php
<?php
/**
 * Publishing Test Script
 * Tests Facebook publishing configuration and API calls
 */

// Set CLI environment
$_SERVER['REQUEST_METHOD'] = 'GET';

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/api/facebook.php';
require_once __DIR__ . '/api/publishing.php';

echo "=== BlogPostAI Publishing Test ===\n\n";

// Test 1: Database Connection
echo "1. Testing Database Connection...\n";
try {
    $db = Database::getInstance()->getConnection();
    echo "   ✓ Database connected successfully\n\n";
} catch (Exception $e) {
    echo "   ✗ Database connection failed: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Test 2: Check Facebook Settings
echo "2. Checking Facebook Settings...\n";
$stmt = $db->prepare("SELECT `key`, value_encrypted FROM settings WHERE section = 'facebook' OR (section='common' AND `key`='FB_ENABLED')");
$stmt->execute();
$settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($settings)) {
    echo "   ✗ No Facebook settings found\n\n";
} else {
    foreach ($settings as $setting) {
        $value = $setting['value_encrypted'];
        if (strpos($setting['key'], 'TOKEN') !== false || strpos($setting['key'], 'SECRET') !== false) {
            $value = substr($value, 0, 10) . '...';
        }
        echo "   - {$setting['key']}: $value\n";
    }
    echo "\n";
}

// Test 3: Test Facebook Service Connection
echo "3. Testing Facebook API Connection...\n";
try {
    $fbService = new FacebookService();
    $result = $fbService->testConnection();

    if ($result['success']) {
        echo "   ✓ Facebook connection successful!\n";
        if (isset($result['data'])) {
            echo "   Page Name: " . ($result['data']['page_name'] ?? 'N/A') . "\n";
            echo "   Page ID: " . ($result['data']['page_id'] ?? 'N/A') . "\n";
            echo "   Category: " . ($result['data']['category'] ?? 'N/A') . "\n";
        }
    } else {
        echo "   ✗ Facebook connection failed!\n";
        echo "   Error: " . $result['message'] . "\n";
        if (isset($result['error_code'])) {
            echo "   Error Code: " . $result['error_code'] . "\n";
        }
        if (isset($result['http_code'])) {
            echo "   HTTP Code: " . $result['http_code'] . "\n";
        }
    }
} catch (Exception $e) {
    echo "   ✗ Exception: " . $e->getMessage() . "\n";
}
echo "\n";

// Test 4: Test Publishing Service
echo "4. Testing Publishing Service (DRY RUN)...\n";
try {
    $publishService = new PublishingService();

    // Test with minimal data
    $testData = [
        'content' => 'This is a test post (not actually published)'
    ];

    echo "   Testing data validation...\n";
    if (!empty($testData['content'])) {
        echo "   ✓ Content field present\n";
    }

    // Check which platforms are enabled
    $stmt = $db->prepare("SELECT `key`, value_encrypted FROM settings WHERE section='common' AND `key` LIKE '%ENABLED'");
    $stmt->execute();
    $enabled = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo "\n   Enabled Platforms:\n";
    foreach ($enabled as $platform) {
        $status = $platform['value_encrypted'] === 'true' ? '✓' : '✗';
        echo "   $status " . str_replace('_ENABLED', '', $platform['key']) . "\n";
    }

} catch (Exception $e) {
    echo "   ✗ Exception: " . $e->getMessage() . "\n";
}
echo "\n";

// Test 5: Check publish_records table
echo "5. Checking Recent Publish Attempts...\n";
$stmt = $db->prepare("SELECT * FROM publish_records ORDER BY created_at DESC LIMIT 3");
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($records)) {
    echo "   No publish records found\n";
} else {
    foreach ($records as $record) {
        echo "   ---\n";
        echo "   Platform: " . $record['platform'] . "\n";
        echo "   Status: " . $record['status'] . "\n";
        echo "   Created: " . $record['created_at'] . "\n";
        if (!empty($record['error_message'])) {
            echo "   Error: " . $record['error_message'] . "\n";
        }
        if (!empty($record['response_data'])) {
            $response = json_decode($record['response_data'], true);
            if ($response) {
                echo "   Response: " . json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
            }
        }
    }
}
echo "\n";

echo "=== Test Complete ===\n";
