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

// Check if user is logged in
if (!isset($_SESSION['token'])) {
    header('Location: login.php');
    exit;
}

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

// Test token validity
$profile_test = api_get_profil($token);
if (!$profile_test['success']) {
    $login_result = api_login('Widia', 'qwerty5*');
    if ($login_result['success']) {
        $token = $login_result['data']['token'];
        $_SESSION['token'] = $token;
        $_SESSION['user_data'] = $login_result['data'];
        $user_data = $login_result['data'];
    } else {
        header('Location: login.php');
        exit;
    }
}

// Get berita ID from URL
$berita_id = $_GET['id'] ?? '';

// Get user profile data
$profile_result = api_get_profil($token);
$profile_data = $profile_result['success'] ? $profile_result['data'] : [];

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

// Extract user info
$pegawai = $profile_data['pegawai'] ?? $profile_data['data']['pegawai'] ?? $profile_data['data'] ?? [];
$user_name = $pegawai['nama_lengkap'] ?? $pegawai['nama'] ?? $user_data['nama'] ?? $user_data['nama_lengkap'] ?? 'User';
$user_jabatan = $pegawai['jabatan']['nama_jabatan'] ?? $pegawai['jabatan'] ?? $user_data['jabatan'] ?? $user_data['nama_jabatan'] ?? 'Karyawan';

// Find specific berita
$berita_item = null;
if (!empty($berita_data) && is_array($berita_data)) {
    $berita_items = $berita_data['data'] ?? $berita_data;
    if (is_array($berita_items)) {
        // Debug log
        error_log("Mencari berita dengan ID: " . $berita_id);
        error_log("Available items: " . json_encode(array_map(function ($item) {
            return ['id' => $item['id'] ?? 'NO_ID', 'judul' => $item['judul'] ?? 'NO_TITLE'];
        }, $berita_items)));

        foreach ($berita_items as $index => $item) {
            $item_id = $item['id'] ?? $item['berita_id'] ?? $index;
            if ($item_id == $berita_id) {
                $berita_item = $item;
                error_log("Berita ditemukan di index $index");
                break;
            }
        }

        // Fallback: jika ID tidak ditemukan, coba gunakan index
        if (!$berita_item && is_numeric($berita_id)) {
            $index = intval($berita_id);
            if (isset($berita_items[$index])) {
                $berita_item = $berita_items[$index];
                error_log("Berita ditemukan menggunakan index fallback: $index");
            }
        }

        if (!$berita_item) {
            error_log("Berita dengan ID $berita_id tidak ditemukan");
        }
    }
}

// Function untuk format tanggal Indonesia
function formatTanggalIndonesia($tanggal = null, $format = 'l, d F Y')
{
    $hari = ['Sunday' => 'Minggu', 'Monday' => 'Senin', 'Tuesday' => 'Selasa', 'Wednesday' => 'Rabu', 'Thursday' => 'Kamis', 'Friday' => 'Jumat', 'Saturday' => 'Sabtu'];
    $bulan = ['January' => 'Januari', 'February' => 'Februari', 'March' => 'Maret', 'April' => 'April', 'May' => 'Mei', 'June' => 'Juni', 'July' => 'Juli', 'August' => 'Agustus', 'September' => 'September', 'October' => 'Oktober', 'November' => 'November', 'December' => 'Desember'];

    if ($tanggal) {
        $tanggal_inggris = date($format, strtotime($tanggal));
    } else {
        $tanggal_inggris = date($format);
    }

    $tanggal_indonesia = str_replace(array_keys($hari), array_values($hari), str_replace(array_keys($bulan), array_values($bulan), $tanggal_inggris));
    return $tanggal_indonesia;
}
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1">
    <meta name="theme-color" content="#F2F2F7">
    <meta name="color-scheme" content="light">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <title>Bank BIJ — Informasi</title>
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars(site_public_asset('assets/images/bij_logo.png')); ?>">
    <link rel="stylesheet" href="<?php echo asset('css/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('css/tailwind.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('css/ios-app.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('fa-7.1.0-web/css/all.min.css'); ?>">
</head>

