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

// Simulate dashboard environment
if (!isset($_SESSION['token'])) {
    $login_result = api_login('Widia', 'qwerty5*');
    if ($login_result['success']) {
        $_SESSION['token'] = $login_result['data']['token'];
        $_SESSION['user_data'] = $login_result['data'];
    }
}

$token = $_SESSION['token'] ?? '';

// Get berita exactly like dashboard
$berita_result = api_get_berita($token);
$berita_data = $berita_result['success'] ? $berita_result['data'] : [];

echo "<h2>Dashboard Debug - Berita</h2>";

echo "<h3>API Result:</h3>";
echo "Success: " . ($berita_result['success'] ? 'YES' : 'NO') . "<br>";
echo "HTTP Code: " . $berita_result['http_code'] . "<br>";

echo "<h3>Data Analysis:</h3>";
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>Raw Data:</h3>";
echo "<pre>" . print_r($berita_data, true) . "</pre>";

echo "<h3>Dashboard Logic Test:</h3>";
if (!empty($berita_data) && is_array($berita_data)) {
    echo "✅ Condition passed - should show berita<br>";

    // Handle different data structures
    $berita_items = array_values($berita_data); // Convert to indexed array
    $berita_items = array_slice($berita_items, 0, 3);

    echo "Berita Items Count: " . count($berita_items) . "<br>";

    foreach ($berita_items 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: <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>";
}
