<?php
require_once __DIR__ . '/../config.php';

echo "<h2>Simple Berita Test</h2>";

// Login fresh
$login_result = api_login('Widia', 'qwerty5*');
if ($login_result['success']) {
    $token = $login_result['data']['token'];
    echo "✅ Login berhasil<br>";

    // Call API directly
    $ch = curl_init(API_BASE . 'berita');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => ['token' => $token],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "HTTP Code: $httpCode<br>";
    echo "Raw Response: <pre>$response</pre>";

    $data = json_decode($response, true);
    echo "JSON Decode Success: " . (json_last_error() === JSON_ERROR_NONE ? 'YES' : 'NO') . "<br>";
    echo "JSON Error: " . json_last_error_msg() . "<br>";

    if ($data && isset($data['data'])) {
        echo "Data Count: " . count($data['data']) . "<br>";
        if (!empty($data['data'])) {
            $first = $data['data'][0];
            echo "First Item Judul: " . ($first['judul'] ?? 'N/A') . "<br>";
            echo "First Item Tanggal: " . ($first['tanggal'] ?? 'N/A') . "<br>";
        }
    }
} else {
    echo "❌ Login gagal: " . json_encode($login_result['data']);
}