<body class="ios-app">
    <div class="mobile-frame p-4">
        <header class="ios-screen-head">
            <div class="ios-screen-head__row">
                <div class="bank-logo flex-shrink-0">
                    <img src="<?php echo asset('logo_bij3.png'); ?>" alt="Logo Bank BIJ">
                </div>
                <div class="ios-head-meta">
                    <h1 class="ios-head-brand">BPR <span class="ios-accent">Intan Jabar</span></h1>
                    <p class="ios-head-page">Detail informasi</p>
                </div>
                <div class="ios-head-user">
                    <span class="ios-head-name"><?php echo htmlspecialchars($user_name); ?></span>
                    <span class="ios-head-role"><?php echo htmlspecialchars($user_jabatan); ?></span>
                </div>
            </div>
        </header>

        <nav class="ios-nav-back" aria-label="Navigasi">
            <a href="dashboard.php"><i class="fas fa-chevron-left" aria-hidden="true"></i> Dashboard</a>
        </nav>

        <?php if ($berita_item): ?>
            <!-- Detail Berita -->
            <div class="dashboard-card p-4">
                <div class="mb-4">
                    <h2 class="text-xl font-bold text-gray-800 mb-2"><?php echo htmlspecialchars($berita_item['judul'] ?? 'Informasi'); ?></h2>
                    <div class="flex items-center text-sm text-gray-500 mb-4">
                        <i class="fas fa-calendar mr-2"></i>
                        <span><?php echo formatTanggalIndonesia($berita_item['tanggal'] ?? ''); ?></span>
                    </div>
                </div>

                <?php
                $beritaPhotoUrl = uploads_berita_url((string) ($berita_item['photo'] ?? ''));
                ?>
                <?php if ($beritaPhotoUrl !== ''): ?>
                    <div class="mb-6">
                        <img src="<?php echo htmlspecialchars($beritaPhotoUrl); ?>"
                            alt="<?php echo htmlspecialchars($berita_item['judul'] ?? ''); ?>"
                            class="w-full max-h-96 object-contain rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300"
                            style="min-height: 200px;"
                            onerror="this.style.display='none';">
                    </div>
                <?php endif; ?>

                <div class="prose max-w-none">
                    <div class="text-gray-700 leading-relaxed">
                        <?php
                        $isi = $berita_item['isi'] ?? 'Tidak ada konten';
                        // Bersihkan tag HTML yang tidak perlu, tapi biarkan line breaks
                        $isi = strip_tags($isi, '<br><p><strong><em><u><b><i>');
                        // Hapus tag p kosong
                        $isi = preg_replace('/<p[^>]*>\s*<\/p>/i', '', $isi);
                        // Hapus tag p yang hanya berisi whitespace
                        $isi = preg_replace('/<p[^>]*>\s+<\/p>/i', '', $isi);
                        // Convert line breaks
                        $isi = nl2br($isi);
                        echo $isi;
                        ?>
                    </div>
                </div>

                <div class="mt-6 pt-4 border-t border-gray-200">
                    <div class="flex items-center justify-between text-sm text-gray-500">
                        <span>Diterbitkan: <?php echo formatTanggalIndonesia($berita_item['tanggal'] ?? ''); ?></span>
                        <span>ID: <?php echo htmlspecialchars($berita_item['id'] ?? ''); ?></span>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <!-- Berita Tidak Ditemukan -->
            <div class="dashboard-card p-8 text-center">
                <i class="fas fa-exclamation-triangle text-gray-400 text-4xl mb-4"></i>
                <h2 class="text-xl font-bold text-gray-800 mb-2">Informasi Tidak Ditemukan</h2>
                <p class="text-gray-600 mb-4">Informasi yang Anda cari tidak ditemukan atau sudah tidak tersedia.</p>
                <p class="text-sm text-gray-500 mb-4">ID yang dicari: <code><?php echo htmlspecialchars($berita_id); ?></code></p>

                <!-- Tampilkan daftar berita yang tersedia -->
                <?php if (!empty($berita_data) && is_array($berita_data)): ?>
                    <?php
                    $berita_items = $berita_data['data'] ?? $berita_data;
                    if (is_array($berita_items) && count($berita_items) > 0):
                    ?>
                        <div class="mt-6">
                            <h3 class="text-lg font-semibold text-gray-800 mb-3">Berita yang Tersedia:</h3>
                            <div class="space-y-2 text-left">
                                <?php foreach ($berita_items as $index => $item): ?>
                                    <?php
                                    $item_id = $item['id'] ?? $item['berita_id'] ?? $index;
                                    $item_judul = $item['judul'] ?? 'Tanpa Judul';
                                    $item_tanggal = $item['tanggal'] ?? '';
                                    ?>
                                    <div class="p-3 bg-gray-50 rounded-lg">
                                        <a href="detail-info.php?id=<?php echo urlencode($item_id); ?>"
                                            class="block hover:bg-gray-100 p-2 rounded transition-colors">
                                            <div class="font-medium text-blue-800"><?php echo htmlspecialchars($item_judul); ?></div>
                                            <div class="text-sm text-gray-600">ID: <?php echo htmlspecialchars($item_id); ?> | Tanggal: <?php echo htmlspecialchars($item_tanggal); ?></div>
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>

                <div class="mt-6">
                    <a href="dashboard.php" class="inline-flex items-center px-4 py-3 bg-blue-700 text-white rounded-xl hover:bg-blue-800 transition-colors font-medium">
                        <i class="fas fa-arrow-left mr-2"></i> Kembali ke Dashboard
                    </a>
                </div>
            </div>
        <?php endif; ?>

        <!-- Related Information -->
        <div class="dashboard-card p-4 mt-4">
            <h3 class="text-lg font-bold text-gray-800 mb-3">Informasi Terkait</h3>
            <div class="space-y-3">
                <a href="#" class="block p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <h4 class="font-medium text-gray-800">Panduan Presensi Online</h4>
                    <p class="text-sm text-gray-600">Cara menggunakan sistem presensi online</p>
                </a>
                <a href="#" class="block p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <h4 class="font-medium text-gray-800">Kebijakan Cuti Karyawan</h4>
                    <p class="text-sm text-gray-600">Aturan dan prosedur pengajuan cuti</p>
                </a>
                <a href="#" class="block p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <h4 class="font-medium text-gray-800">Update Sistem</h4>
                    <p class="text-sm text-gray-600">Informasi terbaru tentang sistem</p>
                </a>
            </div>
        </div>

        <!-- Footer -->
        <div class="text-center mt-6 ios-foot">
            <p>© 2024 Bank BIJ • v2.4.1</p>
        </div>
    </div>

    <script>
        // Update time
        function updateTime() {
            const now = new Date();
            const timeString = now.toLocaleTimeString('id-ID', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
            const dateString = now.toLocaleDateString('id-ID', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });

            const timeElement = document.getElementById('current-time');
            const dateElement = document.getElementById('current-date');
            if (timeElement) timeElement.textContent = timeString;
            if (dateElement) dateElement.textContent = dateString;
        }

        // Update time every second
        setInterval(updateTime, 1000);
        updateTime();
    </script>
</body>

</html>