<?php
session_start();
require_once __DIR__ . '/../config.php';

echo "<h2>Test Token Dashboard</h2>";

// Cek session
echo "<h3>1. Session Check:</h3>";
echo "<pre>";
echo "Session Token: " . ($_SESSION['token'] ?? 'TIDAK ADA') . "\n";
echo "User Data: " . json_encode($_SESSION['user_data'] ?? []) . "\n";
echo "</pre>";

// Cek token dari session
$token = $_SESSION['token'] ?? '';

if (empty($token)) {
    echo "<p style='color:red'>❌ Token tidak ada di session, coba login dulu</p>";
    echo "<a href='login.php'>Login</a>";
    exit;
}

echo "<p style='color:green'>✅ Token ditemukan: " . substr($token, 0, 20) . "...</p>";

// Test API berita dengan token dari session
echo "<h3>2. Test API Berita dengan Token Session:</h3>";
$berita_result = api_get_berita($token);

echo "<pre>";
echo "Success: " . ($berita_result['success'] ? 'YES' : 'NO') . "\n";
echo "HTTP Code: " . $berita_result['http_code'] . "\n";
echo "Raw Response: " . $berita_result['raw_response'] . "\n";
echo "</pre>";

if ($berita_result['success']) {
    echo "<p style='color:green'>✅ API berita berhasil dengan token session</p>";

    if (!empty($berita_result['data']['data'])) {
        echo "<p>Jumlah berita: " . count($berita_result['data']['data']) . "</p>";

        foreach (array_slice($berita_result['data']['data'], 0, 2) as $index => $item) {
            echo "<div style='border:1px solid #ccc;padding:10px;margin:10px 0;'>";
            echo "<h4>📅 " . htmlspecialchars($item['tanggal'] ?? '') . " — " . htmlspecialchars($item['judul'] ?? '') . "</h4>";
            echo "<p>" . nl2br(htmlspecialchars($item['isi'] ?? '')) . "</p>";
            echo "</div>";
        }
    }
} else {
    echo "<p style='color:red'>❌ API berita gagal dengan token session</p>";
}

// Test login fresh untuk bandingkan
echo "<h3>3. Test Login Fresh untuk Bandingkan:</h3>";
$login_result = api_login('Widia', 'qwerty5*');
if ($login_result['success']) {
    $fresh_token = $login_result['data']['token'];
    echo "<p style='color:green'>✅ Login fresh berhasil</p>";

    $fresh_berita_result = api_get_berita($fresh_token);
    echo "<pre>";
    echo "Fresh Token Success: " . ($fresh_berita_result['success'] ? 'YES' : 'NO') . "\n";
    echo "Fresh Token HTTP Code: " . $fresh_berita_result['http_code'] . "\n";
    echo "</pre>";

    if ($fresh_berita_result['success']) {
        echo "<p style='color:green'>✅ API berita berhasil dengan token fresh</p>";
    } else {
        echo "<p style='color:red'>❌ API berita gagal dengan token fresh</p>";
    }
} else {
    echo "<p style='color:red'>❌ Login fresh gagal</p>";
}
