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

echo "<h2>Debug Berita Direct</h2>";

// Login dulu
$login_result = api_login('Widia', 'qwerty5*');
if ($login_result['success']) {
    $token = $login_result['data']['token'];

    // Get berita
    $berita_result = api_get_berita($token);

    echo "<h3>Raw API Response:</h3>";
    echo "<pre>" . json_encode($berita_result, JSON_PRETTY_PRINT) . "</pre>";

    echo "<h3>Data Extraction:</h3>";
    $berita_data = $berita_result['success'] ? $berita_result['data'] : [];
    echo "Success: " . ($berita_result['success'] ? 'YES' : 'NO') . "<br>";
    echo "Data Type: " . gettype($berita_data) . "<br>";
    echo "Data Count: " . (is_array($berita_data) ? count($berita_data) : 'N/A') . "<br>";
    echo "Data Empty: " . (empty($berita_data) ? 'YES' : 'NO') . "<br>";

    echo "<h3>Data Content:</h3>";
    echo "<pre>" . json_encode($berita_data, JSON_PRETTY_PRINT) . "</pre>";

    echo "<h3>Test Display Logic:</h3>";
    if (!empty($berita_data) && is_array($berita_data)) {
        echo "✅ Condition passed - should show berita<br>";
        echo "<h4>Raw Array Structure:</h4>";
        echo "<pre>" . print_r($berita_data, true) . "</pre>";

        foreach (array_slice($berita_data, 0, 3) as $index => $berita) {
            echo "<div style='border: 1px solid #ccc; padding: 10px; margin: 5px 0;'>";
            echo "<strong>Berita " . (intval($index) + 1) . ":</strong><br>";
            echo "Raw berita item: <pre>" . print_r($berita, true) . "</pre>";
            echo "Judul: " . ($berita['judul'] ?? 'N/A') . "<br>";
            echo "Tanggal: " . ($berita['tanggal'] ?? 'N/A') . "<br>";
            echo "Isi: " . substr(strip_tags($berita['isi'] ?? 'N/A'), 0, 100) . "...<br>";
            echo "</div>";
        }
    } else {
        echo "❌ Condition failed - showing 'Tidak ada pengumuman'<br>";
        echo "Empty check: " . (empty($berita_data) ? 'TRUE' : 'FALSE') . "<br>";
        echo "Array check: " . (is_array($berita_data) ? 'TRUE' : 'FALSE') . "<br>";
    }
} else {
    echo "Login gagal: " . json_encode($login_result['data']);
}
