<?php
// API endpoint for notices
// This endpoint returns a list of notices for the frontend website
// Compatible with WordPress wp_remote_get() calls
// Accessible at: https://eportal.kkcp.gov.bd/api/notices

require_once __DIR__ . '/../includes/db.php';

header('Content-Type: application/json');

try {
    $pdo = getDBConnection();

    // Query notices - only active notices ordered by CreatedDate DESC
    $sql = "SELECT Id, Name, Description, CreatedDate, AttachmentUrl, Important
            FROM notices
            WHERE (IsActive IS NULL OR IsActive = 1)
            ORDER BY CreatedDate DESC";

    $stmt = $pdo->query($sql);
    $notices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format the notices to match the expected structure
    $formattedNotices = [];
    foreach ($notices as $notice) {
        $formattedNotice = new stdClass();

        // Map fields to lowercase names as expected by WordPress
        $formattedNotice->name = $notice['Name'] ?? '';
        $formattedNotice->createdDate = $notice['CreatedDate'] ?? '';

        // Format attachmentUrl - ensure it's properly formatted
        if (!empty($notice['AttachmentUrl'])) {
            // If it's already a full URL, use it as is
            if (strpos($notice['AttachmentUrl'], 'http') === 0) {
                $formattedNotice->attachmentUrl = $notice['AttachmentUrl'];
            } else {
                // Add base URL if the path is relative
                $formattedNotice->attachmentUrl = 'https://eportal.kkcp.gov.bd/' . ltrim($notice['AttachmentUrl'], '/');
            }
        } else {
            $formattedNotice->attachmentUrl = '';
        }

        $formattedNotices[] = $formattedNotice;
    }

    // Return the array directly (not wrapped in a response object)
    // This matches the format expected by the WordPress code
    echo json_encode($formattedNotices);

} catch (Exception $e) {
    // Return empty array on error
    http_response_code(500);
    echo json_encode([]);
}
?>
