<?php
header('Content-Type: application/json');
$response = ['success' => false, 'information' => null, 'message' => 'Tidak ada informasi terbaru.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) {
    http_response_code(401);
    $response['message'] = 'Sesi tidak valid.';
    echo json_encode($response);
    exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in get_latest_information.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id, title, content, image_filename FROM informations WHERE status = 'active' ORDER BY created_at DESC LIMIT 1");
    $stmt->execute();
    $information = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($information) {
        if (!empty($information['image_filename'])) {
            // Pastikan base_url() menghasilkan URL yang benar
            if (function_exists('base_url')) {
                 // Asumsi gambar ada di public/uploads/informations/
                $information['image_url'] = base_url('uploads/informations/' . rawurlencode($information['image_filename']));
            } else {
                // Fallback jika base_url tidak ada, mungkin perlu disesuaikan
                $information['image_url'] = '/uploads/informations/' . rawurlencode($information['image_filename']);
            }
        } else {
            $information['image_url'] = null;
        }

        $response['success'] = true;
        $response['information'] = $information;
        unset($response['message']);
    } else {
        $response['message'] = 'Tidak ada informasi aktif yang ditemukan.';
    }

} catch (\PDOException $e) {
    error_log("Get Latest Information DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("Get Latest Information General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
